Re: IntegrityError at /userapp/detail/ NOT NULL constraint failed: userapp_profile.babyinfo_id

2021-05-31 Thread Hugh Frost
Hey bro,
i try to combine  two model forms in single view django views  
but i dnt knw how to work with this please check my below code and help me!

On Monday, May 31, 2021 at 11:15:29 PM UTC+5:30 Kasper Laudrup wrote:

> On 31/05/2021 18.46, Hugh Frost wrote:
> > Hii all,
> > I hv been struck in last 4 days please fix this error , i'm new to django
> >
>
> Instead of telling people how many days you've spent trying to fix the
> error, try spend some time on explaining what you've spent the days on
> doing and what you're trying to achieve.
>
> That will greatly improve your chances of getting help.
>
> Kind regards,
>
> Kasper Laudrup
>
>
> > -- 
> > You received this message because you are subscribed to the Google
> > Groups "Django users" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> > an email to django-users...@googlegroups.com
> > .
> > To view this discussion on the web visit
> > 
> https://groups.google.com/d/msgid/django-users/c753a468-0b45-4266-9094-213719986069n%40googlegroups.com
> > <
> https://groups.google.com/d/msgid/django-users/c753a468-0b45-4266-9094-213719986069n%40googlegroups.com?utm_medium=email_source=footer
> >.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3c8e630f-103b-4612-9cb8-955950953a7bn%40googlegroups.com.


Re: IntegrityError at /userapp/detail/ NOT NULL constraint failed: userapp_profile.babyinfo_id

2021-05-31 Thread Kasper Laudrup
On 31/05/2021 18.46, Hugh Frost wrote:
> Hii all,
> I hv been struck in last 4 days please fix this error , i'm new to django
>

Instead of telling people how many days you've spent trying to fix the
error, try spend some time on explaining what you've spent the days on
doing and what you're trying to achieve.

That will greatly improve your chances of getting help.

Kind regards,

Kasper Laudrup


> -- 
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users+unsubscr...@googlegroups.com
> .
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/c753a468-0b45-4266-9094-213719986069n%40googlegroups.com
> .

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e46ce62f-e92a-8efa-c49e-11c8036af6ff%40stacktrace.dk.


OpenPGP_signature
Description: OpenPGP digital signature


IntegrityError at /userapp/detail/ NOT NULL constraint failed: userapp_profile.babyinfo_id

2021-05-31 Thread Hugh Frost
Hii all,
I hv been struck in last 4 days please fix this error , i'm new to django

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c753a468-0b45-4266-9094-213719986069n%40googlegroups.com.
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User

from PIL import Image
# from package.models import Package
# from .models import BabyInfo,Profile
# from user_profile.models import BabyInfo
# Create your models here.
class UserOTP(models.Model):
	user = models.ForeignKey(User, on_delete = models.CASCADE)
	time_st = models.DateTimeField(auto_now = True)
	otp = models.SmallIntegerField()

def upload_profile_to(instance,filename):
	return f'profile_picture/{instance}/{filename}'

class BabyInfo(models.Model):
	MALE = 'male'
	FEMALE = 'female'
	BOTH = 'both'
	GENDER = (
('MALE','Male'),
('FEMALE','Female'),
('BOTH','both'),
)

	Y='yes'
	N='no'
	CHOICES = (
('Y', 'Yes'),
('N', 'No'),
)
	born_status = models.CharField(max_length=1, choices=CHOICES)
	gender = models.CharField(max_length=10, choices=GENDER, verbose_name="gender")
	story_name = models.CharField(max_length=100)
	baby_date = models.DateField()
	profile_pic = models.ImageField(upload_to = upload_profile_to, default = 'defaults/profile_pic.jpg')
	# package=models.ForeignKey(Package,on_delete=models.CASCADE)
	created = models.DateTimeField(verbose_name=('Created'),auto_now_add=True)
	updated = models.DateTimeField(verbose_name=('Updated'),auto_now=True)

	class Meta:
		verbose_name = ('BabyInfo')
		verbose_name_plural = ('BabyInfos')
		ordering = ['-created']

	def __str__(self):
		return self.story_name


class Profile(models.Model):
	user = models.OneToOneField(User, on_delete = models.CASCADE,)
	profile_pic = models.ImageField(upload_to = upload_profile_to, null=True)
	# cover_image = models.ImageField(upload_to = 'upload_cover_to', null = True, default= 'defaults/cover_image.jpg')
	name=models.CharField(max_length=250)
	mail_id=models.EmailField()
	relationship=models.CharField(max_length=100)
	phone_no=models.IntegerField()
	is_lead_user=models.BooleanField(('Is LEAD USER'),help_text='button to toggle employee lead and aditional',default=False)
	babyinfo=models.ForeignKey(BabyInfo,on_delete=models.CASCADE,null=True)
	created = models.DateTimeField(verbose_name=('Created'),auto_now_add=True,null=True)
	updated = models.DateTimeField(verbose_name=('Updated'),auto_now=True,null=True)

	class Meta:
		verbose_name = ('Profile')
		verbose_name_plural = ('Profiles')
		ordering = ['-created']

	def __str__(self):
		return self.mail_id

	def save(self, *args, **kwargs):
		super().save(*args, **kwargs)

		img = Image.open(self.profile_pic.path)
		if img.height > 300 or img.width > 300:
			output_size = (300, 300)
			img.thumbnail(output_size)
			img.save(self.profile_pic.path)

		img2 = Image.open(self.cover_image.path)
		if img2.height > 500 or img2.width > 500:
			output_size = (500, 500)
			img2.thumbnail(output_size)
			img2.save(self.cover_image.path)
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django import forms
# Create your views here.
# from .forms import Profile
from userapp.models import BabyInfo,Profile,UserOTP
from userapp.forms import BabyForm1,BabyForm2


from django.contrib import messages
import random
from .forms import SignUpForm
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.conf import settings
from django.http import HttpResponse, Http404, JsonResponse
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def page(request):
return render(request,'userapp_temp/landing_page.html')

def home(request):
return render(request,'userapp_temp/home.html',)

# def index(request):
# return render(request, 'userapp_temp/index.html', {'title':'index'})

# def login(request):
# return render(request,'userapp_temp/login.html')
#
# def register(request):
# return render(request,'userapp_temp/signup.html')

def profile(request):
return render(request,'userapp_temp/profile.html')


#(BABY_PROFILE)#
def detail(request):
if request.method == 'POST':
baby_form1 = BabyForm1(data=request.POST)
  

IntegrityError on a foreign key constraint

2021-01-30 Thread degnon...@gmail.com
Hi, I'm having a really incomprehensible error currently. We are working 
with three models here, "DataImport", "Contact" and "Dataset", the 
DataImport model import data from a file to a Dataset object, the data is 
imported as a Contact object , the DataImport model have a foreign key to 
the Dataset model. This is how the app works:

- a user upload a file
- we convert the content of the file to a TablibDataset or TablibDatabook, 
these are tablib (python package) classes, don't worry too much about this, 
tablib have their own Dataset and I have my own, that's why I import the 
tablib classes with aliases
- if the loaded data is a TablibDataset, the import start and create 
contacts from the loaded data (this works)
- if the loaded_data is a TablibDatabook, the databook is split into 
multiple sheet (yes I'm working with excel files) and new Dataset (my 
model)  and DataImport objects are created to handle the import for each  
sheet (here is the issue)

All import are done as async task using the django_q package
The issue I have is that, when I create a new dataset, start the import and 
try to add a new contact I get this:
```
insert or update on table "datasets_contact" violates foreign key 
constraint "datasets_contact_dataset_id_9dda7f76_fk_datasets_dataset_id"
DETAIL:  Key (dataset_id)=(39) is not present in table "datasets_dataset".
```
It seems like the dataset is not save in db that's why I'm getting this 
error when I try to create a new contact, but I'm creating my Dataset 
object with Dataset.objects.create(), I don't understand the problem.

The code for all this is a bit long, so here is a gist with all the 
necessary code 
https://gist.github.com/Tobi-De/411ee7b7fc988864869c8d7ad93ab34f

The method that create the Dataset and DataImpot objects is the class 
method "create_import_from_databook"

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/dbfc0761-347d-47a5-9689-9886ce1e37fcn%40googlegroups.com.


IntegrityError - null value in column "email" violates not-null constraint

2020-08-04 Thread Francisco André
Hey guys.

I'm developing a new project and creating a custom user model, extending 
the AbstractBaseUser class, but when add a new user in admin interface or 
modelform I get the error: IntegrityError at /null value in column "email" 
violates not-null constraint.

The field email is necessary and I inform in the form, it's used to login 
too.

It's necessary create a "custom modelform" too? I followed many  tutorials 
by web, including documentation. Links bellow.

https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#custom-users-admin-full-example
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractbaseuser

And, this my gist code of model, form and admin file.

https://gist.github.com/fandrefh/ff6d8bbe047654174aa699072589539a

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2a69ebc6-cf63-4e67-8178-973b29818ac7o%40googlegroups.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-31 Thread Sunday Iyanu Ajayi
You will need to login into the database admin page ( maybe pgadmin ) to
update the user_id . From your model, user_id  can't be null
*AJAYI Sunday *
(+234) 806 771 5394
*sunnexaj...@gmail.com *



On Thu, Jul 30, 2020 at 11:58 AM Dinolin yp job 
wrote:

>
>
> It worked but the user_id in uploads_upload is empty. How can I can make
> that work?
> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com
> wrote:
>
>> From the error, it states that you are trying to add an upload object to
>> the database without a user. And from your model.py, the User foreign key
>> does not have a null=True, and blank=True. So you can't save a null value
>> for that user field.
>>
>> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
>> wrote:
>>
>>> I'm trying to save image in postgres database. I have upload model which
>>> has a foreign key reference to the extended custom user model. But it shows
>>> the following error
>>>
>>>
>>> uploads/model.py
>>> from django.db import models
>>> from django.contrib.auth import get_user_model
>>>
>>> User = get_user_model()
>>>
>>> class Upload(models.Model):
>>> upload_file = models.ImageField(upload_to='uploads/')
>>> upload_date = models.DateTimeField(auto_now_add =True)
>>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>>
>>>
>>> What am I missing? Thanks in advance
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/57100db3-81b7-49ca-86e6-096c121c94c8n%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAKYSAw0noinV2U%2BBCYCEc_dSbYxY7RFLwyrKKpxQWqy%2BfuW%2BNA%40mail.gmail.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-31 Thread oba stephen
Good to know..

Cheers!

On Fri, Jul 31, 2020 at 7:21 AM Dinolin yp job 
wrote:

> Thanks a lot @obastephen it worked.
>
> On Friday, July 31, 2020 at 12:32:47 AM UTC+5:30 obast...@gmail.com wrote:
>
>> irst in your UploadSerializer fields use fields = "__all__"
>>
>> Then you can use this in your views:
>>
>> *def post(self, **request, format=None**):*
>> *upload_file = request.data.get("upload_file"**)*
>> *upload_date = **request.data.get("upload_date"**)*
>>
>>
>> *user = request.userdata = {'upload_file': upload_file,
>> 'upload_date': upload_date, 'user': user}*
>> *serializer = **UploadSerializer**(data=data)*
>>
>>
>>
>>
>> *if serializer.is_valid():serializer.save()
>>   return Response(serializer.data, status=status.HTTP_201_CREATED)
>> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
>> On Thu, Jul 30, 2020 at 5:59 PM Dinolin yp job 
>> wrote:
>>
>>> I don't have forms.py since I'm creating only the endpoints using rest
>>> framework. I've done it earlier and it has worked but earlier the foreign
>>> key was to refer the default User model but now I have customized User
>>> model by extending AbstractBaseUser.
>>>
>>> uploads/views.py
>>>
>>>
>>>
>>>
>>>
>>>
>>> *class UploadView(APIView):def post(self, request,
>>> format=None):serializer =
>>> UploadSerializer(data=request.data)if
>>> serializer.is_valid():serializer.save()return
>>> Response(serializer.data, status=status.HTTP_201_CREATED)return
>>> Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
>>>
>>> uploads/serializers.py
>>>
>>>
>>>
>>> *class UploadSerializer(serializers.ModelSerializer):class Meta:
>>> model = Uploadfields = ('upload_file', 'upload_date')*
>>>
>>> users/models.py
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *class User(AbstractBaseUser):user_id =
>>> models.AutoField(primary_key=True)username =
>>> models.CharField(max_length=50, unique=True)first_name =
>>> models.CharField(max_length=50)last_name =
>>> models.CharField(max_length=50)company_name =
>>> models.CharField(max_length=100)email =
>>> models.EmailField(max_length=150, unique=True)is_active =
>>> models.BooleanField(default=True)is_superuser =
>>> models.BooleanField(default=False)objects = UserManager()
>>> USERNAME_FIELD = 'username'REQUIRED_FIELDS = ['first_name',
>>> 'last_name', 'company_name', 'email']def get_full_name(self):
>>> return self.first_name + self.last_name*
>>>
>>>
>>> On Thursday, July 30, 2020 at 7:59:38 PM UTC+5:30 obast...@gmail.com
>>> wrote:
>>>
 You can create an upload form with an Image field, then when saving the
 for set the User field to request.user.

 Do you have an UploadForm already in your forms.py? if yes, show me
 with the view that handles.

 On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job 
 wrote:

>
>
> It worked but user_id column in uploads_upload table is empty. How to
> solve this issue?
> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com
> wrote:
>
>> From the error, it states that you are trying to add an upload object
>> to the database without a user. And from your model.py, the User foreign
>> key does not have a null=True, and blank=True. So you can't save a null
>> value for that user field.
>>
>> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
>> wrote:
>>
>>> I'm trying to save image in postgres database. I have upload model
>>> which has a foreign key reference to the extended custom user model. 
>>> But it
>>> shows the following error
>>>
>>>
>>> uploads/model.py
>>> from django.db import models
>>> from django.contrib.auth import get_user_model
>>>
>>> User = get_user_model()
>>>
>>> class Upload(models.Model):
>>> upload_file = models.ImageField(upload_to='uploads/')
>>> upload_date = models.DateTimeField(auto_now_add =True)
>>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>>
>>>
>>> What am I missing? Thanks in advance
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it,
>>> send an email to django-users...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group 

Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-31 Thread Dinolin yp job
Thanks a lot @obastephen it worked.

On Friday, July 31, 2020 at 12:32:47 AM UTC+5:30 obast...@gmail.com wrote:

> irst in your UploadSerializer fields use fields = "__all__"
>
> Then you can use this in your views:
>
> *def post(self, **request, format=None**):*
> *upload_file = request.data.get("upload_file"**)*
> *upload_date = **request.data.get("upload_date"**)*
>
>
> *user = request.userdata = {'upload_file': upload_file, 
> 'upload_date': upload_date, 'user': user}*
> *serializer = **UploadSerializer**(data=data)*
>
>
>
>
> *if serializer.is_valid():serializer.save()
> return Response(serializer.data, status=status.HTTP_201_CREATED)
> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
> On Thu, Jul 30, 2020 at 5:59 PM Dinolin yp job  
> wrote:
>
>> I don't have forms.py since I'm creating only the endpoints using rest 
>> framework. I've done it earlier and it has worked but earlier the foreign 
>> key was to refer the default User model but now I have customized User 
>> model by extending AbstractBaseUser. 
>>
>> uploads/views.py
>>
>>
>>
>>
>>
>>
>> *class UploadView(APIView):def post(self, request, 
>> format=None):serializer = 
>> UploadSerializer(data=request.data)if 
>> serializer.is_valid():serializer.save()return 
>> Response(serializer.data, status=status.HTTP_201_CREATED)return 
>> Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
>>
>> uploads/serializers.py
>>
>>
>>
>> *class UploadSerializer(serializers.ModelSerializer):class Meta:
>> model = Uploadfields = ('upload_file', 'upload_date')*
>>
>> users/models.py
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> *class User(AbstractBaseUser):user_id = 
>> models.AutoField(primary_key=True)username = 
>> models.CharField(max_length=50, unique=True)first_name = 
>> models.CharField(max_length=50)last_name = 
>> models.CharField(max_length=50)company_name = 
>> models.CharField(max_length=100)email = 
>> models.EmailField(max_length=150, unique=True)is_active = 
>> models.BooleanField(default=True)is_superuser = 
>> models.BooleanField(default=False)objects = UserManager()
>> USERNAME_FIELD = 'username'REQUIRED_FIELDS = ['first_name', 
>> 'last_name', 'company_name', 'email']def get_full_name(self):
>> return self.first_name + self.last_name*
>>
>>
>> On Thursday, July 30, 2020 at 7:59:38 PM UTC+5:30 obast...@gmail.com 
>> wrote:
>>
>>> You can create an upload form with an Image field, then when saving the 
>>> for set the User field to request.user.
>>>
>>> Do you have an UploadForm already in your forms.py? if yes, show me with 
>>> the view that handles.
>>>
>>> On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job  
>>> wrote:
>>>


 It worked but user_id column in uploads_upload table is empty. How to 
 solve this issue?
 On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com 
 wrote:

> From the error, it states that you are trying to add an upload object 
> to the database without a user. And from your model.py, the User foreign 
> key does not have a null=True, and blank=True. So you can't save a null 
> value for that user field. 
>
> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job  
> wrote:
>
>> I'm trying to save image in postgres database. I have upload model 
>> which has a foreign key reference to the extended custom user model. But 
>> it 
>> shows the following error
>>
>>
>> uploads/model.py
>> from django.db import models
>> from django.contrib.auth import get_user_model
>>
>> User = get_user_model()
>>
>> class Upload(models.Model):
>> upload_file = models.ImageField(upload_to='uploads/')
>> upload_date = models.DateTimeField(auto_now_add =True)
>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>
>>
>> What am I missing? Thanks in advance
>>
>> -- 
>> You received this message because you are subscribed to the Google 
>> Groups "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, 
>> send an email to django-users...@googlegroups.com.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>  
>> 
>> .
>>
> -- 
 You received this message because you are subscribed to the Google 
 Groups "Django users" group.
 To unsubscribe from this group and stop receiving emails from it, send 
 an email to django-users...@googlegroups.com.

>>> To view this discussion on the web visit 
 

Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread oba stephen
irst in your UploadSerializer fields use fields = "__all__"

Then you can use this in your views:

*def post(self, **request, format=None**):*
*upload_file = request.data.get("upload_file"**)*
*upload_date = **request.data.get("upload_date"**)*


*user = request.userdata = {'upload_file': upload_file,
'upload_date': upload_date, 'user': user}serializer = *
*UploadSerializer*



*(data=data)if serializer.is_valid():serializer.save()
  return Response(serializer.data, status=status.HTTP_201_CREATED)
  return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)*

On Thu, Jul 30, 2020 at 5:59 PM Dinolin yp job 
wrote:

> I don't have forms.py since I'm creating only the endpoints using rest
> framework. I've done it earlier and it has worked but earlier the foreign
> key was to refer the default User model but now I have customized User
> model by extending AbstractBaseUser.
>
> uploads/views.py
>
>
>
>
>
>
> *class UploadView(APIView):def post(self, request,
> format=None):serializer =
> UploadSerializer(data=request.data)if
> serializer.is_valid():serializer.save()return
> Response(serializer.data, status=status.HTTP_201_CREATED)return
> Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
>
> uploads/serializers.py
>
>
>
> *class UploadSerializer(serializers.ModelSerializer):class Meta:
> model = Uploadfields = ('upload_file', 'upload_date')*
>
> users/models.py
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *class User(AbstractBaseUser):user_id =
> models.AutoField(primary_key=True)username =
> models.CharField(max_length=50, unique=True)first_name =
> models.CharField(max_length=50)last_name =
> models.CharField(max_length=50)company_name =
> models.CharField(max_length=100)email =
> models.EmailField(max_length=150, unique=True)is_active =
> models.BooleanField(default=True)is_superuser =
> models.BooleanField(default=False)objects = UserManager()
> USERNAME_FIELD = 'username'REQUIRED_FIELDS = ['first_name',
> 'last_name', 'company_name', 'email']def get_full_name(self):
> return self.first_name + self.last_name*
>
>
> On Thursday, July 30, 2020 at 7:59:38 PM UTC+5:30 obast...@gmail.com
> wrote:
>
>> You can create an upload form with an Image field, then when saving the
>> for set the User field to request.user.
>>
>> Do you have an UploadForm already in your forms.py? if yes, show me with
>> the view that handles.
>>
>> On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job 
>> wrote:
>>
>>>
>>>
>>> It worked but user_id column in uploads_upload table is empty. How to
>>> solve this issue?
>>> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com
>>> wrote:
>>>
 From the error, it states that you are trying to add an upload object
 to the database without a user. And from your model.py, the User foreign
 key does not have a null=True, and blank=True. So you can't save a null
 value for that user field.

 On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
 wrote:

> I'm trying to save image in postgres database. I have upload model
> which has a foreign key reference to the extended custom user model. But 
> it
> shows the following error
>
>
> uploads/model.py
> from django.db import models
> from django.contrib.auth import get_user_model
>
> User = get_user_model()
>
> class Upload(models.Model):
> upload_file = models.ImageField(upload_to='uploads/')
> upload_date = models.DateTimeField(auto_now_add =True)
> user = models.ForeignKey(User, on_delete=models.CASCADE)
>
>
> What am I missing? Thanks in advance
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
> 
> .
>
 --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>>
>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/e3462364-f867-4187-80bd-abfaa09d86b8n%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> 

Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread oba stephen
first in your UploadSerializer fields use fields = "__all__"

Then you can use this in your views:

*def post(self, **request, format=None**):*
*upload_file = request.data.get("upload_file"**)*
*upload_date = **request.data.get("upload_date"**)*






*user = request.userdata = {'upload_file': upload_file,
'upload_date': upload_date, 'user': user}serializer =
VoteSerializer(data=data)if serializer.is_valid():
serializer.save()return Response(serializer.data,
status=status.HTTP_201_CREATED)return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)*


This should do it for you.

On Thu, Jul 30, 2020 at 5:59 PM Dinolin yp job 
wrote:

> I don't have forms.py since I'm creating only the endpoints using rest
> framework. I've done it earlier and it has worked but earlier the foreign
> key was to refer the default User model but now I have customized User
> model by extending AbstractBaseUser.
>
> uploads/views.py
>
>
>
>
>
>
> *class UploadView(APIView):def post(self, request,
> format=None):serializer =
> UploadSerializer(data=request.data)if
> serializer.is_valid():serializer.save()return
> Response(serializer.data, status=status.HTTP_201_CREATED)return
> Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*
>
> uploads/serializers.py
>
>
>
> *class UploadSerializer(serializers.ModelSerializer):class Meta:
> model = Uploadfields = ('upload_file', 'upload_date')*
>
> users/models.py
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *class User(AbstractBaseUser):user_id =
> models.AutoField(primary_key=True)username =
> models.CharField(max_length=50, unique=True)first_name =
> models.CharField(max_length=50)last_name =
> models.CharField(max_length=50)company_name =
> models.CharField(max_length=100)email =
> models.EmailField(max_length=150, unique=True)is_active =
> models.BooleanField(default=True)is_superuser =
> models.BooleanField(default=False)objects = UserManager()
> USERNAME_FIELD = 'username'REQUIRED_FIELDS = ['first_name',
> 'last_name', 'company_name', 'email']def get_full_name(self):
> return self.first_name + self.last_name*
>
>
> On Thursday, July 30, 2020 at 7:59:38 PM UTC+5:30 obast...@gmail.com
> wrote:
>
>> You can create an upload form with an Image field, then when saving the
>> for set the User field to request.user.
>>
>> Do you have an UploadForm already in your forms.py? if yes, show me with
>> the view that handles.
>>
>> On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job 
>> wrote:
>>
>>>
>>>
>>> It worked but user_id column in uploads_upload table is empty. How to
>>> solve this issue?
>>> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com
>>> wrote:
>>>
 From the error, it states that you are trying to add an upload object
 to the database without a user. And from your model.py, the User foreign
 key does not have a null=True, and blank=True. So you can't save a null
 value for that user field.

 On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
 wrote:

> I'm trying to save image in postgres database. I have upload model
> which has a foreign key reference to the extended custom user model. But 
> it
> shows the following error
>
>
> uploads/model.py
> from django.db import models
> from django.contrib.auth import get_user_model
>
> User = get_user_model()
>
> class Upload(models.Model):
> upload_file = models.ImageField(upload_to='uploads/')
> upload_date = models.DateTimeField(auto_now_add =True)
> user = models.ForeignKey(User, on_delete=models.CASCADE)
>
>
> What am I missing? Thanks in advance
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
> 
> .
>
 --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>>
>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/e3462364-f867-4187-80bd-abfaa09d86b8n%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google 

Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread Dinolin yp job
I don't have forms.py since I'm creating only the endpoints using rest 
framework. I've done it earlier and it has worked but earlier the foreign 
key was to refer the default User model but now I have customized User 
model by extending AbstractBaseUser. 

uploads/views.py






*class UploadView(APIView):def post(self, request, format=None):
serializer = UploadSerializer(data=request.data)if 
serializer.is_valid():serializer.save()return 
Response(serializer.data, status=status.HTTP_201_CREATED)return 
Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)*

uploads/serializers.py



*class UploadSerializer(serializers.ModelSerializer):class Meta:
model = Uploadfields = ('upload_file', 'upload_date')*

users/models.py
















*class User(AbstractBaseUser):user_id = 
models.AutoField(primary_key=True)username = 
models.CharField(max_length=50, unique=True)first_name = 
models.CharField(max_length=50)last_name = 
models.CharField(max_length=50)company_name = 
models.CharField(max_length=100)email = 
models.EmailField(max_length=150, unique=True)is_active = 
models.BooleanField(default=True)is_superuser = 
models.BooleanField(default=False)objects = UserManager()
USERNAME_FIELD = 'username'REQUIRED_FIELDS = ['first_name', 
'last_name', 'company_name', 'email']def get_full_name(self):
return self.first_name + self.last_name*


On Thursday, July 30, 2020 at 7:59:38 PM UTC+5:30 obast...@gmail.com wrote:

> You can create an upload form with an Image field, then when saving the 
> for set the User field to request.user.
>
> Do you have an UploadForm already in your forms.py? if yes, show me with 
> the view that handles.
>
> On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job  
> wrote:
>
>>
>>
>> It worked but user_id column in uploads_upload table is empty. How to 
>> solve this issue?
>> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com 
>> wrote:
>>
>>> From the error, it states that you are trying to add an upload object to 
>>> the database without a user. And from your model.py, the User foreign key 
>>> does not have a null=True, and blank=True. So you can't save a null value 
>>> for that user field. 
>>>
>>> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job  
>>> wrote:
>>>
 I'm trying to save image in postgres database. I have upload model 
 which has a foreign key reference to the extended custom user model. But 
 it 
 shows the following error


 uploads/model.py
 from django.db import models
 from django.contrib.auth import get_user_model

 User = get_user_model()

 class Upload(models.Model):
 upload_file = models.ImageField(upload_to='uploads/')
 upload_date = models.DateTimeField(auto_now_add =True)
 user = models.ForeignKey(User, on_delete=models.CASCADE)


 What am I missing? Thanks in advance

 -- 
 You received this message because you are subscribed to the Google 
 Groups "Django users" group.
 To unsubscribe from this group and stop receiving emails from it, send 
 an email to django-users...@googlegroups.com.
 To view this discussion on the web visit 
 https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
  
 
 .

>>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com.
>>
> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/e3462364-f867-4187-80bd-abfaa09d86b8n%40googlegroups.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0ce310b5-7bf5-4200-8ddd-e679c160669dn%40googlegroups.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread oba stephen
You can create an upload form with an Image field, then when saving the for
set the User field to request.user.

Do you have an UploadForm already in your forms.py? if yes, show me with
the view that handles.

On Thu, Jul 30, 2020 at 11:59 AM Dinolin yp job 
wrote:

>
>
> It worked but user_id column in uploads_upload table is empty. How to
> solve this issue?
> On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com
> wrote:
>
>> From the error, it states that you are trying to add an upload object to
>> the database without a user. And from your model.py, the User foreign key
>> does not have a null=True, and blank=True. So you can't save a null value
>> for that user field.
>>
>> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
>> wrote:
>>
>>> I'm trying to save image in postgres database. I have upload model which
>>> has a foreign key reference to the extended custom user model. But it shows
>>> the following error
>>>
>>>
>>> uploads/model.py
>>> from django.db import models
>>> from django.contrib.auth import get_user_model
>>>
>>> User = get_user_model()
>>>
>>> class Upload(models.Model):
>>> upload_file = models.ImageField(upload_to='uploads/')
>>> upload_date = models.DateTimeField(auto_now_add =True)
>>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>>
>>>
>>> What am I missing? Thanks in advance
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/e3462364-f867-4187-80bd-abfaa09d86b8n%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAAJsLnrbpKP1%3DN76ZccFmDv%3DswShpBrYHgeAZxnDoYP-MyZ3XQ%40mail.gmail.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread Dinolin yp job


It worked but user_id column in uploads_upload table is empty. How to solve 
this issue?
On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com wrote:

> From the error, it states that you are trying to add an upload object to 
> the database without a user. And from your model.py, the User foreign key 
> does not have a null=True, and blank=True. So you can't save a null value 
> for that user field. 
>
> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job  
> wrote:
>
>> I'm trying to save image in postgres database. I have upload model which 
>> has a foreign key reference to the extended custom user model. But it shows 
>> the following error
>>
>>
>> uploads/model.py
>> from django.db import models
>> from django.contrib.auth import get_user_model
>>
>> User = get_user_model()
>>
>> class Upload(models.Model):
>> upload_file = models.ImageField(upload_to='uploads/')
>> upload_date = models.DateTimeField(auto_now_add =True)
>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>
>>
>> What am I missing? Thanks in advance
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e3462364-f867-4187-80bd-abfaa09d86b8n%40googlegroups.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread Dinolin yp job


It worked but the user_id in uploads_upload is empty. How can I can make 
that work?
On Thursday, July 30, 2020 at 3:31:21 PM UTC+5:30 obast...@gmail.com wrote:

> From the error, it states that you are trying to add an upload object to 
> the database without a user. And from your model.py, the User foreign key 
> does not have a null=True, and blank=True. So you can't save a null value 
> for that user field. 
>
> On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job  
> wrote:
>
>> I'm trying to save image in postgres database. I have upload model which 
>> has a foreign key reference to the extended custom user model. But it shows 
>> the following error
>>
>>
>> uploads/model.py
>> from django.db import models
>> from django.contrib.auth import get_user_model
>>
>> User = get_user_model()
>>
>> class Upload(models.Model):
>> upload_file = models.ImageField(upload_to='uploads/')
>> upload_date = models.DateTimeField(auto_now_add =True)
>> user = models.ForeignKey(User, on_delete=models.CASCADE)
>>
>>
>> What am I missing? Thanks in advance
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/57100db3-81b7-49ca-86e6-096c121c94c8n%40googlegroups.com.


Re: IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread oba stephen
>From the error, it states that you are trying to add an upload object to
the database without a user. And from your model.py, the User foreign key
does not have a null=True, and blank=True. So you can't save a null value
for that user field.

On Thu, Jul 30, 2020 at 10:52 AM Dinolin yp job 
wrote:

> I'm trying to save image in postgres database. I have upload model which
> has a foreign key reference to the extended custom user model. But it shows
> the following error
>
>
> uploads/model.py
> from django.db import models
> from django.contrib.auth import get_user_model
>
> User = get_user_model()
>
> class Upload(models.Model):
> upload_file = models.ImageField(upload_to='uploads/')
> upload_date = models.DateTimeField(auto_now_add =True)
> user = models.ForeignKey(User, on_delete=models.CASCADE)
>
>
> What am I missing? Thanks in advance
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAAJsLno%2BZ14h9Z%3DHxkFWoqkA7k%3DtgLtuSmST-epu_wKPSaFpFw%40mail.gmail.com.


IntegrityError: null value in column "user_id" violates not-null constraint

2020-07-30 Thread Dinolin yp job
I'm trying to save image in postgres database. I have upload model which 
has a foreign key reference to the extended custom user model. But it shows 
the following error


uploads/model.py
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Upload(models.Model):
upload_file = models.ImageField(upload_to='uploads/')
upload_date = models.DateTimeField(auto_now_add =True)
user = models.ForeignKey(User, on_delete=models.CASCADE)


What am I missing? Thanks in advance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/bddd1f92-895c-4e23-8f08-976c0f178f17o%40googlegroups.com.


Re: IntegrityError: NOT NULL constraint failed

2020-05-27 Thread sunday honesty
Thanks Samuel it worked

On Thu, May 28, 2020, 12:23 AM Samuel Nogueira  wrote:

> In your Comment model you have a author field wich is a ForeignKey. The
> error is pointing exactly to that field, since it is a not null field. To
> overcome this you must pick the ID of the logged user and set the author
> field with the user ID. You can do that in your views.py the same way as
> you did in new_comment.post = post, only changing .post for .author and
> matching it with request.user. the line will look like this
> new_comment.author = request.user. remember to put it before
> new_comment.save()
>
>
>
> *De: *sunday honesty 
> *Enviado:*quarta-feira, 27 de maio de 2020 19:36
> *Para: *Django users 
> *Assunto: *IntegrityError: NOT NULL constraint failed
>
>
>
> I try to let user add comments to blog post am making... When I run
> makemigrations and migrate, everything seemed fine . The form displayed
> well but shows the following error when I fill the form and click on the
> submit button. Django.db.utils.IntegrityError: NOT NULL constraint failed:
> blog_comment.author_id
>
>
>
> Am new to Django and following a tutorial. The tutorial doesn't have users
> except the super user. I learnt about users and so I let user register to
> use the blog. The tutorial provided a name field in the form so commenter
> can enter their name. Here, I want to use the current user for this
> field(see my models.py below to see how I have done this). Any help to
> solve this will be appreciated.
>
>
>
> PS: I have seen similar questions like this and deleted my migrations file
> and re-ran migrations but it didn't still work.
>
>
>
> #models.py
>
> class Comment(models.Model):
>
> post = models.ForeignKey(Post, on_delete=models.CASCADE,
> related_name='comments')
>
> author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
>
> comment = models.TextField()
>
> created = models.DateTimeField(auto_now_add=True)
>
> updated = models.DateTimeField(auto_now=True)
>
> active = models.BooleanField(default=True)
>
>
>
> class Meta:
>
> ordering = ('created',)
>
>
>
> def __str__(self):
>
> return f'Comment by {self.author} on {self.post}'
>
>
>
> #forms.py
>
> class CommentForm(forms.ModelForm):
>
>
>
> class Meta:
>
> model = Comment
>
> fields = ('comment',)
>
>
>
> #views.py
>
> login_required
>
> def post_detail(request, post, pk):
>
> post = get_object_or_404(Post, id=pk, slug=post, status='published')
>
> comments = post.comments.filter(active=True)
>
> new_comment = None
>
>
>
> if request.method == 'POST':
>
> comment_form = CommentForm(data=request.POST)
>
> if comment_form.is_valid():
>
> new_comment = comment_form.save(commit=False)
>
> new_comment.post = post
>
> new_comment.save()
>
> else:
>
> comment_form = CommentForm()
>
> return render(request,
>
> 'post_detail.html',
>
> {'post': post,
>
> 'comments': comments,
>
> 'new_comment': new_comment,
>
> 'comment_form': comment_form})
>
>
>
> --
>
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
>
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
>
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/87349ba6-bb75-477c-a84b-9e15be428a5b%40googlegroups.com
> .
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5ecef62c.1c69fb81.ab057.4da7%40mx.google.com
> <https://groups.google.com/d/msgid/django-users/5ecef62c.1c69fb81.ab057.4da7%40mx.google.com?utm_medium=email_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CALcuGNtreJ4koB6v22TtGKsPSD9-w4%3DzFR_v63u5c%3Dk6rNJUXA%40mail.gmail.com.


RES: IntegrityError: NOT NULL constraint failed

2020-05-27 Thread Samuel Nogueira
In your Comment model you have a author field wich is a ForeignKey. The error is pointing exactly to that field, since it is a not null field. To overcome this you must pick the ID of the logged user and set the author field with the user ID. You can do that in your views.py the same way as you did in new_comment.post = post, only changing .post for .author and matching it with request.user. the line will look like this new_comment.author = request.user. remember to put it before new_comment.save()  De: sunday honestyEnviado:quarta-feira, 27 de maio de 2020 19:36Para: Django usersAssunto: IntegrityError: NOT NULL constraint failed I try to let user add comments to blog post am making... When I run makemigrations and migrate, everything seemed fine . The form displayed well but shows the following error when I fill the form and click on the submit button. Django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id Am new to Django and following a tutorial. The tutorial doesn't have users except the super user. I learnt about users and so I let user register to use the blog. The tutorial provided a name field in the form so commenter can enter their name. Here, I want to use the current user for this field(see my models.py below to see how I have done this). Any help to solve this will be appreciated. PS: I have seen similar questions like this and deleted my migrations file and re-ran migrations but it didn't still work. #models.pyclass Comment(models.Model):    post = models.ForeignKey(Post, _on_delete_=models.CASCADE, related_name='comments')    author = models.ForeignKey(get_user_model(), _on_delete_=models.CASCADE,)    comment = models.TextField()   created = models.DateTimeField(auto_now_add=True)  updated = models.DateTimeField(auto_now=True)    active = models.BooleanField(default=True) class Meta:    ordering = ('created',) def __str__(self):    return f'Comment by {self.author} on {self.post}' #forms.pyclass CommentForm(forms.ModelForm): class Meta:    model = Comment    fields = ('comment',) #views.pylogin_requireddef post_detail(request, post, pk):    post = get_object_or_404(Post, id=pk, slug=post, status='published')    comments = post.comments.filter(active=True)    new_comment = None if request.method == 'POST':    comment_form = CommentForm(data="">    if comment_form.is_valid():    new_comment = comment_form.save(commit=False)    new_comment.post = post    new_comment.save()    else:    comment_form = CommentForm()    return render(request,    'post_detail.html',    {'post': post,    'comments': comments,    'new_comment': new_comment,    'comment_form': comment_form}) -- You received this message because you are subscribed to the Google Groups "Django users" group.To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com.To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/87349ba6-bb75-477c-a84b-9e15be428a5b%40googlegroups.com. 



-- 
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5ecef62c.1c69fb81.ab057.4da7%40mx.google.com.


IntegrityError: NOT NULL constraint failed

2020-05-27 Thread sunday honesty
I try to let user add comments to blog post am making... When I run 
makemigrations and migrate, everything seemed fine . The form displayed well 
but shows the following error when I fill the form and click on the submit 
button. Django.db.utils.IntegrityError: NOT NULL constraint failed: 
blog_comment.author_id

Am new to Django and following a tutorial. The tutorial doesn't have users 
except the super user. I learnt about users and so I let user register to use 
the blog. The tutorial provided a name field in the form so commenter can enter 
their name. Here, I want to use the current user for this field(see my 
models.py below to see how I have done this). Any help to solve this will be 
appreciated.

PS: I have seen similar questions like this and deleted my migrations file and 
re-ran migrations but it didn't still work.

#models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, 
related_name='comments')
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
comment = models.TextField()   
created = models.DateTimeField(auto_now_add=True)  
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)

class Meta:
ordering = ('created',)

def __str__(self):
return f'Comment by {self.author} on {self.post}'

#forms.py
class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('comment',)

#views.py
login_required
def post_detail(request, post, pk):
post = get_object_or_404(Post, id=pk, slug=post, status='published')
comments = post.comments.filter(active=True)
new_comment = None

if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'post_detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/87349ba6-bb75-477c-a84b-9e15be428a5b%40googlegroups.com.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-07-17 Thread Michael Barr
That's what I had to revert to doing, yes. I added logic to the 
validate_unique() method on the model itself and then updated the query 
logic manually.

On Wednesday, July 17, 2019 at 2:15:52 AM UTC-4, Derek wrote:
>
> Would it be correct to say that adding validation at model clean level 
> would make more sense when using this feature with the admin?
>
> On Tuesday, 9 April 2019 15:13:19 UTC+2, Simon Charette wrote:
>>
>> No form validation is implemented for UniqueConstraint(condition) yet as 
>> that would require
>> a non-trivial refactor of how it's performed. It was discussed during the 
>> feature development[0].
>>
>> I'd suggest you override you form or your model's clean() method to 
>> perform the validation
>> yourself until built-in support is added.
>>
>> Submitting a new Trac ticket so we don't loose track of the issue would 
>> also be appreciated.
>>
>> Cheers,
>> Simon
>>
>> [0] https://github.com/django/django/pull/10796#discussion_r244216763
>>
>> Le mardi 9 avril 2019 07:29:53 UTC-4, Ryan Jarvis a écrit :
>>>
>>> Hey there,
>>>
>>> I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
>>> seem to be misunderstanding something.  When adding a Constraint to the 
>>> model I am getting an uncaught IntegrityError in the admin.  
>>> I've got the following sample code:
>>>
>>> *models.py*
>>>
>>> class Seminar(models.Model):
>>> seminar_id = models.CharField(max_length=255, unique=True)
>>> members = models.ManyToManyField(User, through='SeminarRole', 
>>> related_name="studies")
>>>
>>> class SeminarRole(models.Model):
>>> LEAD = 1  # Only 1 Lead permitted per seminar
>>> SUPPORT = 2
>>> ROLE_CHOICES = (
>>> (LEAD, 'Lead'),
>>> (SUPPORT, 'Support'),
>>> )
>>>
>>> user = models.ForeignKey(User, related_name='seminar_roles', 
>>> on_delete=models.CASCADE)
>>> seminar = models.ForeignKey('seminar', related_name='roles', 
>>> on_delete=models.CASCADE)
>>>
>>> role = models.IntegerField(choices=ROLE_CHOICES)
>>>
>>> class Meta:
>>> constraints = [
>>> models.UniqueConstraint(fields=['seminar'], 
>>> condition=Q(role=1), name="only_one_lead"),
>>> ]
>>>
>>>
>>>
>>> For the code above in the Django Admin I can successfully add a 
>>> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for 
>>> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as 
>>> another Lead to SeminarA it gives me an Exception.  Should I be seeing the 
>>> Django Admin catch this before hand?
>>>
>>> IntegrityError at /admin/study_management/seminarrole/add/
>>> duplicate key value violates unique constraint "only_one_lead"
>>> DETAIL:  Key (seminar_id)=(1) already exists.
>>>
>>>
>>> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>>>
>>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/54a5cda6-000d-4f2d-8260-1e0765c33d84%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-07-17 Thread Derek
Would it be correct to say that adding validation at model clean level 
would make more sense when using this feature with the admin?

On Tuesday, 9 April 2019 15:13:19 UTC+2, Simon Charette wrote:
>
> No form validation is implemented for UniqueConstraint(condition) yet as 
> that would require
> a non-trivial refactor of how it's performed. It was discussed during the 
> feature development[0].
>
> I'd suggest you override you form or your model's clean() method to 
> perform the validation
> yourself until built-in support is added.
>
> Submitting a new Trac ticket so we don't loose track of the issue would 
> also be appreciated.
>
> Cheers,
> Simon
>
> [0] https://github.com/django/django/pull/10796#discussion_r244216763
>
> Le mardi 9 avril 2019 07:29:53 UTC-4, Ryan Jarvis a écrit :
>>
>> Hey there,
>>
>> I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
>> seem to be misunderstanding something.  When adding a Constraint to the 
>> model I am getting an uncaught IntegrityError in the admin.  
>> I've got the following sample code:
>>
>> *models.py*
>>
>> class Seminar(models.Model):
>> seminar_id = models.CharField(max_length=255, unique=True)
>> members = models.ManyToManyField(User, through='SeminarRole', 
>> related_name="studies")
>>
>> class SeminarRole(models.Model):
>> LEAD = 1  # Only 1 Lead permitted per seminar
>> SUPPORT = 2
>> ROLE_CHOICES = (
>> (LEAD, 'Lead'),
>> (SUPPORT, 'Support'),
>> )
>>
>> user = models.ForeignKey(User, related_name='seminar_roles', 
>> on_delete=models.CASCADE)
>> seminar = models.ForeignKey('seminar', related_name='roles', 
>> on_delete=models.CASCADE)
>>
>> role = models.IntegerField(choices=ROLE_CHOICES)
>>
>> class Meta:
>> constraints = [
>> models.UniqueConstraint(fields=['seminar'], 
>> condition=Q(role=1), name="only_one_lead"),
>> ]
>>
>>
>>
>> For the code above in the Django Admin I can successfully add a 
>> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for 
>> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as 
>> another Lead to SeminarA it gives me an Exception.  Should I be seeing the 
>> Django Admin catch this before hand?
>>
>> IntegrityError at /admin/study_management/seminarrole/add/
>> duplicate key value violates unique constraint "only_one_lead"
>> DETAIL:  Key (seminar_id)=(1) already exists.
>>
>>
>> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/acce73e7-b15c-4efc-9e30-bfb40510c8a8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-07-15 Thread Michael Barr
Yeah, this one just bit me in the Django Admin as well. According to the 
docs <https://docs.djangoproject.com/en/2.2/ref/models/constraints/>,

Validation of Constraints
>
> In general constraints are *not* checked during full_clean(), and do not 
> raise ValidationErrors. Rather you’ll get a database integrity error on 
> save(). UniqueConstraints are different in this regard, in that they 
> leverage the existing validate_unique() logic, and thus enable two-stage 
> validation. In addition to IntegrityError on save(), ValidationError is 
> also raised during model validation when the UniqueConstraint is violated.
>

However, it makes no mention of UniqueConstraint instances with conditions 
being ignored. It took me diving into the Django source code to find out 
what was happening. Thankfully, I stumbled upon this here to confirm my 
sanity. :)

On Tuesday, April 9, 2019 at 9:13:19 AM UTC-4, Simon Charette wrote:
>
> No form validation is implemented for UniqueConstraint(condition) yet as 
> that would require
> a non-trivial refactor of how it's performed. It was discussed during the 
> feature development[0].
>
> I'd suggest you override you form or your model's clean() method to 
> perform the validation
> yourself until built-in support is added.
>
> Submitting a new Trac ticket so we don't loose track of the issue would 
> also be appreciated.
>
> Cheers,
> Simon
>
> [0] https://github.com/django/django/pull/10796#discussion_r244216763
>
> Le mardi 9 avril 2019 07:29:53 UTC-4, Ryan Jarvis a écrit :
>>
>> Hey there,
>>
>> I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
>> seem to be misunderstanding something.  When adding a Constraint to the 
>> model I am getting an uncaught IntegrityError in the admin.  
>> I've got the following sample code:
>>
>> *models.py*
>>
>> class Seminar(models.Model):
>> seminar_id = models.CharField(max_length=255, unique=True)
>> members = models.ManyToManyField(User, through='SeminarRole', 
>> related_name="studies")
>>
>> class SeminarRole(models.Model):
>> LEAD = 1  # Only 1 Lead permitted per seminar
>> SUPPORT = 2
>> ROLE_CHOICES = (
>> (LEAD, 'Lead'),
>> (SUPPORT, 'Support'),
>> )
>>
>> user = models.ForeignKey(User, related_name='seminar_roles', 
>> on_delete=models.CASCADE)
>> seminar = models.ForeignKey('seminar', related_name='roles', 
>> on_delete=models.CASCADE)
>>
>> role = models.IntegerField(choices=ROLE_CHOICES)
>>
>> class Meta:
>> constraints = [
>> models.UniqueConstraint(fields=['seminar'], 
>> condition=Q(role=1), name="only_one_lead"),
>> ]
>>
>>
>>
>> For the code above in the Django Admin I can successfully add a 
>> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for 
>> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as 
>> another Lead to SeminarA it gives me an Exception.  Should I be seeing the 
>> Django Admin catch this before hand?
>>
>> IntegrityError at /admin/study_management/seminarrole/add/
>> duplicate key value violates unique constraint "only_one_lead"
>> DETAIL:  Key (seminar_id)=(1) already exists.
>>
>>
>> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e0a79eab-e9d6-46fb-86c3-8f5d97fb3f7c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-04-09 Thread Simon Charette
No form validation is implemented for UniqueConstraint(condition) yet as 
that would require
a non-trivial refactor of how it's performed. It was discussed during the 
feature development[0].

I'd suggest you override you form or your model's clean() method to perform 
the validation
yourself until built-in support is added.

Submitting a new Trac ticket so we don't loose track of the issue would 
also be appreciated.

Cheers,
Simon

[0] https://github.com/django/django/pull/10796#discussion_r244216763

Le mardi 9 avril 2019 07:29:53 UTC-4, Ryan Jarvis a écrit :
>
> Hey there,
>
> I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
> seem to be misunderstanding something.  When adding a Constraint to the 
> model I am getting an uncaught IntegrityError in the admin.  
> I've got the following sample code:
>
> *models.py*
>
> class Seminar(models.Model):
> seminar_id = models.CharField(max_length=255, unique=True)
> members = models.ManyToManyField(User, through='SeminarRole', 
> related_name="studies")
>
> class SeminarRole(models.Model):
> LEAD = 1  # Only 1 Lead permitted per seminar
> SUPPORT = 2
> ROLE_CHOICES = (
> (LEAD, 'Lead'),
> (SUPPORT, 'Support'),
> )
>
> user = models.ForeignKey(User, related_name='seminar_roles', 
> on_delete=models.CASCADE)
> seminar = models.ForeignKey('seminar', related_name='roles', 
> on_delete=models.CASCADE)
>
> role = models.IntegerField(choices=ROLE_CHOICES)
>
> class Meta:
> constraints = [
> models.UniqueConstraint(fields=['seminar'], 
> condition=Q(role=1), name="only_one_lead"),
> ]
>
>
>
> For the code above in the Django Admin I can successfully add a 
> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for 
> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as 
> another Lead to SeminarA it gives me an Exception.  Should I be seeing the 
> Django Admin catch this before hand?
>
> IntegrityError at /admin/study_management/seminarrole/add/
> duplicate key value violates unique constraint "only_one_lead"
> DETAIL:  Key (seminar_id)=(1) already exists.
>
>
> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/12fba4e5-7f07-4491-afb6-b969e73252da%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-04-09 Thread Robin Riis
The Integrity error means that there is a row in the database with role = 1
So another row with role=1 would break the unique constraint and is not
allowed.

So either remove the unique constraint or make sure it will be unique.

Den tis 9 apr. 2019 13:29Ryan Jarvis  skrev:

> Hey there,
>
> I'm trying out the new UniqueConstraint functionality in Django 2.2 and
> seem to be misunderstanding something.  When adding a Constraint to the
> model I am getting an uncaught IntegrityError in the admin.
> I've got the following sample code:
>
> *models.py*
>
> class Seminar(models.Model):
> seminar_id = models.CharField(max_length=255, unique=True)
> members = models.ManyToManyField(User, through='SeminarRole',
> related_name="studies")
>
> class SeminarRole(models.Model):
> LEAD = 1  # Only 1 Lead permitted per seminar
> SUPPORT = 2
> ROLE_CHOICES = (
> (LEAD, 'Lead'),
> (SUPPORT, 'Support'),
> )
>
> user = models.ForeignKey(User, related_name='seminar_roles',
> on_delete=models.CASCADE)
> seminar = models.ForeignKey('seminar', related_name='roles',
> on_delete=models.CASCADE)
>
> role = models.IntegerField(choices=ROLE_CHOICES)
>
> class Meta:
> constraints = [
> models.UniqueConstraint(fields=['seminar'],
> condition=Q(role=1), name="only_one_lead"),
> ]
>
>
>
> For the code above in the Django Admin I can successfully add a
> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for
> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as
> another Lead to SeminarA it gives me an Exception.  Should I be seeing the
> Django Admin catch this before hand?
>
> IntegrityError at /admin/study_management/seminarrole/add/
> duplicate key value violates unique constraint "only_one_lead"
> DETAIL:  Key (seminar_id)=(1) already exists.
>
>
> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/fb2ab520-178d-4a0c-acf7-8cb0498936e4%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/fb2ab520-178d-4a0c-acf7-8cb0498936e4%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAPLZMbPxNN%3DCa6GqjcR_kXDO_a2VyzKxgVNfTgzAdtnfhhYqgA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


UniqueConstraint raises uncaught IntegrityError in Admin

2019-04-09 Thread Ryan Jarvis
Hey there,

I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
seem to be misunderstanding something.  When adding a Constraint to the 
model I am getting an uncaught IntegrityError in the admin.  
I've got the following sample code:

*models.py*

class Seminar(models.Model):
seminar_id = models.CharField(max_length=255, unique=True)
members = models.ManyToManyField(User, through='SeminarRole', 
related_name="studies")

class SeminarRole(models.Model):
LEAD = 1  # Only 1 Lead permitted per seminar
SUPPORT = 2
ROLE_CHOICES = (
(LEAD, 'Lead'),
(SUPPORT, 'Support'),
)

user = models.ForeignKey(User, related_name='seminar_roles', 
on_delete=models.CASCADE)
seminar = models.ForeignKey('seminar', related_name='roles', 
on_delete=models.CASCADE)

role = models.IntegerField(choices=ROLE_CHOICES)

class Meta:
constraints = [
models.UniqueConstraint(fields=['seminar'], 
condition=Q(role=1), name="only_one_lead"),
]



For the code above in the Django Admin I can successfully add a SeminarRole 
with User1 as the Lead for SeminarA, User2 as the Lead for SeminarB, and 
User1 as Support for SeminarB but if I try and add User2 as another Lead to 
SeminarA it gives me an Exception.  Should I be seeing the Django Admin 
catch this before hand?

IntegrityError at /admin/study_management/seminarrole/add/
duplicate key value violates unique constraint "only_one_lead"
DETAIL:  Key (seminar_id)=(1) already exists.


I'm on Django 2.2, Python 3.7 and Postgres 11.2

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fb2ab520-178d-4a0c-acf7-8cb0498936e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Need your help to fix IntegrityError in my Django code.

2018-07-02 Thread prateek gupta
Hi All,

I have created a simple database admin panel 
(Django2..6+Python3.6+Mysql5.7) where admin can operate create/edit/delete 
operations of database.
I am facing following IntegrityError  error when I try to Merge two 
products and click on Preview from my Django admin panel-
2018-07-02 16:17:56,428 [ERROR] exception.py:118 
handle_uncaught_exception() : Internal Server Error: 
/where2buy/merchantproduct/
Traceback (most recent call last):
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py",
 
line 85, in _execute
return self.cursor.execute(sql, params)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\mysql\base.py",
 
line 71, in execute
return self.cursor.execute(query, args)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\cursors.py",
 
line 250, in execute
self.errorhandler(self, exc, value)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\connections.py",
 
line 50, in defaulterrorhandler
raise errorvalue
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\cursors.py",
 
line 247, in execute
res = self._query(query)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\cursors.py",
 
line 411, in _query
rowcount = self._do_query(q)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\cursors.py",
 
line 374, in _do_query
db.query(q)
  File 
"C:\Users\prateek1.gupta\AppData\Local\Continuum\anaconda3\lib\site-packages\MySQLdb\connections.py",
 
line 277, in query
_mysql.connection.query(self, query)
_mysql_exceptions.IntegrityError: (1451, 'Cannot delete or update a parent 
row: a foreign key constraint fails (`productsearchv2`.`feed`, CONSTRAINT 
`feed_mproduct_id_fk` FOREIGN KEY (`merchant_id`, `merchant_product_id`) 
REFERENCES `merchant_product` (`merchant_id`, `merchant_product_id`) ON 
DELETE NO )')

I think issue is may be wrong relationship settings in my model file but 
couldn't able to find exact issue.
Can anyone please help me to find the issue? My code is as below-

class MerchantProduct(models.Model):
merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, 
null=True)
merchant_product_id = models.CharField(max_length=100)
gtin = models.CharField(max_length=15, blank=True, null=True)
merchant_group_id = models.CharField(max_length=100, blank=True, null=True)
name = models.CharField(max_length=300)
description = models.TextField(blank=True, null=True)
image_urls = models.TextField(blank=True, null=True)
image_phashes = models.TextField(blank=True, null=True)
web_url = models.URLField(blank=True, null=True)
brand = models.CharField(max_length=100, blank=True, null=True)
category = models.CharField(max_length=150, blank=True, null=True)
color = models.CharField(max_length=100, blank=True, null=True)
size = models.CharField(max_length=100, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
unique_together = (('merchant', 'merchant_product_id'),)
managed = False
db_table = 'merchant_product'

def __str__(self):
return self.name

class Product(models.Model):
merchants = models.ManyToManyField(Merchant, through='MerchantProduct')
brand = models.ForeignKey(Brand, related_name='brand', 
on_delete=models.SET_NULL, blank=True, null=True)
category = models.ForeignKey(Category, related_name='category', 
on_delete=models.SET_NULL, blank=True, null=True)
group = models.ForeignKey('self', related_name='ID', 
on_delete=models.SET_NULL, blank=True, null=True)
gtin = models.CharField(max_length=15, blank=True, null=True)
name = models.CharField(max_length=300)
description = models.TextField()
image_urls = models.TextField()
image_phashes = models.CharField(max_length=200, blank=True, null=True)
color = models.CharField(max_length=100, blank=True, null=True)
size = models.CharField(max_length=100, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
managed = False
db_table = 'product'

def __str__(self):
return self.name


class Merchant(models.Model):
DATA_QUALITY_CHOICES = (
('approx', 'Approximate'),
('exact', 'Exact'),
)
name = models.CharField(unique=True, max_length=45)
display_name = models.CharField(unique=True, max_length=255)
url_name = models.CharField(

Re: IntegrityError: FOREIGN KEY constraint failed: Django 2.0.3

2018-03-22 Thread Seven Reeds
Uh, am I not using the ORM?  If I am not then what must I do to get back on 
track?

I just realized that i didn't include the "Delete" CBV in my original 
post.  I do not have easy access to the code at the moment so what follows 
is a rough approximation of what that code is about and is prolly full of 
errors:

class Delete(DeleteView):
def get:
profile = Profile.objects.get(account_number=self.request.account_number)
user = user.objects.get(pk=profile.user.pk)
user.delete()

In a debugger I can stop on the "user.delete()" line and see that the 
profile and user objects are what I expect them to be.



On Wednesday, March 21, 2018 at 10:34:47 AM UTC-5, Simon Charette wrote:
>
> Hello Anon,
>
> Django doesn't use database level ON DELETE constraints and emulates them 
> in Python
> to dispatch pre_delete/post_delete signals. As long as you're using the 
> ORM to perform
> the deletion you shouldn't encounter constraint violations.
>
> There's a ticket to add support for database level on_delete 
> constraints[0].
>
> Cheers,
> Simon
>
> [0] https://code.djangoproject.com/ticket/21961
>
> Le mercredi 21 mars 2018 10:50:25 UTC-4, Anon Ymous a écrit :
>>
>> Hi,
>>
>> I am learning python by trying to create a small Django app.  I may have 
>> found a bug related to Django and/or sqlite3.  If you are stackoverflow 
>> folks then my initial post is there:  
>> https://stackoverflow.com/questions/49361834/integrityerror-exception-in-deleteview-cbv
>>
>> My app really is just creating a small web site to add users and figure 
>> out how to do CRUD operations in building user profiles.  I am using the 
>> following setup:
>>
>> Django Version: 2.0.3
>> Python Version: 3.6.3
>> Installed Applications:
>> ['django.contrib.admin',
>> 'django.contrib.auth',
>> 'django.contrib.contenttypes',
>> 'django.contrib.sessions',
>> 'django.contrib.messages',
>> 'django.contrib.staticfiles',
>> 'django_extensions',
>> 'django.contrib.sites',
>> 'allauth',
>> 'allauth.account',
>> 'allauth.socialaccount',
>> 'auditlog',
>> 'widget_tweaks',
>> 'Members.apps.MembersConfig']
>> Installed Middleware:
>> ['django.middleware.security.SecurityMiddleware',
>> 'django.contrib.sessions.middleware.SessionMiddleware',
>> 'django.middleware.common.CommonMiddleware',
>> 'django.middleware.csrf.CsrfViewMiddleware',
>> 'django.contrib.auth.middleware.AuthenticationMiddleware',
>> 'django.contrib.messages.middleware.MessageMiddleware',
>> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
>> 'auditlog.middleware.AuditlogMiddleware']
>>
>> I am using sqlite3 as the DB backend..
>>
>> I can create the virgin project, tweak the settings file and do the 
>> initial "makemigrations" and "migrate".  This, of course, creates the 
>> Django "user" table(s).  I went about creating my own "profile" model that 
>> "extends" the User model by creating a "oneToOne" field that points back to 
>> User and specifies an "on_delete=models.CASCADE" clause:
>>
>> class Profile(models.Model):
>> ...
>> user = models.OneToOneField(
>> User,
>> on_delete=models.CASCADE,
>> blank=False,
>> null=False,
>> )
>> ...
>>
>> The thing is the table that is created is given the constraint:
>>
>> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY 
>> DEFERRED,
>>
>> but the "on delete cascade" clause is missing.  
>>
>> I first noticed this when testing a profile delete operation.  I get a 
>> foreign key constraint violation.  Looking into that led me here to you 
>> guys.
>>
>> I have added that clause to the table:
>>
>> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) on delete cascade 
>> DEFERRABLE INITIALLY DEFERRED,
>>
>> but I still get the constraint violation.  I did more digging last night 
>> and see that at least one of the Django generated "user_*" tables also has 
>> a foreign key relationship back to the "user" table and that is also 
>> missing the cascade clause.
>>
>> My guesses at this instant include:
>>
>>- I have no idea what I am doing
>>- Django or the sqlite3 backend *should* be handling the cascade ops 
>>internally -- but isn't
>>
>> What am I missing?
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/47509400-f086-4f25-b749-c5bf0853f2d4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError: FOREIGN KEY constraint failed: Django 2.0.3

2018-03-21 Thread Simon Charette
Hello Anon,

Django doesn't use database level ON DELETE constraints and emulates them 
in Python
to dispatch pre_delete/post_delete signals. As long as you're using the ORM 
to perform
the deletion you shouldn't encounter constraint violations.

There's a ticket to add support for database level on_delete constraints[0].

Cheers,
Simon

[0] https://code.djangoproject.com/ticket/21961

Le mercredi 21 mars 2018 10:50:25 UTC-4, Anon Ymous a écrit :
>
> Hi,
>
> I am learning python by trying to create a small Django app.  I may have 
> found a bug related to Django and/or sqlite3.  If you are stackoverflow 
> folks then my initial post is there:  
> https://stackoverflow.com/questions/49361834/integrityerror-exception-in-deleteview-cbv
>
> My app really is just creating a small web site to add users and figure 
> out how to do CRUD operations in building user profiles.  I am using the 
> following setup:
>
> Django Version: 2.0.3
> Python Version: 3.6.3
> Installed Applications:
> ['django.contrib.admin',
> 'django.contrib.auth',
> 'django.contrib.contenttypes',
> 'django.contrib.sessions',
> 'django.contrib.messages',
> 'django.contrib.staticfiles',
> 'django_extensions',
> 'django.contrib.sites',
> 'allauth',
> 'allauth.account',
> 'allauth.socialaccount',
> 'auditlog',
> 'widget_tweaks',
> 'Members.apps.MembersConfig']
> Installed Middleware:
> ['django.middleware.security.SecurityMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> 'auditlog.middleware.AuditlogMiddleware']
>
> I am using sqlite3 as the DB backend..
>
> I can create the virgin project, tweak the settings file and do the 
> initial "makemigrations" and "migrate".  This, of course, creates the 
> Django "user" table(s).  I went about creating my own "profile" model that 
> "extends" the User model by creating a "oneToOne" field that points back to 
> User and specifies an "on_delete=models.CASCADE" clause:
>
> class Profile(models.Model):
> ...
> user = models.OneToOneField(
> User,
> on_delete=models.CASCADE,
> blank=False,
> null=False,
> )
> ...
>
> The thing is the table that is created is given the constraint:
>
> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY 
> DEFERRED,
>
> but the "on delete cascade" clause is missing.  
>
> I first noticed this when testing a profile delete operation.  I get a 
> foreign key constraint violation.  Looking into that led me here to you 
> guys.
>
> I have added that clause to the table:
>
> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) on delete cascade 
> DEFERRABLE INITIALLY DEFERRED,
>
> but I still get the constraint violation.  I did more digging last night 
> and see that at least one of the Django generated "user_*" tables also has 
> a foreign key relationship back to the "user" table and that is also 
> missing the cascade clause.
>
> My guesses at this instant include:
>
>- I have no idea what I am doing
>- Django or the sqlite3 backend *should* be handling the cascade ops 
>internally -- but isn't
>
> What am I missing?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0a368a90-da44-4af1-a5a1-d680e35d0b5d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


IntegrityError: FOREIGN KEY constraint failed: Django 2.0.3

2018-03-21 Thread Anon Ymous
Hi,

I am learning python by trying to create a small Django app.  I may have 
found a bug related to Django and/or sqlite3.  If you are stackoverflow 
folks then my initial post is there:  
https://stackoverflow.com/questions/49361834/integrityerror-exception-in-deleteview-cbv

My app really is just creating a small web site to add users and figure out 
how to do CRUD operations in building user profiles.  I am using the 
following setup:

Django Version: 2.0.3
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'auditlog',
'widget_tweaks',
'Members.apps.MembersConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'auditlog.middleware.AuditlogMiddleware']

I am using sqlite3 as the DB backend..

I can create the virgin project, tweak the settings file and do the initial 
"makemigrations" and "migrate".  This, of course, creates the Django "user" 
table(s).  I went about creating my own "profile" model that "extends" the 
User model by creating a "oneToOne" field that points back to User and 
specifies an "on_delete=models.CASCADE" clause:

class Profile(models.Model):
...
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
blank=False,
null=False,
)
...

The thing is the table that is created is given the constraint:

FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY 
DEFERRED,

but the "on delete cascade" clause is missing.  

I first noticed this when testing a profile delete operation.  I get a 
foreign key constraint violation.  Looking into that led me here to you 
guys.

I have added that clause to the table:

FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) on delete cascade 
DEFERRABLE INITIALLY DEFERRED,

but I still get the constraint violation.  I did more digging last night 
and see that at least one of the Django generated "user_*" tables also has 
a foreign key relationship back to the "user" table and that is also 
missing the cascade clause.

My guesses at this instant include:

   - I have no idea what I am doing
   - Django or the sqlite3 backend *should* be handling the cascade ops 
   internally -- but isn't
   
What am I missing?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/29eb69c4-8f01-4695-b72e-0914ff46422e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: get_or_create IntegrityError

2017-02-16 Thread Vijay Khemlani
As far as I know Postgres uses "sequences" for generating the model IDs.

If you set the id manually I think you are bypassing the sequence,
which doesn't autoincrement. So when you use the sequence the next
time the ID clashes.

pgAdmin should auto generate the id if you leave the field blank.

On 2/16/17, Matthew Pava <matthew.p...@iss.com> wrote:
> This is a fascinating issue, fellow Django users.
>
> I have a model called Lookups that is basically just an auto-generated pk
> and a name.  I added some data to that table using pgAdmin 3 since I'm using
> a PostgreSQL backend.
> One of my users then filled out a form that ran some code that would
> 'get_or_create' on the Lookups model.  It threw an IntegrityError saying
> that the Key (id)=# already exists.
> Upon further investigation, I realized that the id # was one that I had
> already entered manually in the database several days ago.  Only after the
> user kept running that form until the id incremented to one that did not
> exist did the IntegrityError go away.
>
> Maybe I entered the id manually in pgAdmin 3 instead of letting it do the
> auto-generation and that's why it broke?
>
> But Django was generating the proper SQL, so I can't imagine how Django
> could possibly be involved in addressing this issue:
>
> 'INSERT INTO "general_lookups" ("name") VALUES (%s) RETURNING
> "general_lookups"."id"'
>
>
> Maybe it's more a problem with PostgreSQL, but I wanted to share this with
> you in case you ever run into this issue.  I think for now, I should just
> use Django to enter data into the database, or test pgAdmin to
> auto-increment the id with manual data entry.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5d108192354c470ca56946d28ffe02b7%40ISS1.ISS.LOCAL.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CALn3ei3ZjhY%2BYfZyJUzZamA8t1t3JUw37_mGm%2BY4ymFG%2Bq%3D7Cw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


get_or_create IntegrityError

2017-02-16 Thread Matthew Pava
This is a fascinating issue, fellow Django users.

I have a model called Lookups that is basically just an auto-generated pk and a 
name.  I added some data to that table using pgAdmin 3 since I'm using a 
PostgreSQL backend.
One of my users then filled out a form that ran some code that would 
'get_or_create' on the Lookups model.  It threw an IntegrityError saying that 
the Key (id)=# already exists.
Upon further investigation, I realized that the id # was one that I had already 
entered manually in the database several days ago.  Only after the user kept 
running that form until the id incremented to one that did not exist did the 
IntegrityError go away.

Maybe I entered the id manually in pgAdmin 3 instead of letting it do the 
auto-generation and that's why it broke?

But Django was generating the proper SQL, so I can't imagine how Django could 
possibly be involved in addressing this issue:

'INSERT INTO "general_lookups" ("name") VALUES (%s) RETURNING 
"general_lookups"."id"'


Maybe it's more a problem with PostgreSQL, but I wanted to share this with you 
in case you ever run into this issue.  I think for now, I should just use 
Django to enter data into the database, or test pgAdmin to auto-increment the 
id with manual data entry.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5d108192354c470ca56946d28ffe02b7%40ISS1.ISS.LOCAL.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError column email is not unique

2016-07-02 Thread M Hashmi
@James

As per my understanding I did following. Now it is not adding email if it 
exists but also its not giving me any error.

class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')

def clean_email(self):
email = self.cleaned_data["email"]
if UserCheckout.objects.filter(email=email).exists():
raise forms.ValidationError("Please confirm emails addresses 
are the same.")
return email

def clean(self):
cleaned_data = super(GuestCheckoutForm, self).clean()
email = cleaned_data.get('email')
email2 = cleaned_data.get('email2')

if email and email2 and email != email2:
self.add_error('email2', forms.ValidationError('Please confirm 
emails addresses.'))

Rest of the code is same.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a63b8508-063d-405c-a7a2-67ab428bea21%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError column email is not unique

2016-07-02 Thread M Hashmi
@James

As per my understanding I did following. Now it is not adding email if it 
exists but also its not giving me any error.

class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')

def clean_email(self):
email = self.cleaned_data["email"]
if UserCheckout.objects.filter(email=email).exists():
raise forms.ValidationError("Please confirm emails addresses 
are the same.")
return email

def clean(self):
cleaned_data = super(GuestCheckoutForm, self).clean()
email = cleaned_data.get('email')
email2 = cleaned_data.get('email2')

if email and email2 and email != email2:
self.add_error('email2', forms.ValidationError('Please confirm 
emails addresses.'))

Rest of the code is same.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/12116f4b-01b5-4a33-9397-20819d11557d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError column email is not unique

2016-07-02 Thread M Hashmi
Thanks james for your kind response.
Intention is to set a single identifier for guest user account email. If 
that email exists then user can login or if doesn't he will have to get 
registered.
However let me implement your suggested code and I will respond you back.

Thanks again

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a9ffd1b7-cd56-4cf6-853f-66409c700074%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError column email is not unique

2016-07-02 Thread James Schneider
On Jul 2, 2016 7:23 AM, "M Hashmi" <mhashmi1...@gmail.com> wrote:
>
> I am working on my Checkout view with regular/guest user but getting hard
time to come around the integrity error. Idea is to let guest users
register with email only to checkout and I need to set the user email
unique.
>
> models.py
>
> from django.conf import settings
> from django.db import models
>
> class UserCheckout(models.Model):
> user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True,
blank=True)
> email = models.EmailField(unique=True)
>
> def __unicode__(self):
> return self.email
>
>
> forms.py
>
>
>
>
> from django import forms
> from django.contrib.auth import get_user_model
>
> User=get_user_model()
> class GuestCheckoutForm(forms.Form):
> email = forms.EmailField()
> email2 = forms.EmailField(label='Verify Email')
> def clean_email2(self):
> email = self.cleaned_data.get("email")
> email2 = self.cleaned_data.get("email2")
> if email == email2:
> user_exists = User.objects.filter(email=email).count()
> if user_exists != 0:

This should probably be

if UserCheckout.objects.filter(email=email).exists():

Do not use count() for checking whether or not a record exists. You are
also checking against User objects, and not against UserCheckout objects,
which doesn't make any sense based on the code you've posted.

> raise forms.ValidationError("User already exists. Please
login instead")
> return email2
> else:
> raise forms.ValidationError("Please confirm emails addresses
are the same.")
>
>
> In my cart views this is how I've rendered my form.
>
>
> def post(self, request, *args, **kwargs):
> self.object = self.get_object()
> form = self.get_form()
> if form.is_valid():
> email = form.cleaned_data.get("email")
> user_checkout = UserCheckout.objects.create(email=email)

Here is where the actual error is coming from. Your validation only checks
User for a unique email constraint, but then you create a UserCheckout
object without first checking the unique email constraint for UserCheckout.

> return self.form_valid(form)
> else:
> return self.form_invalid(form)
>
>
> I've registered the model with admin and in admin it shows the error for
duplication perfectly fine but from frontend I am getting error below:
>
>
> IntegrityError at /checkout/
> column email is not unique
> Request Method: POST
> Request URL:http://localhost:8000/checkout/
> Django Version: 1.8.13
> Exception Type: IntegrityError
> Exception Value:
> column email is not unique
> Exception Location:
C:\Users\Ali\ecomm\lib\site-packages\django\db\backends\sqlite3\base.py in
execute, line 318
> Python Executable:  C:\Users\Ali\ecomm\Scripts\python.EXE
> Python Version: 2.7.9
>

You'll only get this error if a user checks out using an email address that
matches an existing user, not an existing email that's been used to check
out before.

Is the intention to create both UserCheckout and User objects (which can
log in) through this process?

-James

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVbUJ_P0jFAeybUZPifEsbO7sE%3Dz%3DSU9%2BACdfDb_PX49g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


IntegrityError column email is not unique

2016-07-02 Thread M Hashmi
I am working on my Checkout view with regular/guest user but getting hard 
time to come around the integrity error. Idea is to let guest users 
register with email only to checkout and I need to set the user email 
unique. 

models.py

*from django.conf import settings
from django.db import models

class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
email = models.EmailField(unique=True)

def __unicode__(self):
return self.email*


forms.py




*from django import forms
from django.contrib.auth import** get_user_model*
*User=get_user_model()
class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')
def clean_email2(self):
email = self.cleaned_data.get("email")
email2 = self.cleaned_data.get("email2")
if email == email2:
user_exists = User.objects.filter(email=email).count()
if user_exists != 0:
raise forms.ValidationError("User already exists. Please login 
instead")
return email2
else:
raise forms.ValidationError("Please confirm emails addresses are 
the same.")*


In my cart views this is how I've rendered my form.


*def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
email = form.cleaned_data.get("email")
user_checkout = UserCheckout.objects.create(email=email)
return self.form_valid(form)
else:
return self.form_invalid(form)*


I've registered the model with admin and in admin it shows the error for 
duplication perfectly fine but from frontend I am getting error below:


*IntegrityError at /checkout/
column email is not unique
Request Method: POST
Request URL:http://localhost:8000/checkout/
Django Version: 1.8.13
Exception Type: IntegrityError
Exception Value:
column email is not unique
Exception Location: 
C:\Users\Ali\ecomm\lib\site-packages\django\db\backends\sqlite3\base.py in 
execute, line 318
Python Executable:  C:\Users\Ali\ecomm\Scripts\python.EXE
Python Version: 2.7.9*


Please advise.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b85b393e-1164-4d81-9269-5db4b287d64f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError for unique_together ?

2016-06-23 Thread Derek
Thanks Simon

Those definitions are the closest I can get to the original in terms of
type and relationship; what other info is needed?

That ticket refers to child models inline - not my situation.

Upgrading is on the cards - but still has to be budgeted for

Derek

On 23 June 2016 at 21:26, Simon Charette <charett...@gmail.com> wrote:

> Hi Derek,
>
> It's hard to tell without your exact model admin definitions but I suspect
> this
> might be related to #25987[1] which is fixed in Django 1.10.
>
> By the way you should at least upgrade to 1.8 as your Django version is
> not supported anymore and you could be exposed to multiple security issues.
>
> Cheers,
> Simon
>
> [1] https://code.djangoproject.com/ticket/25987
>
>
> Le jeudi 23 juin 2016 14:44:10 UTC-4, Derek a écrit :
>>
>> Hi
>>
>> I have a strange situation (with Django 1.6.11 and MySQL 5.5). Attempting
>> to save a new entry (from the admin) with values that violate the
>> duplication restriction imposed by the unique_together constraint - in
>> other words a duplicate of a record already in the database - raises an
>> IntegrityError (stack trace listed at the end).
>>
>> The model looks like something like :
>>
>> name = CharField(
>> max_length=100)
>> title = ForeignKey(Title)
>> city = CharField(
>> max_length=50,
>> default=CITY_DEFAULT),
>> occupation = ForeignKey(Occupation)
>>
>> class Meta:
>> ordering = ['name']
>> unique_together = (('name', 'title', 'city', 'occupation', ),)
>>
>> I have also tested this situation in the shell. A normal clean() will not
>> raise any error, but a full_clean() will. Does that imply the code path
>> being triggered by an attempted save from within the admin does not call
>> full_clean() or attempt to trap an IntegrityError?
>>
>> I should add that `city` field is not on the form to be filled in; and is
>> added in the clean method.
>>
>> What is the best / correct solution to this?
>>
>> Thanks!
>> Derek
>>
>>
>> Traceback:
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/core/handlers/base.py"
>> in get_response
>>   112. response = wrapped_callback(request,
>> *callback_args, **callback_kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>> in wrapper
>>   465. return self.admin_site.admin_view(view)(*args,
>> **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>> in _wrapped_view
>>   99. response = view_func(request, *args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/views/decorators/cache.py"
>> in _wrapped_view_func
>>   52. response = view_func(request, *args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/sites.py"
>> in inner
>>   198. return view(request, *args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>> in _wrapper
>>   29. return bound_func(*args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>> in _wrapped_view
>>   99. response = view_func(request, *args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>> in bound_func
>>   25. return func(self, *args2, **kwargs2)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/transaction.py"
>> in inner
>>   371. return func(*args, **kwargs)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>> in add_view
>>   1164. self.save_model(request, new_object, form, False)
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>> in save_model
>>   893. obj.save()
>> File
>> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
>> in save
>>   545.force_update=force_update,
>> 

Re: IntegrityError for unique_together ?

2016-06-23 Thread Simon Charette
Hi Derek,

It's hard to tell without your exact model admin definitions but I suspect 
this
might be related to #25987[1] which is fixed in Django 1.10.

By the way you should at least upgrade to 1.8 as your Django version is
not supported anymore and you could be exposed to multiple security issues.

Cheers,
Simon

[1] https://code.djangoproject.com/ticket/25987

Le jeudi 23 juin 2016 14:44:10 UTC-4, Derek a écrit :
>
> Hi
>
> I have a strange situation (with Django 1.6.11 and MySQL 5.5). Attempting 
> to save a new entry (from the admin) with values that violate the 
> duplication restriction imposed by the unique_together constraint - in 
> other words a duplicate of a record already in the database - raises an 
> IntegrityError (stack trace listed at the end).
>
> The model looks like something like :
>
> name = CharField(
> max_length=100)
> title = ForeignKey(Title)
> city = CharField(
> max_length=50,
> default=CITY_DEFAULT),
> occupation = ForeignKey(Occupation)
> 
> class Meta:
> ordering = ['name']
> unique_together = (('name', 'title', 'city', 'occupation', ),)
>
> I have also tested this situation in the shell. A normal clean() will not 
> raise any error, but a full_clean() will. Does that imply the code path 
> being triggered by an attempted save from within the admin does not call 
> full_clean() or attempt to trap an IntegrityError?
>
> I should add that `city` field is not on the form to be filled in; and is 
> added in the clean method.
>
> What is the best / correct solution to this?
>
> Thanks!
> Derek
>
>
> Traceback:
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/core/handlers/base.py"
>  
> in get_response
>   112. response = wrapped_callback(request, 
> *callback_args, **callback_kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>  
> in wrapper
>   465. return self.admin_site.admin_view(view)(*args, 
> **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>  
> in _wrapped_view
>   99. response = view_func(request, *args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/views/decorators/cache.py"
>  
> in _wrapped_view_func
>   52. response = view_func(request, *args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/sites.py"
>  
> in inner
>   198. return view(request, *args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>  
> in _wrapper
>   29. return bound_func(*args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>  
> in _wrapped_view
>   99. response = view_func(request, *args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
>  
> in bound_func
>   25. return func(self, *args2, **kwargs2)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/transaction.py"
>  
> in inner
>   371. return func(*args, **kwargs)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>  
> in add_view
>   1164. self.save_model(request, new_object, form, False)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
>  
> in save_model
>   893. obj.save()
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
>  
> in save
>   545.force_update=force_update, 
> update_fields=update_fields)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
>  
> in save_base
>   573. updated = self._save_table(raw, cls, force_insert, 
> force_update, using, update_fields)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
>  
> in _save_table
>   654. result = self._do_insert(cls._base_manager, using, 
> fields, update_pk, raw)
> File 
> "/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
>  
> in _do

IntegrityError for unique_together ?

2016-06-23 Thread Derek
Hi

I have a strange situation (with Django 1.6.11 and MySQL 5.5). Attempting
to save a new entry (from the admin) with values that violate the
duplication restriction imposed by the unique_together constraint - in
other words a duplicate of a record already in the database - raises an
IntegrityError (stack trace listed at the end).

The model looks like something like :

name = CharField(
max_length=100)
title = ForeignKey(Title)
city = CharField(
max_length=50,
default=CITY_DEFAULT),
occupation = ForeignKey(Occupation)

class Meta:
ordering = ['name']
unique_together = (('name', 'title', 'city', 'occupation', ),)

I have also tested this situation in the shell. A normal clean() will not
raise any error, but a full_clean() will. Does that imply the code path
being triggered by an attempted save from within the admin does not call
full_clean() or attempt to trap an IntegrityError?

I should add that `city` field is not on the form to be filled in; and is
added in the clean method.

What is the best / correct solution to this?

Thanks!
Derek


Traceback:
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
  112. response = wrapped_callback(request,
*callback_args, **callback_kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
in wrapper
  465. return self.admin_site.admin_view(view)(*args,
**kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
in _wrapped_view
  99. response = view_func(request, *args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/views/decorators/cache.py"
in _wrapped_view_func
  52. response = view_func(request, *args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/sites.py"
in inner
  198. return view(request, *args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
in _wrapper
  29. return bound_func(*args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
in _wrapped_view
  99. response = view_func(request, *args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/utils/decorators.py"
in bound_func
  25. return func(self, *args2, **kwargs2)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/transaction.py"
in inner
  371. return func(*args, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
in add_view
  1164. self.save_model(request, new_object, form, False)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/contrib/admin/options.py"
in save_model
  893. obj.save()
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
in save
  545.force_update=force_update,
update_fields=update_fields)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
in save_base
  573. updated = self._save_table(raw, cls, force_insert,
force_update, using, update_fields)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
in _save_table
  654. result = self._do_insert(cls._base_manager, using,
fields, update_pk, raw)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/base.py"
in _do_insert
  687.using=using, raw=raw)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/manager.py"
in _insert
  232. return insert_query(self.model, objs, fields, **kwargs)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/query.py"
in insert_query
  1514. return query.get_compiler(using=using).execute_sql(return_id)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
  903. cursor.execute(sql, params)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/backends/util.py"
in execute
  69. return super(CursorDebugWrapper, self).execute(sql,
params)
File
"/home/derek/.virtualenvs/reg/local/lib/python2.7/site-packages/django/db/backends/util.py"
in execute
  53. return self.cursor.execute(sql, params)
File
"/home/derek/.virtualenvs/reg/local/lib/p

Re: DJango 1.8 test case fails with IntegrityError error

2015-09-22 Thread Jose Paul
Hi Simon,

I am working on this support .

But the test case generates sql with null values for non null fields.

We cannot change the model ,because this is part of python ,i believe.

The problem might be the schema generated for the table from the model .
I can see only one field as non null in DB2.

Is this different from other database?.

Thanks,
Jose

On Monday, September 21, 2015 at 8:37:51 PM UTC+5:30, Simon Charette wrote:
>
> Hi Jose,
>
> I looks like ibm_db_django doesn't support Django 1.6+ yet 
> <https://pypi.python.org/pypi/ibm_db_django/>.
>
> Simon
>
> Le lundi 21 septembre 2015 07:14:39 UTC-4, Jose Paul a écrit :
>>
>> I am trying to run DJango 1.8 test cases with DB2
>>
>> Several insert statement fails 
>>
>> Here is the insert command generated by test case.
>>
>> INSERT INTO "AUTH_USER" ("PASSWORD", "LAST_LOGIN", "IS_SUPERUSER", 
>> "USERNAME", "FIRST_NAME", "LAST_NAME", "EMAIL", "IS_STAFF", "IS_ACTIVE", 
>> "DATE_JOINED") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
>>
>> Value : (None, None, True, u'superuser', None, None, None, False, True, 
>> u'2015-09-17 12:31:09.562000')
>>
>> ibm_db_dbi::IntegrityError: Statement Execute Failed: [IBM][CLI 
>> Driver][DB2/NT] SQL0407N  Assignment of a NULL value to a NOT NULL column 
>> "TBSPACEID=2, TABLEID=24, COLNO=1" is not allowed.  SQLSTATE=23502\r 
>> SQLCODE=-407
>>
>>
>> Except last_login none of the field are nullable .
>> But still DJango testcase generate insert statement  as above and pass 
>> None as value which fails .
>>
>> Why this happens ?.
>> Why correct non null values are not generated for non null field .
>>
>> Please help .Thanks ,
>> Jose
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0a3e908b-13ee-43f0-a7d5-57769472c6fb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: DJango 1.8 test case fails with IntegrityError error

2015-09-21 Thread Simon Charette
Hi Jose,

I looks like ibm_db_django doesn't support Django 1.6+ yet 
<https://pypi.python.org/pypi/ibm_db_django/>.

Simon

Le lundi 21 septembre 2015 07:14:39 UTC-4, Jose Paul a écrit :
>
> I am trying to run DJango 1.8 test cases with DB2
>
> Several insert statement fails 
>
> Here is the insert command generated by test case.
>
> INSERT INTO "AUTH_USER" ("PASSWORD", "LAST_LOGIN", "IS_SUPERUSER", 
> "USERNAME", "FIRST_NAME", "LAST_NAME", "EMAIL", "IS_STAFF", "IS_ACTIVE", 
> "DATE_JOINED") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
>
> Value : (None, None, True, u'superuser', None, None, None, False, True, 
> u'2015-09-17 12:31:09.562000')
>
> ibm_db_dbi::IntegrityError: Statement Execute Failed: [IBM][CLI 
> Driver][DB2/NT] SQL0407N  Assignment of a NULL value to a NOT NULL column 
> "TBSPACEID=2, TABLEID=24, COLNO=1" is not allowed.  SQLSTATE=23502\r 
> SQLCODE=-407
>
>
> Except last_login none of the field are nullable .
> But still DJango testcase generate insert statement  as above and pass 
> None as value which fails .
>
> Why this happens ?.
> Why correct non null values are not generated for non null field .
>
> Please help .Thanks ,
> Jose
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/414d880d-d849-496a-9f96-a03a51d9baae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: DJango 1.8 test case fails with IntegrityError error

2015-09-21 Thread Jose Paul


Please see the call stack too ,for one of the error


"C:\Users\IBM_ADMIN\PythonWorkspace\DJangoTestCases\src\DJangoTestCases\tests\admin_filters\tests.py",
 
line 229, in setUp

self.alfred = User.objects.create_user('alfred', 'alf...@example.com')

File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 
187, in create_user

**extra_fields)

File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 
182, in _create_user

user.save(using=self._db)

File "C:\Python27\lib\site-packages\django\db\models\base.py", line 710, in 
save

force_update=force_update, update_fields=update_fields)

File "C:\Python27\lib\site-packages\django\db\models\base.py", line 738, in 
save_base

updated = self._save_table(raw, cls, force_insert, force_update, using, 
update_fields)

File "C:\Python27\lib\site-packages\django\db\models\base.py", line 822, in 
_save_table

result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Python27\lib\site-packages\django\db\models\base.py", line 861, in 
_do_insert

using=using, raw=raw)

File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 127, 
in manager_method

return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py", line 920, 
in _insert

return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 
974, in execute_sql

cursor.execute(sql, params)

File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 67, 
in execute

return self.cursor.execute(sql, params)

File 
"c:\python27\lib\site-packages\ibm_db_django-1.0.7-py2.7.egg\ibm_db_django\pybase.py",
 
line 165, in execute

six.reraise(utils.IntegrityError, utils.IntegrityError( *tuple( six.PY3 and 
e.args or ( e._message, ) ) ), sys.exc_info()[2])

File 
"c:\python27\lib\site-packages\ibm_db_django-1.0.7-py2.7.egg\ibm_db_django\pybase.py",
 
line 161, in execute

return super( DB2CursorWrapper, self ).execute( operation, parameters )

File 
"c:\python27\lib\site-packages\ibm_db-2.0.5.1-py2.7.egg\ibm_db_dbi.py", 
line 1335, in execute

self._execute_helper(parameters)

File 
"c:\python27\lib\site-packages\ibm_db-2.0.5.1-py2.7.egg\ibm_db_dbi.py", 
line 1247, in _execute_helper

raise self.messages[len(self.messages) - 1]

IntegrityError: Statement Execute Failed: [IBM][CLI Driver][DB2/NT] 
SQL0407N Assignment of a NULL value to a NOT NULL column "TBSPACEID=2, 
TABLEID=24, COLNO=5" is not allowed. SQLSTATE=23502\r SQLCODE=-407




On Monday, September 21, 2015 at 4:44:39 PM UTC+5:30, Jose Paul wrote:
>
> I am trying to run DJango 1.8 test cases with DB2
>
> Several insert statement fails 
>
> Here is the insert command generated by test case.
>
> INSERT INTO "AUTH_USER" ("PASSWORD", "LAST_LOGIN", "IS_SUPERUSER", 
> "USERNAME", "FIRST_NAME", "LAST_NAME", "EMAIL", "IS_STAFF", "IS_ACTIVE", 
> "DATE_JOINED") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
>
> Value : (None, None, True, u'superuser', None, None, None, False, True, 
> u'2015-09-17 12:31:09.562000')
>
> ibm_db_dbi::IntegrityError: Statement Execute Failed: [IBM][CLI 
> Driver][DB2/NT] SQL0407N  Assignment of a NULL value to a NOT NULL column 
> "TBSPACEID=2, TABLEID=24, COLNO=1" is not allowed.  SQLSTATE=23502\r 
> SQLCODE=-407
>
>
> Except last_login none of the field are nullable .
> But still DJango testcase generate insert statement  as above and pass 
> None as value which fails .
>
> Why this happens ?.
> Why correct non null values are not generated for non null field .
>
> Please help .Thanks ,
> Jose
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7d38d707-138b-4acc-baab-089ae089c228%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


DJango 1.8 test case fails with IntegrityError error

2015-09-21 Thread Jose Paul
I am trying to run DJango 1.8 test cases with DB2

Several insert statement fails 

Here is the insert command generated by test case.

INSERT INTO "AUTH_USER" ("PASSWORD", "LAST_LOGIN", "IS_SUPERUSER", 
"USERNAME", "FIRST_NAME", "LAST_NAME", "EMAIL", "IS_STAFF", "IS_ACTIVE", 
"DATE_JOINED") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)

Value : (None, None, True, u'superuser', None, None, None, False, True, 
u'2015-09-17 12:31:09.562000')

ibm_db_dbi::IntegrityError: Statement Execute Failed: [IBM][CLI 
Driver][DB2/NT] SQL0407N  Assignment of a NULL value to a NOT NULL column 
"TBSPACEID=2, TABLEID=24, COLNO=1" is not allowed.  SQLSTATE=23502\r 
SQLCODE=-407


Except last_login none of the field are nullable .
But still DJango testcase generate insert statement  as above and pass None 
as value which fails .

Why this happens ?.
Why correct non null values are not generated for non null field .

Please help .Thanks ,
Jose

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c6f5ed39-4084-4a45-9b97-24b680b45ebc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


IntegrityError : AUTH_USER DJango 1.8

2015-09-21 Thread Jose Paul
Daer All,

I am trying to run DJango 1.8 test cases .

I am getting several IntegrityError  error  on AUTH_USER table .


SQL generated by test case

INSERT INTO "AUTH_USER" ("PASSWORD", "LAST_LOGIN", "IS_SUPERUSER", 
"USERNAME", "FIRST_NAME", "LAST_NAME", "EMAIL", "IS_STAFF", "IS_ACTIVE", 
"DATE_JOINED") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)

Values it tries to insert 

(None, None, True, u'superuser', None, None, None, False, True, 
u'2015-09-17 12:31:09.562000')

Error 
ibm_db_dbi::IntegrityError: Statement Execute Failed: [IBM][CLI 
Driver][DB2/NT] SQL0407N  Assignment of a NULL value to a NOT NULL column 
"TBSPACEID=2, TABLEID=24, COLNO=1" is not allowed.  SQLSTATE=23502\r 
SQLCODE=-407

In the table only LAST_LOGIN is nullable field .
But the sql generated tries to insert none to other fields .DB2 throw error 
because of this .

I think there is some problem in the sql generated .
I am getting several same  errors on this table .

Can someone comment please .

Thanks
Jose



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/8e21f914-52c9-419d-8646-678d8aef96e7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Solved: save as new in the Admin with 1:1 inlines causes IntegrityError

2014-10-17 Thread Mike Dewhirst
I discovered a unicode problem related to the degree symbol (°) when 
running under Python 2.7 and dealt with that. It somehow fixed the 
IntegrityError.


One of those things I guess

AWTEW

Mike

On 15/10/2014 9:40 AM, Mike Dewhirst wrote:

Using Django 1.6.7, in the Admin if I change the name of an object (in
this case "substance") with 1:1 relationships and click [Save as new] I
get an integrity error[1]. This was working in Django 1.5.x.

Before I put in the effort to roll back to 1.5 for proof I thought I'd
check the docs and found this with a "Changed in Django 1.6" note ...

https://docs.djangoproject.com/en/1.6/ref/models/instances/#how-django-knows-to-update-vs-insert


Does anyone have a suggestion?

The interactive traceback indicates my save() method on one of the 1:1
models (in this case "gas") is triggering the problem. See below.

Thanks for any pointers

Mike

- - - - - - - - - - - -



--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/54410C83.7000201%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


save as new in the Admin with 1:1 inlines causes IntegrityError

2014-10-14 Thread Mike Dewhirst
 "C:\Users\mike\env\xxdx\lib\site-packages\django\forms\models.py" 
in save_new

  877. obj.save()
File "C:\Users\mike\env\xxdx\ssds\substance\models\gas.py" in save
  168. super(Gas, self).save(*args, **kwargs)

#
# here is the entire save method containing line 168 above
#
159 def save(self, *args, **kwargs):
160 self.get_oxidizing_comment()
161 if not self.n_equivalency:
162 casno = self.cas()
163 if casno:
164 try:
165 self.n_equivalency = N_EQUIVALENCY[casno]
166 except KeyError:
167 pass
168 super(Gas, self).save(*args, **kwargs)
169 if self.ozone:
170 sdsutils.insert_ozone_reg(self)
#
#

File "C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\base.py" 
in save
  545.force_update=force_update, 
update_fields=update_fields)
File "C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\base.py" 
in save_base
  573. updated = self._save_table(raw, cls, force_insert, 
force_update, using, update_fields)
File "C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\base.py" 
in _save_table
  654. result = self._do_insert(cls._base_manager, using, 
fields, update_pk, raw)
File "C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\base.py" 
in _do_insert

  687.using=using, raw=raw)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\manager.py" 
in _insert

  232. return insert_query(self.model, objs, fields, **kwargs)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\query.py" in 
insert_query

  1514. return query.get_compiler(using=using).execute_sql(return_id)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\models\sql\compiler.py" 
in execute_sql

  903. cursor.execute(sql, params)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\backends\util.py" in 
execute
  69. return super(CursorDebugWrapper, self).execute(sql, 
params)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\backends\util.py" in 
execute

  53. return self.cursor.execute(sql, params)
File "C:\Users\mike\env\xxdx\lib\site-packages\django\db\utils.py" in 
__exit__

  99. six.reraise(dj_exc_type, dj_exc_value, traceback)
File 
"C:\Users\mike\env\xxdx\lib\site-packages\django\db\backends\util.py" in 
execute

  53. return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /admin/substance/substance/17/
Exception Value: duplicate key value violates unique constraint 
"substance_gas_substance_id_key"

DETAIL:  Key (substance_id)=(22) already exists.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/543DA667.7030304%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


IntegrityError

2014-03-28 Thread Warren Jacobus
Hi,

I've been trying to create a simple flight booking system but seem to have 
trouble.

When trying to create a Flight object it says that aircraft_id may not be 
null
and when trying to set a Passenger object it says flight_id may not be null


Here is my models.py file

from django.db import models
  2 from django.utils import timezone
  3 import datetime
  4 
 # Create your models here.
class Aircraft(models.Model):
   aircraft_model = models.CharField(max_length=30)
   aircraft_num_seats = models.IntegerField(default=50)
   available = models.BooleanField(default=False)
 
   def __unicode__(self):
   return "%s , %d , %s" % 
(self.aircraft_model,self.aircraft_num_seats,self.available)
 
class Passenger(models.Model):
   passenger_name = models.CharField(max_length=30,default="John")
   passenger_surname= models.CharField(max_length=30,default="Doe")
   def __unicode__(self):
   return "%s %s"% (self.passenger_name,self.passenger_surname)
  
  
class Flight(models.Model):
   aircraft = models.ForeignKey(Aircraft)
   passengers = models.ManyToManyField(Passenger)
  
   num_seat_available = models.IntegerField(default=50) # requires method 
to calculate this
   departFrom = models.CharField(max_length=50)
   departTo = models.CharField(max_length=50)
   departTime = models.DateTimeField(default=timezone.now())
   flight_duration = models.IntegerField(default=0) # requires method to 
calculate this
   arrival = models.DateTimeField(default = timezone.now())
   cancel_flight = models.BooleanField(default=False)
  
   def __unicode__(self):
  return "%s --> %s , %s --> %s" % 
(self.departFrom,self.departTo,str(self.departTime),str(self.arrival))

Thanks

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/edab5b92-756f-4c90-a26e-75cedbe7d2af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError

2014-03-28 Thread Lukas Nemec

You need to re-create your database.

Good way is to create a script that populates your DB with some test 
data, and drop DB after a major change, or when something breaks, and 
re-create it.


For now, you should try to create different DB (to preserve your data) 
and do

python manage.py syncdb


Lukas


On 03/28/2014 03:24 PM, Warren Jacobus wrote:

Hi,

I've been trying to create a simple flight booking system but seem to 
have trouble.


When trying to create a Flight object it says that aircraft_id may not 
be null
and when trying to set a Passenger object it says flight_id may not be 
null



Here is my models.py file

from django.db import models
  2 from django.utils import timezone
  3 import datetime
  4
 # Create your models here.
class Aircraft(models.Model):
   aircraft_model = models.CharField(max_length=30)
   aircraft_num_seats = models.IntegerField(default=50)
   available = models.BooleanField(default=False)
   def __unicode__(self):
   return "%s , %d , %s" % 
(self.aircraft_model,self.aircraft_num_seats,self.available)

class Passenger(models.Model):
   passenger_name = models.CharField(max_length=30,default="John")
   passenger_surname= models.CharField(max_length=30,default="Doe")
   def __unicode__(self):
   return "%s %s"% (self.passenger_name,self.passenger_surname)
class Flight(models.Model):
   aircraft = models.ForeignKey(Aircraft)
   passengers = models.ManyToManyField(Passenger)
   num_seat_available = models.IntegerField(default=50) # requires 
method to calculate this

   departFrom = models.CharField(max_length=50)
   departTo = models.CharField(max_length=50)
   departTime = models.DateTimeField(default=timezone.now())
   flight_duration = models.IntegerField(default=0) # requires method 
to calculate this

   arrival = models.DateTimeField(default = timezone.now())
   cancel_flight = models.BooleanField(default=False)
   def __unicode__(self):
  return "%s --> %s , %s --> %s" % 
(self.departFrom,self.departTo,str(self.departTime),str(self.arrival))


Thanks
--
You received this message because you are subscribed to the Google 
Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 
an email to django-users+unsubscr...@googlegroups.com 
.
To post to this group, send email to django-users@googlegroups.com 
.

Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/edab5b92-756f-4c90-a26e-75cedbe7d2af%40googlegroups.com 
.

For more options, visit https://groups.google.com/d/optout.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/53358BDF.8050806%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError --- NOT NULL constraint failed: books_book.publication_date

2014-03-26 Thread Sami Razi
i used

python manage.py sqlall 

you're right sam, when i set null to true, it doesn't really change. 
thank you so very much.
i'm a newbie with databases and i don't know what statements sould i use... 
i don't know the syntax...
i would install south. thank you.

 thank you so very much.
but i'm a newbie with databases, should i type something like this in the 
dbshell? 

UPDATE BOOKS_BOOK SET PUBLICATION_DATE NULL=TRUE

On Wednesday, March 26, 2014 11:40:03 AM UTC-4, Sam Walters wrote:
>
> Did you perhaps change the schema of the database after you had created it.
>
> Eg: added null=True as a constraint after creating the table?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b25a8c37-5f05-4f9a-bd5b-d9875469db7a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError --- NOT NULL constraint failed: books_book.publication_date

2014-03-26 Thread Sam Walters
Did you perhaps change the schema of the database after you had created it.

Eg: added null=True as a constraint after creating the table?

If so check the db sheme using:
python manage.py sqlall 

It sounds simple enough. You will have to go into the db shell and update
your schema manually.

using

python manage.py dbshell

If you're developing something where the schema is always getting modified
and you dont want to manually update table constraints
look into

django south addon.

hope this helps


On Wed, Mar 26, 2014 at 3:31 PM, Sami Razi <s.sami.ghay...@gmail.com> wrote:

>
>  i'm learning django using djangobook <http://djangobook.com>, in chapter
> 6, i'm having this error:
>
>   IntegrityError at /admin/books/book/add/
>
>   NOT NULL constraint failed: books_book.publication_date
>
>
> it seems i should set null=True for  publication_date field. but i did it 
> already, this is my models.py:
>
>
> from django.db import models
>
> class Publisher(models.Model):
> name = models.CharField(max_length=30)
> address = models.CharField(max_length=50)
> city = models.CharField(max_length=60)
> state_province = models.CharField(max_length=30)
> country = models.CharField(max_length=50)
> website = models.URLField()
>
> def __unicode__(self):
> return self.name
>
> class Author(models.Model):
> first_name = models.CharField(max_length=30)
> last_name = models.CharField(max_length=40)
> email = models.EmailField(blank=True, verbose_name='e-mail')
>
> def __unicode__(self):
> return u'%s %s' % (self.first_name, self.last_name)
>
> class Book(models.Model):
> title = models.CharField(max_length=100)
> authors = models.ManyToManyField(Author)
> publisher = models.ForeignKey(Publisher)
>publication_date = models.DateField(blank=True, *null=True*)
>
> def __unicode__(self):
> return self.title
>
>
> what am i doing wrong?
> i googled the error message but didn't find a related answer.
> thank you for your help.
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/87ef0e56-f90f-4097-8a2c-e747ac874b71%40googlegroups.com<https://groups.google.com/d/msgid/django-users/87ef0e56-f90f-4097-8a2c-e747ac874b71%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAMbLS2-4SLs_OqCrKj4qQm_Xif2oDsCG97RJWDmrAFUR%2BCuxNA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


IntegrityError --- NOT NULL constraint failed: books_book.publication_date

2014-03-26 Thread Sami Razi
   
 i'm learning django using djangobook <http://djangobook.com>, in chapter 
6, i'm having this error:

  IntegrityError at /admin/books/book/add/ 

  NOT NULL constraint failed: books_book.publication_date


it seems i should set null=True for  publication_date field. but i did it 
already, this is my models.py:

 
from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
  
def __unicode__(self):
return self.name
  
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
 
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
 
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
   publication_date = models.DateField(blank=True, *null=True*)
  
def __unicode__(self):
return self.title
  

what am i doing wrong?
i googled the error message but didn't find a related answer.
thank you for your help.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/87ef0e56-f90f-4097-8a2c-e747ac874b71%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IntegrityError with proxy model but not with parent?

2013-09-26 Thread Rafael Durán Castañeda
Hi,

As long as I know, a model form needs the fields to be included in order to get 
validation working, so I suspect you did something like this:

class ProxyForm(forms.ModelForm):
class Meta:
model = models.Myproxy
fields = ('name', )

Since stuff field is not included in the form fields validation doesn't work 
for it, however you can get it working with something like this:

class ProxyForm(forms.ModelForm):
stuff = forms.CharField(widget=forms.HiddenInput, initial='stuff')
class Meta:
model = models.Myproxy
fields = ('name', 'stuff',)

Thought you probably need customize validation/error messages or you will get 
messages like:

Parent with this Name and Stuff already exists.

for a form that does´t include stuff as a hidden input.

HTH
El 25/09/2013, a las 20:15, Derek <gamesb...@gmail.com> escribió:

> I am working with a proxy model that does not seem to work with the 
> 'unique_together' of the model being proxied.
> 
> What I have is:
> 
> class Parent(Model):
> id = AutoField(primary_key=True)
> name = CharField()
> stuff = CharField()
> 
> class Meta:
> ordering = ['name']
> unique_together = (('name', 'stuff'),)
> 
> class Myproxy(Parent):
> 
> class Meta:
> proxy = True
> 
> def __init__(self, *args, **kwargs):
> super(Myproxy, self).__init__(*args, **kwargs)
> self.stuff = "test"
> 
> If I use the Parent model and try to enter, 'myname' and 'test' as the 
> name/stuff entries twice, I get the usual warning on the second attempt; the 
> admin telling me that this model entry already exists.
> 
> However, if I try the same thing on the Myproxy model (which has a form 
> without the stuff field; as its meant to be a preset value), I get an:
> 
> IntegrityError at /admin/../add/
> (1062, "Duplicate entry 'myname-test' for key 'name'")
> 
> The stack trace is as follows:
> 
> Traceback:
> File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in 
> get_response
>   115. response = callback(request, *callback_args, 
> **callback_kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" 
> in wrapper
>   372. return self.admin_site.admin_view(view)(*args, 
> **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in 
> _wrapped_view
>   91. response = view_func(request, *args, **kwargs)
> File 
> "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in 
> _wrapped_view_func
>   89. response = view_func(request, *args, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" 
> in inner
>   202. return view(request, *args, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in 
> _wrapper
>   25. return bound_func(*args, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in 
> _wrapped_view
>   91. response = view_func(request, *args, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in 
> bound_func
>   21. return func(self, *args2, **kwargs2)
> File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in 
> inner
>   223. return func(*args, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" 
> in add_view
>   1007. self.save_model(request, new_object, form, False)
> File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" 
> in save_model
>   740. obj.save()
> File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
>   546.force_update=force_update, 
> update_fields=update_fields)
> File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in 
> save_base
>   591.update_fields=update_fields)
> File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in 
> save_base
>   650. result = manager._insert([self], fields=fields, 
> return_id=update_pk, using=using, raw=raw)
> File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in 
> _insert
>   215. return insert_query(self.model, objs, fields, **kwargs)
> File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in 
> insert_query
>   1675. return query.get_

IntegrityError with proxy model but not with parent?

2013-09-25 Thread Derek
I am working with a proxy model that does not seem to work with the
'unique_together' of the model being proxied.

What I have is:

class Parent(Model):
id = AutoField(primary_key=True)
name = CharField()
stuff = CharField()

class Meta:
ordering = ['name']
unique_together = (('name', 'stuff'),)

class Myproxy(Parent):

class Meta:
proxy = True

def __init__(self, *args, **kwargs):
super(Myproxy, self).__init__(*args, **kwargs)
self.stuff = "test"

If I use the Parent model and try to enter, 'myname' and 'test' as the
name/stuff entries twice, I get the usual warning on the second attempt;
the admin telling me that this model entry already exists.

However, if I try the same thing on the Myproxy model (which has a form
without the stuff field; as its meant to be a preset value), I get an:

IntegrityError at /admin/../add/
(1062, "Duplicate entry 'myname-test' for key 'name'")

The stack trace is as follows:

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
  115. response = callback(request, *callback_args,
**callback_kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in
wrapper
  372. return self.admin_site.admin_view(view)(*args,
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in
_wrapped_view
  91. response = view_func(request, *args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py"
in _wrapped_view_func
  89. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py"
in inner
  202. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in
_wrapper
  25. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in
_wrapped_view
  91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in
bound_func
  21. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in
inner
  223. return func(*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in
add_view
  1007. self.save_model(request, new_object, form, False)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in
save_model
  740. obj.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in
save
  546.force_update=force_update,
update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in
save_base
  591.update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in
save_base
  650. result = manager._insert([self], fields=fields,
return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py"
in _insert
  215. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in
insert_query
  1675. return query.get_compiler(using=using).execute_sql(return_id)
File
"/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py"
in execute_sql
  937. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in
execute
  41. return self.cursor.execute(sql, params)
File
"/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py"
in execute
  122. six.reraise(utils.IntegrityError,
utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File
"/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py"
in execute
  120. return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py" in execute
  174. self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py" in
defaulterrorhandler
  36. raise errorclass, errorvalue


(FTR, I have also tried overriding the model save(), but again get an
IntegrityError, instead of Django performing the expected check).

I am obviously missing some key piece of code, but cannot see what it is.

Thanks
Derek

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe fro

Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-29 Thread isachin
hey guys, got the solution:

for each field to validate, I wrote a validate function:

code snippet:

def clean_:
try:
UserProfile.objects.get(phone_num=self.cleaned_data[''])
except UserProfile.DoesNotExist:
return self.cleaned_data[""]
raise forms.ValidationError(("FIELD VALUE already exist"))



On Sat, Apr 27, 2013 at 6:41 PM, isachin <iclcools...@gmail.com> wrote:

> @ Kelly: thank you very much for pointing me to django's source code.
>
> Yes I got that validation done and applied the same code for validation.
> Below is the snippet :
>
>profile.serial_num = self.cleaned_data['phone_num']
> try:
> profile._default_manager.get(phone_num=profile.serial_num)
> except UserProfile.DoesNotExist:
> profile.serial_num = profile.phone_num
> raise forms.ValidationError("Phone number already exist")
>
> @ all
>
> Now the next problem is, similar snippet appears in
>
> */site-packages/django/contrib/auth/forms.py*
>
> throws an error in the template form itself, but my code only shows up
> error in django's traceback, how can I bring it to front ?
> so that as soon as one fills phone number field it and press *submit, *it
> should say 'Phone number already exist'.
>
> m I doing wrong in using UserCreationForm ? or UserProfile. I m using
> user.get_profile() for profile fields.
>
>
>
> On Thu, Apr 25, 2013 at 7:09 PM, Kelly Nicholes <kelbolici...@gmail.com>wrote:
>
>> If you ever want to know how the UserCreationForm works, the source is
>> always available not only on your machine but also on
>> https://github.com/django/django/blob/master/django/contrib/auth/models.py
>>
>>
>> On Wednesday, April 24, 2013 9:27:39 AM UTC-6, sachin wrote:
>>>
>>> Hello,
>>>
>>> I m extending my auth user model to add addition entries like phone
>>> numbers and emp_id. In the model I m marking both the fields as unique=True.
>>> Form generation is using UserCreationForm. But whenever I try to save
>>> same phone number or emp_id it throws
>>>
>>> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>>>
>>> How to handle this error and show it to user during form input?
>>>
>>> Also how do the same UserCreationForm validates duplicate entry for
>>> username etc ??
>>>
>>>  --
>> You received this message because you are subscribed to a topic in the
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit
>> https://groups.google.com/d/topic/django-users/EaYF9DEptLo/unsubscribe?hl=en
>> .
>> To unsubscribe from this group and all its topics, send an email to
>> django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>
>
> --
> Sachin
>



-- 
Sachin

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-27 Thread isachin
@ Kelly: thank you very much for pointing me to django's source code.

Yes I got that validation done and applied the same code for validation.
Below is the snippet :

   profile.serial_num = self.cleaned_data['phone_num']
try:
profile._default_manager.get(phone_num=profile.serial_num)
except UserProfile.DoesNotExist:
profile.serial_num = profile.phone_num
raise forms.ValidationError("Phone number already exist")

@ all

Now the next problem is, similar snippet appears in

*/site-packages/django/contrib/auth/forms.py*

throws an error in the template form itself, but my code only shows up
error in django's traceback, how can I bring it to front ?
so that as soon as one fills phone number field it and press *submit, *it
should say 'Phone number already exist'.

m I doing wrong in using UserCreationForm ? or UserProfile. I m using
user.get_profile() for profile fields.



On Thu, Apr 25, 2013 at 7:09 PM, Kelly Nicholes <kelbolici...@gmail.com>wrote:

> If you ever want to know how the UserCreationForm works, the source is
> always available not only on your machine but also on
> https://github.com/django/django/blob/master/django/contrib/auth/models.py
>
>
> On Wednesday, April 24, 2013 9:27:39 AM UTC-6, sachin wrote:
>>
>> Hello,
>>
>> I m extending my auth user model to add addition entries like phone
>> numbers and emp_id. In the model I m marking both the fields as unique=True.
>> Form generation is using UserCreationForm. But whenever I try to save
>> same phone number or emp_id it throws
>>
>> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>>
>> How to handle this error and show it to user during form input?
>>
>> Also how do the same UserCreationForm validates duplicate entry for
>> username etc ??
>>
>>  --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/EaYF9DEptLo/unsubscribe?hl=en
> .
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>



-- 
Sachin

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-25 Thread Kelly Nicholes
If you ever want to know how the UserCreationForm works, the source is 
always available not only on your machine but also on 
https://github.com/django/django/blob/master/django/contrib/auth/models.py


On Wednesday, April 24, 2013 9:27:39 AM UTC-6, sachin wrote:
>
> Hello,
>
> I m extending my auth user model to add addition entries like phone 
> numbers and emp_id. In the model I m marking both the fields as unique=True.
> Form generation is using UserCreationForm. But whenever I try to save same 
> phone number or emp_id it throws 
>
> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>
> How to handle this error and show it to user during form input?
>
> Also how do the same UserCreationForm validates duplicate entry for 
> username etc ??
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-25 Thread isachin
Thanx Siddharth and Pradeep, I will try both suggestion and let you know


On Thu, Apr 25, 2013 at 2:07 PM, Pradeep Kumar <nprade...@gmail.com> wrote:

> Hi Sachin,
>
> If you have added the unique=True later and migrated the existing table, I
> would also suggest you to first clean up  the NULL and duplicate entries
> using a script or even from shell.
>
> After doing that you can use
> *  try: *
>  # your code here
> *  except IntegrityError: *
>  #create variables here to send user error message
>
> One more pointer - try checking for the user input( X.object.filter
> method) in the unique fields in database before performing .save
>
>
> On Thu, Apr 25, 2013 at 1:34 PM, Siddharth Ghumre <
> siddharth.ghumr...@gmail.com> wrote:
>
>> hi Sachin,
>>
>> Please use django's form clean method in order to validate your phone_num
>> field.
>> You can also override the django's clean method by using your own
>> clean_phone_field method.
>> Please refer the link:-
>>
>> https://docs.djangoproject.com/en/dev/ref/forms/validation/
>>
>> I am sure that a small googling on overriding the clean method in django
>> form class will defiantly help you.
>>
>> -Siddharth
>>
>>
>> On Wed, Apr 24, 2013 at 8:57 PM, sachin <iclcools...@gmail.com> wrote:
>>
>>> Hello,
>>>
>>> I m extending my auth user model to add addition entries like phone
>>> numbers and emp_id. In the model I m marking both the fields as unique=True.
>>> Form generation is using UserCreationForm. But whenever I try to save
>>> same phone number or emp_id it throws
>>>
>>> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>>>
>>> How to handle this error and show it to user during form input?
>>>
>>> Also how do the same UserCreationForm validates duplicate entry for
>>> username etc ??
>>>
>>>  --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To post to this group, send email to django-users@googlegroups.com.
>>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>>> For more options, visit https://groups.google.com/groups/opt_out.
>>>
>>>
>>>
>>
>>  --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>  --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/EaYF9DEptLo/unsubscribe?hl=en
> .
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>



-- 
Sachin

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-25 Thread Pradeep Kumar
Hi Sachin,

If you have added the unique=True later and migrated the existing table, I
would also suggest you to first clean up  the NULL and duplicate entries
using a script or even from shell.

After doing that you can use
*  try: *
 # your code here
*  except IntegrityError: *
 #create variables here to send user error message

One more pointer - try checking for the user input( X.object.filter method)
in the unique fields in database before performing .save


On Thu, Apr 25, 2013 at 1:34 PM, Siddharth Ghumre <
siddharth.ghumr...@gmail.com> wrote:

> hi Sachin,
>
> Please use django's form clean method in order to validate your phone_num
> field.
> You can also override the django's clean method by using your own
> clean_phone_field method.
> Please refer the link:-
>
> https://docs.djangoproject.com/en/dev/ref/forms/validation/
>
> I am sure that a small googling on overriding the clean method in django
> form class will defiantly help you.
>
> -Siddharth
>
>
> On Wed, Apr 24, 2013 at 8:57 PM, sachin <iclcools...@gmail.com> wrote:
>
>> Hello,
>>
>> I m extending my auth user model to add addition entries like phone
>> numbers and emp_id. In the model I m marking both the fields as unique=True.
>> Form generation is using UserCreationForm. But whenever I try to save
>> same phone number or emp_id it throws
>>
>> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>>
>> How to handle this error and show it to user during form input?
>>
>> Also how do the same UserCreationForm validates duplicate entry for
>> username etc ??
>>
>>  --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-25 Thread Siddharth Ghumre
hi Sachin,

Please use django's form clean method in order to validate your phone_num
field.
You can also override the django's clean method by using your own
clean_phone_field method.
Please refer the link:-

https://docs.djangoproject.com/en/dev/ref/forms/validation/

I am sure that a small googling on overriding the clean method in django
form class will defiantly help you.

-Siddharth


On Wed, Apr 24, 2013 at 8:57 PM, sachin <iclcools...@gmail.com> wrote:

> Hello,
>
> I m extending my auth user model to add addition entries like phone
> numbers and emp_id. In the model I m marking both the fields as unique=True.
> Form generation is using UserCreationForm. But whenever I try to save same
> phone number or emp_id it throws
>
> *IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*
>
> How to handle this error and show it to user during form input?
>
> Also how do the same UserCreationForm validates duplicate entry for
> username etc ??
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




handling IntegrityError: Duplicate entry in UserCreationForm

2013-04-24 Thread sachin
Hello,

I m extending my auth user model to add addition entries like phone numbers 
and emp_id. In the model I m marking both the fields as unique=True.
Form generation is using UserCreationForm. But whenever I try to save same 
phone number or emp_id it throws 

*IntegrityError: (1062, "Duplicate entry '447' for key 'phone_num'")*

How to handle this error and show it to user during form input?

Also how do the same UserCreationForm validates duplicate entry for 
username etc ??

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: error- IntegrityError at /register/

2013-03-06 Thread Avnesh Shakya
thanks i got it
regards,
Avnesh shakya

On Thu, Mar 7, 2013 at 10:09 AM, Avnesh Shakya <avnesh.n...@gmail.com>wrote:

> hi i have got error- IntegrityError at /register/
>
> lrntkr_student.contact_no may not be NULL
>
> ,when i was trying to input data through html page(register.html), but
> data is not updating in database and generating that error. please help me
> i m unable to find this error.
>
> thanks
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




error- IntegrityError at /register/

2013-03-06 Thread Avnesh Shakya
hi i have got error- IntegrityError at /register/

lrntkr_student.contact_no may not be NULL

,when i was trying to input data through html page(register.html), but data
is not updating in database and generating that error. please help me i m
unable to find this error.

thanks

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


{%extends "homepage/index.html"%}
{%block title%}
 Login
{%endblock%}

{%block content%}
	
{% if not success %}

Registration
		
			
Name:
			
			

{% if name_error == "" %}
 Name will contain first name and last name character.
{% else %}
	{{ name_error }}
{% endif %}
			
		
		
			
Email id:
			
			

{% if emailid_error == "" %}
 Example : u...@mail.com
{% else %}
 {{ emailid_error }}
{% endif %}
			
		
	   		
			
User Name:
			
			

{% if username_error == "" %}
 User name contain 6-8 letter combination of alphabet and digit no special character.
{% else %}
	{{ username_error }}
{% endif %}
			
		
		
			
Password:
			
			

{% if password_error == "" %}
Password Must contain 8-15 Character.
{% else %}
 {{ password_error }}
{% endif %}
			
		
		
			
Re-password:
			
			

{% if rpassword_error == "" %}
password is not matching
{% else %}
 {{ rpassword_error }}
{% endif %}
			
		
	
	
		
Date Of Birth:
		
		
		
			Month
			1
			2
			3
			4
			5
			6
			7
			8
			9
			10
			11
			12
		

		
			Day
			1
			2
			3
			4
			5
			6
			7
			8
			9
			10
			11
			12
			13
			14
			15
			16
			17
			18	
			19
			20
			21
			22
			23
			24
			25
			26
			27
			28
			29
			30
			31
		
	
		
			Year
			2009
			2008
2007
2006
2005
2004
2003
2002
2001
2000
1999
1998
1997
1996
1995
1994
1993
1992
1991
1990
1989
1988
1987
1986
1985
1984
1983
1982
1981
1980
1979
1978
1977
1976
1975
1974
1973
1972
1971
1970
1969
1968
1967
1966
1965
1964
1963
1962
1961
1960
1959
1958
1957
1956
1955
1954
1953
1952
1951
1950
1949
1948
1947
1946
1945
1944
1943
1942
1941
1940
1939
1938
1937
1936
1935
1934
1933
1932
1931
1930
1929
1928
1927
1926
1925
1924
1923
1922
1921
1920
1919
1918
1917
1916
1915
1914
1913
1912
1911
1910
1909


	
	

		
			Gender:
		
		
		Male
Female
		
	
 
 
		
			Address:
		
		
		
		{% if address_error == "" %}
need correct address
{% else %}
 {{ address_error }}
{% endif %}
		
	
	
	
		
			Contact no.:
		
		

		{% if contact_error == "" %}
take only 11 digit
{% else %}
 {{ contact_error }}
{% endif %}
		
	
	
	
  

	
	
	
  
{% else %}
Hi Thank you for your Registraton.
{% endif %}

{%endblock%}

models.py
Description: Binary data


views.py
Description: Binary data


Re: IntegrityError after updating to custom user field: django_admin_log still has fk to auth_user

2013-03-02 Thread Peter of the Norse
This sound like a South kind of problem. Your tables were created with a 
foreign key from django_admin_log to auth_user, but you’re not longer using 
auth_user. You’ll have to drop the foreign key and recreate it to remove this 
error.

On Feb 27, 2013, at 4:17 PM, Ben Roberts wrote:

> This ring any bells? I updated my existing site to utilize my new Django 1.5 
> custom user field, and now I can't update anything in Admin because i get the 
> following error: (django_admin_log still has a fk to auth_user, apparently!) 
> Any way to resolve this?
> 
> 
> 
> Traceback (most recent call last):
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py",
>  line 115, in get_response
> response = callback(request, *callback_args, **callback_kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/newrelic-1.10.0.28/newrelic/api/object_wrapper.py",
>  line 220, in __call__
> self._nr_instance, args, kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/newrelic-1.10.0.28/newrelic/hooks/framework_django.py",
>  line 475, in wrapper
> return wrapped(*args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/options.py",
>  line 372, in wrapper
> return self.admin_site.admin_view(view)(*args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
> line 91, in _wrapped_view
> response = view_func(request, *args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py",
>  line 89, in _wrapped_view_func
> response = view_func(request, *args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/sites.py",
>  line 202, in inner
> return view(request, *args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
> line 25, in _wrapper
> return bound_func(*args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
> line 91, in _wrapped_view
> response = view_func(request, *args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
> line 21, in bound_func
> return func(self, *args2, **kwargs2)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
> line 223, in inner
> return func(*args, **kwargs)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
> line 217, in __exit__
> self.exiting(exc_value, self.using)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
> line 281, in exiting
> commit(using=using)
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
> line 152, in commit
> connection.commit()
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/__init__.py",
>  line 241, in commit
> self._commit()
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py",
>  line 242, in _commit
> six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), 
> sys.exc_info()[2])
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py",
>  line 240, in _commit
> return self.connection.commit()
> 
>   File 
> "/app/.heroku/python/lib/python2.7/site-packages/newrelic-1.10.0.28/newrelic/hooks/database_dbapi2.py",
>  line 68, in commit
> return self._nr_connection.commit()
> 
> IntegrityError: insert or update on table "django_admin_log" violates foreign 
> key constraint "django_admin_log_user_id_fkey"
> DETAIL:  Key (user_id)=(2) is not present in table "auth_user".
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>  
>  

Peter of the Norse
rahmc...@radio1190.org



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




IntegrityError after updating to custom user field: django_admin_log still has fk to auth_user

2013-02-28 Thread Ben Roberts
This ring any bells? I updated my existing site to utilize my new Django 
1.5 custom user field, and now I can't update anything in Admin because i 
get the following error: (django_admin_log still has a fk to auth_user, 
apparently!) Any way to resolve this?



Traceback (most recent call last):

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", 
line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)

  File "/app/.heroku/python/lib/python2.7/site-packages/
newrelic-1.10.0.28/newrelic/api/object_wrapper.py", line 220, in __call__
self._nr_instance, args, kwargs)

  File "/app/.heroku/python/lib/python2.7/site-packages/
newrelic-1.10.0.28/newrelic/hooks/framework_django.py", line 475, in wrapper
return wrapped(*args, **kwargs)

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/contrib/admin/options.py", line 372, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
line 91, in _wrapped_view
response = view_func(request, *args, **kwargs)

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/views/decorators/cache.py", line 89, in _wrapped_view_func
response = view_func(request, *args, **kwargs)

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/contrib/admin/sites.py", line 202, in inner
return view(request, *args, **kwargs)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
line 25, in _wrapper
return bound_func(*args, **kwargs)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
line 91, in _wrapped_view
response = view_func(request, *args, **kwargs)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py", 
line 21, in bound_func
return func(self, *args2, **kwargs2)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
line 223, in inner
return func(*args, **kwargs)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
line 217, in __exit__
self.exiting(exc_value, self.using)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
line 281, in exiting
commit(using=using)

  File 
"/app/.heroku/python/lib/python2.7/site-packages/django/db/transaction.py", 
line 152, in commit
connection.commit()

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/db/backends/__init__.py", line 241, in commit
self._commit()

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/db/backends/postgresql_psycopg2/base.py", line 242, in _commit
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), 
sys.exc_info()[2])

  File "/app/.heroku/python/lib/python2.7/site-packages/
django/db/backends/postgresql_psycopg2/base.py", line 240, in _commit
return self.connection.commit()

  File "/app/.heroku/python/lib/python2.7/site-packages/
newrelic-1.10.0.28/newrelic/hooks/database_dbapi2.py", line 68, in commit
return self._nr_connection.commit()

IntegrityError: insert or update on table "django_admin_log" violates 
foreign key constraint "django_admin_log_user_id_fkey"
DETAIL:  Key (user_id)=(2) is not present in table "auth_user".

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-16 Thread Some Developer

On 11/02/13 14:54, Bill Freeman wrote:



On Sun, Feb 10, 2013 at 10:50 AM, Some Developer
<someukdevelo...@gmail.com <mailto:someukdevelo...@gmail.com>> wrote:

On 10/02/13 15:07, Bill Freeman wrote:

Did you previously have a field named 'title' in this model that was
marked unique, that you have since removed?  If so, the column
may still
be in the database with a unique constraint.  Since it's no
longer in
the model, some default may be being used when you save, and that's
obviously not unique.  Use suitable tools for your database (if
PostgreSQL, I suggest PGAdminIII) to examine the schema.  You may be
able to drop the column, or at least the constraint (back up the
database first).

If there never was such a field, then the problem originates in
another
model.  You still may be able to figure it out by inspecting the
database schema.  You can also temporarily set up to catch the
Integrity
Error close to the origin, and call pdb.set_trace(), where you can
examine the query to see what models are involved.

Bill


OK, I've just found something rather strange. If I just do a simple:

tag = BlogTag(title=form.cleaned___data['title'],

 description=form.cleaned_data[__'description'],
 num_articles=0)

tag.save()

    I get an IntegrityError and the model fails to save. On the other
hand if I do the following:

try:
 tag = BlogTag(title=form.cleaned___data['title'],

 description=form.cleaned_data[__'description'],
 num_articles=0)

 tag.save()

except Exception:
 pass

the model saves correctly (I've checked manually in the SQLite
database) and there is no error shown at all (as expected since I
have ignored the exception).

Any idea why this is the case? If it truly were a database
constraint violation I would have assumed that it would fail to save
no matter what you did regarding Python exceptions.

This feels like a bug in Django to me.

Suggestions welcome.


I have to agree that catching exceptions doesn't clear IntegrityError.
But that still doesn't tell us where the bug is.

Does this happen on the development server?  If so, then my suggestion
is to sprinkle in a pdb.set_trace() or two, poke around and/or single
step over a few things, then go around again and single step into the
thing that fails, and repeat until enlightened.

If it only happens on a production server, you're stuck with printing
stuff.  For instance, since your except only has a pass, we don't
actually know whether it was reached.  You can't in general, print to
stdout.  I believe that apache/mod_wsgi puts stuff sent to stderr in the
apacvhe longs.  Django's logging may  help.  I'm fond of writing a
little function that appends its text argument to a file of your choice.

Bill


Apologies for the late response I've had a somewhat busy week with work.

Problem solved. It was a bug in Django Debug Toolbar. Disabling the 
following panel fixed the issue completely.


'debug_toolbar.panels.profiling.ProfilingDebugPanel',

I'm glad that particular problem is sorted :).

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-11 Thread Bill Freeman
On Sun, Feb 10, 2013 at 10:50 AM, Some Developer
<someukdevelo...@gmail.com>wrote:

> On 10/02/13 15:07, Bill Freeman wrote:
>
>> Did you previously have a field named 'title' in this model that was
>> marked unique, that you have since removed?  If so, the column may still
>> be in the database with a unique constraint.  Since it's no longer in
>> the model, some default may be being used when you save, and that's
>> obviously not unique.  Use suitable tools for your database (if
>> PostgreSQL, I suggest PGAdminIII) to examine the schema.  You may be
>> able to drop the column, or at least the constraint (back up the
>> database first).
>>
>> If there never was such a field, then the problem originates in another
>> model.  You still may be able to figure it out by inspecting the
>> database schema.  You can also temporarily set up to catch the Integrity
>> Error close to the origin, and call pdb.set_trace(), where you can
>> examine the query to see what models are involved.
>>
>> Bill
>>
>
> OK, I've just found something rather strange. If I just do a simple:
>
> tag = BlogTag(title=form.cleaned_**data['title'],
>
> description=form.cleaned_data[**'description'],
> num_articles=0)
>
> tag.save()
>
> I get an IntegrityError and the model fails to save. On the other hand if
> I do the following:
>
> try:
> tag = BlogTag(title=form.cleaned_**data['title'],
>
> description=form.cleaned_data[**'description'],
> num_articles=0)
>
> tag.save()
>
> except Exception:
> pass
>
> the model saves correctly (I've checked manually in the SQLite database)
> and there is no error shown at all (as expected since I have ignored the
> exception).
>
> Any idea why this is the case? If it truly were a database constraint
> violation I would have assumed that it would fail to save no matter what
> you did regarding Python exceptions.
>
> This feels like a bug in Django to me.
>
> Suggestions welcome.
>
>
I have to agree that catching exceptions doesn't clear IntegrityError.  But
that still doesn't tell us where the bug is.

Does this happen on the development server?  If so, then my suggestion is
to sprinkle in a pdb.set_trace() or two, poke around and/or single step
over a few things, then go around again and single step into the thing that
fails, and repeat until enlightened.

If it only happens on a production server, you're stuck with printing
stuff.  For instance, since your except only has a pass, we don't actually
know whether it was reached.  You can't in general, print to stdout.  I
believe that apache/mod_wsgi puts stuff sent to stderr in the apacvhe
longs.  Django's logging may  help.  I'm fond of writing a little function
that appends its text argument to a file of your choice.

Bill

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-10 Thread Some Developer

On 10/02/13 15:07, Bill Freeman wrote:

Did you previously have a field named 'title' in this model that was
marked unique, that you have since removed?  If so, the column may still
be in the database with a unique constraint.  Since it's no longer in
the model, some default may be being used when you save, and that's
obviously not unique.  Use suitable tools for your database (if
PostgreSQL, I suggest PGAdminIII) to examine the schema.  You may be
able to drop the column, or at least the constraint (back up the
database first).

If there never was such a field, then the problem originates in another
model.  You still may be able to figure it out by inspecting the
database schema.  You can also temporarily set up to catch the Integrity
Error close to the origin, and call pdb.set_trace(), where you can
examine the query to see what models are involved.

Bill


OK, I've just found something rather strange. If I just do a simple:

tag = BlogTag(title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

I get an IntegrityError and the model fails to save. On the other hand 
if I do the following:


try:
tag = BlogTag(title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

except Exception:
pass

the model saves correctly (I've checked manually in the SQLite database) 
and there is no error shown at all (as expected since I have ignored the 
exception).


Any idea why this is the case? If it truly were a database constraint 
violation I would have assumed that it would fail to save no matter what 
you did regarding Python exceptions.


This feels like a bug in Django to me.

Suggestions welcome.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-10 Thread Bill Freeman
Did you previously have a field named 'title' in this model that was marked
unique, that you have since removed?  If so, the column may still be in the
database with a unique constraint.  Since it's no longer in the model, some
default may be being used when you save, and that's obviously not unique.
Use suitable tools for your database (if PostgreSQL, I suggest PGAdminIII)
to examine the schema.  You may be able to drop the column, or at least the
constraint (back up the database first).

If there never was such a field, then the problem originates in another
model.  You still may be able to figure it out by inspecting the database
schema.  You can also temporarily set up to catch the Integrity Error close
to the origin, and call pdb.set_trace(), where you can examine the query to
see what models are involved.

Bill

On Sat, Feb 9, 2013 at 3:44 AM, Some Developer <someukdevelo...@gmail.com>wrote:

> On 08/02/13 14:08, Andre Terra wrote:
>
>> Please post traceback, settings.py, etc.
>>
>> On Fri, Feb 8, 2013 at 5:18 AM, Some Developer
>> <someukdevelo...@gmail.com 
>> <mailto:someukdeveloper@gmail.**com<someukdevelo...@gmail.com>>>
>> wrote:
>>
>> I have a model for a Tag object with simply has two fields. A title
>> (which has the unique constraint) and a description. I also have a
>> FormView based view class which handles the creation of Tag objects.
>>
>> When I try and save the object in the form_valid() method I always
>> get an IntegrityError stating that the title column is not unique.
>> This is somewhat puzzling as I have deleted the SQLite database file
>> and recreated it using syncdb / migrate so it is completely empty.
>>
>> I'm completely baffled by this error.
>>
>
> Opps. I forgot to post the code.
>
> class TagCreate(FormView):
> template_name = 'blog/tag_create.html'
> success_url = reverse_lazy('blog_tag_create_**confirmed')
> model = BlogTag
> form_class = CreateTagForm
>
> def form_valid(self, form):
> tag = BlogTag(
> title=form.cleaned_data['**title'],
> description=form.cleaned_data[**'description'],
> num_articles=0)
>
> tag.save()
>
> return super(TagCreate, self).form_valid(form)
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to 
> django-users+unsubscribe@**googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> .
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at 
> http://groups.google.com/**group/django-users?hl=en<http://groups.google.com/group/django-users?hl=en>
> .
> For more options, visit 
> https://groups.google.com/**groups/opt_out<https://groups.google.com/groups/opt_out>
> .
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-09 Thread Some Developer

On 08/02/13 14:08, Andre Terra wrote:

Please post traceback, settings.py, etc.

On Fri, Feb 8, 2013 at 5:18 AM, Some Developer
<someukdevelo...@gmail.com <mailto:someukdevelo...@gmail.com>> wrote:

I have a model for a Tag object with simply has two fields. A title
(which has the unique constraint) and a description. I also have a
FormView based view class which handles the creation of Tag objects.

When I try and save the object in the form_valid() method I always
get an IntegrityError stating that the title column is not unique.
This is somewhat puzzling as I have deleted the SQLite database file
and recreated it using syncdb / migrate so it is completely empty.

I'm completely baffled by this error.


Opps. I forgot to post the code.

class TagCreate(FormView):
template_name = 'blog/tag_create.html'
success_url = reverse_lazy('blog_tag_create_confirmed')
model = BlogTag
form_class = CreateTagForm

def form_valid(self, form):
tag = BlogTag(
title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

return super(TagCreate, self).form_valid(form)

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError when creating a brand new model instance

2013-02-08 Thread Some Developer

On 08/02/13 14:08, Andre Terra wrote:

Please post traceback, settings.py, etc.

On Fri, Feb 8, 2013 at 5:18 AM, Some Developer
<someukdevelo...@gmail.com <mailto:someukdevelo...@gmail.com>> wrote:

I have a model for a Tag object with simply has two fields. A title
(which has the unique constraint) and a description. I also have a
FormView based view class which handles the creation of Tag objects.

When I try and save the object in the form_valid() method I always
get an IntegrityError stating that the title column is not unique.
This is somewhat puzzling as I have deleted the SQLite database file
and recreated it using syncdb / migrate so it is completely empty.

I'm completely baffled by this error.


I've been using Django for years and have never had this problem before. 
Hopefully someone will be able to shed some light on it as it is rather 
annoying.


The only thing I am doing now that I haven't done in the past is using 
class based views.


Settings:

The settings are just the default pretty much. The database section is 
below though.


DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DIRNAME, 'data/data.db'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}

Traceback:

Environment:


Request Method: POST
Request URL: http://localhost:8000/blog/tag/create/

Django Version: 1.4.3
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'debug_toolbar_htmltidy',
 'inspector_panel',
 'debug_toolbar_user_panel',
 'compressor',
 'registration',
 'djcelery',
 'south',
 'blog',
 'controlpanel',
 'docs',
 'legal',
 'support',
 'bugs',
 'general')
Installed Middleware:
('django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.transaction.TransactionMiddleware')


Traceback:
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/core/handlers/base.py" 
in get_response
  111. response = callback(request, 
*callback_args, **callback_kwargs)
File 
"/home/somedeveloper/Documents/Development/Python/djangostormcloud/djangostormcloud/decorators/superuser.py" 
in decorator

  17. return f(request, *args, **kwargs)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/base.py" 
in view

  48. return self.dispatch(request, *args, **kwargs)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/base.py" 
in dispatch

  69. return handler(request, *args, **kwargs)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/edit.py" 
in post

  138. return self.form_valid(form)
File 
"/home/somedeveloper/Documents/Development/Python/djangostormcloud/blog/views.py" 
in form_valid

  134. tag.save()
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/base.py" 
in save
  463. self.save_base(using=using, force_insert=force_insert, 
force_update=force_update)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/base.py" 
in save_base
  551. result = manager._insert([self], fields=fields, 
return_id=update_pk, using=using, raw=raw)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/manager.py" 
in _insert

  203. return insert_query(self.model, objs, fields, **kwargs)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/query.py" 
in insert_query

  1593. return query.get_compiler(using=using).execute_sql(return_id)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py" 
in execute_sql

  912. cursor.execute(sql, params)
File 
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/d

Re: IntegrityError when creating a brand new model instance

2013-02-08 Thread Andre Terra
Please post traceback, settings.py, etc.

On Fri, Feb 8, 2013 at 5:18 AM, Some Developer <someukdevelo...@gmail.com>wrote:

> I have a model for a Tag object with simply has two fields. A title (which
> has the unique constraint) and a description. I also have a FormView based
> view class which handles the creation of Tag objects.
>
> When I try and save the object in the form_valid() method I always get an
> IntegrityError stating that the title column is not unique. This is
> somewhat puzzling as I have deleted the SQLite database file and recreated
> it using syncdb / migrate so it is completely empty.
>
> I'm completely baffled by this error.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to 
> django-users+unsubscribe@**googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> .
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at 
> http://groups.google.com/**group/django-users?hl=en<http://groups.google.com/group/django-users?hl=en>
> .
> For more options, visit 
> https://groups.google.com/**groups/opt_out<https://groups.google.com/groups/opt_out>
> .
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




IntegrityError when creating a brand new model instance

2013-02-07 Thread Some Developer
I have a model for a Tag object with simply has two fields. A title 
(which has the unique constraint) and a description. I also have a 
FormView based view class which handles the creation of Tag objects.


When I try and save the object in the form_valid() method I always get 
an IntegrityError stating that the title column is not unique. This is 
somewhat puzzling as I have deleted the SQLite database file and 
recreated it using syncdb / migrate so it is completely empty.


I'm completely baffled by this error.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: IntegrityError

2012-12-18 Thread Satinderpal Singh
On Tue, Dec 18, 2012 at 12:25 PM, Sandeep kaur <mkaurkha...@gmail.com> wrote:
> On Tue, Dec 18, 2012 at 2:48 AM, Satinderpal Singh
> <satinder.goray...@gmail.com> wrote:
>> I created a search box for searching the information about the client
>> so that this information uses to create the report.
>
> add these lines :
>
>> def search(request):
> 
>>   {% endfor %}
>>
>> i want to get job id to be saved through header view:
>> def header(request):
>job =Job.objects.get(id=request.GET['q'])
>> if request.method=='POST':
>> form = headForm(request.POST)
>> if form.is_valid():
>> cd = form.cleaned_data
>profile = form.save(commit=False)
>profile.job = job
>profile.save()
>form.save()
>> HttpResponseRedirect(reverse('Automation.report.views.result'))
>>
>> But get the following error:
>> IntegrityError at /report/header/
>> (1048, "Column 'job_id' cannot be null")
>>
>> Please anybody tell me where i am wrong?
>>
> Hope this helps you.
Yeah it works! Thanks.

--
Satinderpal Singh
http://satindergoraya.blogspot.in/
http://satindergoraya91.blogspot.in/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError

2012-12-18 Thread Satinderpal Singh
On Tue, Dec 18, 2012 at 11:21 AM, Chris Cogdon <ch...@cogdon.org> wrote:
> Can you post the code for the model, and the complete exception trace?

class head(models.Model):
job = models.ForeignKey(Job, null=True)
Header_column_1 = models.CharField(max_length=255,blank=True)
Header_column_2 = models.CharField(max_length=255,blank=True)
Footer_column_3 = models.CharField(max_length=255,blank=True)

def __str__(self):
return self.refrence_no

>
> On Monday, December 17, 2012 1:18:54 PM UTC-8, Satinderpal Singh wrote:
>>
>> I created a search box for searching the information about the client
>> so that this information uses to create the report.
>> def search(request):
>> query = request.GET.get('q', '')
>> if query:
>> results = Job.objects.filter(id =
>>
>> query).values('client__client__name','client__client__address_1','clientjob__material__name','suspencejob__field__name','id','job_no','date','site','report_type',)
>> else:
>> results = []
>> return render_to_response("report/search.html", {"results":
>> results,"query": query})
>>
>> I want to save the value of job in the report table to create a report
>> like:
>>   {% for job in results %}
>> Job Id : {{ job.id }}
>> Name:{{job.client__client__name}}
>> Job No. : {{job.job_no}}
>> Site : {{job.site}}
>> Reference Letter No : {{job.Reference_Letter_no}}
>> Letter Date : {{job.Letter_date}}
>> Address : {{job.client__client__address_1}}
>> Material : {{job.clientjob__material__name}}
>> Report
>>   {% endfor %}
>>
>> i want to get job id to be saved through header view:
>> def header(request):
>> if request.method=='POST':
>> form = headForm(request.POST)
>>     if form.is_valid():
>> cd = form.cleaned_data
>> form.save()
>> return
>> HttpResponseRedirect(reverse('Automation.report.views.result'))
>>
>> But get the following error:
>> IntegrityError at /report/header/
>> (1048, "Column 'job_id' cannot be null")
>>
>> Please anybody tell me where i am wrong?
>>
>>
>>
>>
>> --
>> Satinderpal Singh
>> http://satindergoraya.blogspot.in/
>> http://satindergoraya91.blogspot.in/
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/8St7erk3yrAJ.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.



--
Satinderpal Singh
http://satindergoraya.blogspot.in/
http://satindergoraya91.blogspot.in/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError

2012-12-17 Thread Chris Cogdon
I'd need to see the source for Job and that other model, plus a proper 
exception traceback, so I can tell at what point the IntegrityError is 
being thrown.

also, you should not be using form.save() there... if you do a commit=False 
to get a copy of the model, you only need to save that model... re-saving 
the form again is probably an error.

On Monday, December 17, 2012 10:55:00 PM UTC-8, sandy wrote:
>
> On Tue, Dec 18, 2012 at 2:48 AM, Satinderpal Singh 
> <satinder...@gmail.com > wrote: 
> > I created a search box for searching the information about the client 
> > so that this information uses to create the report. 
>
> add these lines : 
>
> > def search(request): 
>  
> >   {% endfor %} 
> > 
> > i want to get job id to be saved through header view: 
> > def header(request): 
>job =Job.objects.get(id=request.GET['q']) 
> > if request.method=='POST': 
> > form = headForm(request.POST) 
> > if form.is_valid(): 
> > cd = form.cleaned_data 
>profile = form.save(commit=False) 
>profile.job = job 
>profile.save() 
>form.save() 
> > HttpResponseRedirect(reverse('Automation.report.views.result')) 
> > 
> > But get the following error: 
> > IntegrityError at /report/header/ 
> > (1048, "Column 'job_id' cannot be null") 
> > 
> > Please anybody tell me where i am wrong? 
> > 
> Hope this helps you. 
>
> -- 
> Sandeep Kaur 
> E-Mail: mkaur...@gmail.com  
> Blog: sandymadaan.wordpress.com 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/OhGhVvo7EP4J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError

2012-12-17 Thread Sandeep kaur
On Tue, Dec 18, 2012 at 2:48 AM, Satinderpal Singh
<satinder.goray...@gmail.com> wrote:
> I created a search box for searching the information about the client
> so that this information uses to create the report.

add these lines :

> def search(request):

>   {% endfor %}
>
> i want to get job id to be saved through header view:
> def header(request):
   job =Job.objects.get(id=request.GET['q'])
> if request.method=='POST':
> form = headForm(request.POST)
> if form.is_valid():
> cd = form.cleaned_data
   profile = form.save(commit=False)
   profile.job = job
   profile.save()
   form.save()
> HttpResponseRedirect(reverse('Automation.report.views.result'))
>
> But get the following error:
> IntegrityError at /report/header/
> (1048, "Column 'job_id' cannot be null")
>
> Please anybody tell me where i am wrong?
>
Hope this helps you.

-- 
Sandeep Kaur
E-Mail: mkaurkha...@gmail.com
Blog: sandymadaan.wordpress.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError

2012-12-17 Thread Chris Cogdon
Can you post the code for the model, and the complete exception trace? I 
ask you use something that will properly maintain the intending, such as 
pastebin or dpaste.

On Monday, December 17, 2012 1:18:54 PM UTC-8, Satinderpal Singh wrote:
>
> I created a search box for searching the information about the client 
> so that this information uses to create the report. 
> def search(request): 
> query = request.GET.get('q', '') 
> if query: 
> results = Job.objects.filter(id = 
> query).values('client__client__name','client__client__address_1','clientjob__material__name','suspencejob__field__name','id','job_no','date','site','report_type',)
>  
>
> else: 
> results = [] 
> return render_to_response("report/search.html", {"results": 
> results,"query": query}) 
>
> I want to save the value of job in the report table to create a report 
> like: 
>   {% for job in results %} 
> Job Id : {{ job.id }} 
> Name:{{job.client__client__name}} 
> Job No. : {{job.job_no}} 
> Site : {{job.site}} 
> Reference Letter No : {{job.Reference_Letter_no}} 
> Letter Date : {{job.Letter_date}} 
> Address : {{job.client__client__address_1}} 
> Material : {{job.clientjob__material__name}} 
> Report 
>   {% endfor %} 
>
> i want to get job id to be saved through header view: 
> def header(request): 
> if request.method=='POST': 
> form = headForm(request.POST) 
> if form.is_valid(): 
> cd = form.cleaned_data 
> form.save() 
> return 
> HttpResponseRedirect(reverse('Automation.report.views.result')) 
>
> But get the following error: 
> IntegrityError at /report/header/ 
> (1048, "Column 'job_id' cannot be null") 
>
> Please anybody tell me where i am wrong? 
>
>
>
>
> -- 
> Satinderpal Singh 
> http://satindergoraya.blogspot.in/ 
> http://satindergoraya91.blogspot.in/ 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/8St7erk3yrAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: testing unique_together IntegrityError

2012-11-10 Thread Mike Dewhirst

On 11/11/2012 4:45pm, Mike Dewhirst wrote:

Can anyone help with some unit test guidance please?

How can I trap an IntegrityError in a test to prove unique_together is
working?

I'm modelling a company and multiple divisions. A solo division doesn't
need a division.name so I'm allowing it to be blank. It's __unicode__()
method returns self.name or self.company.name

All fine so far. But I insist two divisions cannot have the same name.

In Division's Meta class we have unique_together = (company, name) and
this works as advertised

In a unit test I don't seem to be able to swallow the IntegrityError!!


E..
=
...
IntegrityError: duplicate key value violates unique constraint
"company_division_company_id_name_key"
DETAIL:  Key (company_id, name)=(7, ) already exists.

Here is the unit test ...

 def test_twodivswithnoname(self):
 tstc = Company.objects.get(name='Company Inc')
 tstdiv, c = Division.objects.get_or_create(company=tstc)
 tstdiv.name = ''
 tstdiv.save()
 expected = ''
 result = tstdiv.name
 # prove nothing up my sleeve
 self.assertEqual(result, expected)
 # if name is None, __unicode__() returns the owning company name
 expected = 'Company Inc'
 result = '%s' % tstdiv
 self.assertEqual(result, expected)


This didn't swallow it either ...

try:
tstdivb = Division.objects.create(company=tstc, name='')
    except IntegrityError as e:
pass



 tstdivb = Division.objects.create(company=tstc)
 tstdivb.name = ''
 try:
 # company and name are unique together
 tstdivb.save()
     except IntegrityError as e:
 pass
 tstdivb.delete()

I've also tried self.assertRaises(IntegrityError) instead of the
try/except block. Same result.

Thanks

Mike



--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



testing unique_together IntegrityError

2012-11-10 Thread Mike Dewhirst

Can anyone help with some unit test guidance please?

How can I trap an IntegrityError in a test to prove unique_together is 
working?


I'm modelling a company and multiple divisions. A solo division doesn't 
need a division.name so I'm allowing it to be blank. It's __unicode__() 
method returns self.name or self.company.name


All fine so far. But I insist two divisions cannot have the same name.

In Division's Meta class we have unique_together = (company, name) and 
this works as advertised


In a unit test I don't seem to be able to swallow the IntegrityError!!


E..
=
...
IntegrityError: duplicate key value violates unique constraint 
"company_division_company_id_name_key"

DETAIL:  Key (company_id, name)=(7, ) already exists.

Here is the unit test ...

def test_twodivswithnoname(self):
tstc = Company.objects.get(name='Company Inc')
tstdiv, c = Division.objects.get_or_create(company=tstc)
tstdiv.name = ''
tstdiv.save()
expected = ''
result = tstdiv.name
# prove nothing up my sleeve
self.assertEqual(result, expected)
# if name is None, __unicode__() returns the owning company name
expected = 'Company Inc'
result = '%s' % tstdiv
self.assertEqual(result, expected)
tstdivb = Division.objects.create(company=tstc)
tstdivb.name = ''
try:
# company and name are unique together
tstdivb.save()
    except IntegrityError as e:
pass
tstdivb.delete()

I've also tried self.assertRaises(IntegrityError) instead of the 
try/except block. Same result.


Thanks

Mike

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Occasional IntegrityError on m2m fields using PostgreSQL

2012-11-01 Thread Bernardo
Hello guys,

I can't detect any pattern, maybe 1 in each 1000 thousands edit of a 
certain model returns an IntegrityError on a m2m field. Most of the times 
this field wasn't even modified. When a model is saved I believe django 
always wipes the m2m field and then readds the items, right? I saw django 
calls clear() and then add()s the items. My code then fails with:

IntegrityError: duplicate key value violates unique constraint 
"app_model_m2m_field_key"

It seems like the add of items is performed before the items are cleared, 
which is very weird. I've tried to reproduce it but it's very hard, only 
happens occasionally. Any idea what could cause it? Could maybe setting 
auto commit solve this problem? Thanks in advance

Cheers,
Bernardo

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/OtS2XH-XyioJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



IntegrityError registration_registrationprofile when deleting user from admin

2012-10-23 Thread pietro conconi
Hi
i've included django-registration in my project's apps.
I've included in my project's settings
AUTH_PROFILE_MODULE = "people.Profile"

Trying to delete an User from admin interface,
I'm still getting this frustrating error message

*IntegrityError at /admin/auth/user/X/delete/*

*update or delete on table "auth_user" violates foreign key constraint 
"registration_registrationprofile_user_id_fkey" on table 
"registration_registrationprofile"*

*DETAIL:  Key (id)=(X) is still referenced from table 
"registration_registrationprofile".*

The url /admin/auth/user/X/delete/ 
<http://speed-10.linkeropoli.dom:8012/admin/auth/user/57/delete/> only shows

auth.User instance and profile.Profile instance to be deleted, 

but the instance of this table (registration_registrationprofile) is not 
included and processed.


Any ideas?

Thank's

Peter




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/SdbX0J3O9NEJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Zheng Li
Isn't it because MyISAM does not support transaction?

BTW
I am using django 1.3.1, mysql 5.5, innodb
mysql> SELECT @@GLOBAL.tx_isolation, @@tx_isolation;
+---+-+
| @@GLOBAL.tx_isolation | @@tx_isolation  |
+---+-+
| REPEATABLE-READ   | REPEATABLE-READ |
+---+-+

another question,
does "read committed" affects performance?

On 2012/10/16, at 0:35, Tom Evans wrote:

> On Mon, Oct 15, 2012 at 3:28 PM, Karen Tracey <kmtra...@gmail.com> wrote:
>> On Mon, Oct 15, 2012 at 9:43 AM, Tom Evans <tevans...@googlemail.com> wrote:
>>> 
>>> On Mon, Oct 15, 2012 at 1:50 PM, Zheng Li <dllizh...@gmail.com> wrote:
>>>> get_or_create shouldn't give duplicate entry error
>>>> anyone help.
>>>> 
>>> 
>>> This is incorrect, and a common misconception: get_or_create() is not
>>> atomic. If this happens, you will get duplicate key errors:
>> 
>> 
>> No, get_or_create IS intended to be atomic.
>> 
> 
> I can be intended to be whatever it wants, but since there is no
> atomic database operation to get or create a tuple, there is no
> guarantee of atomicity.
> 
>>> 
>>> 
>>> Thread A calls get_or_create(a='a', b='b')
>>> Thread B calls get_or_create(a='a', b='b')
>>> Thread A get_or_create looks for entry in DB, not found
>>> Thread B get_or_create looks for entry in DB, not found
>>> Thread B creates entry in DB
>>> Thread A get_or_create tries to create entry in DB
>> 
>> 
>> Internally, get_or_create code in thread A will now attempt to GET the
>> object created by thread B. It will not automatically reflect the error to
>> the caller. See:
>> 
>> https://github.com/django/django/blob/stable/1.4.x/django/db/models/query.py#L430
> 
> I regularly - once every few months - see get_or_create raise
> IntegrityError due to duplicate key on MySQL 5.0/MyISAM/Django 1.3. So
> whilst that is the intention of the code, it isn't what happens. I'm
> happy to blame MySQL.
> 
> Cheers
> 
> Tom
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Tom Evans
On Mon, Oct 15, 2012 at 3:28 PM, Karen Tracey <kmtra...@gmail.com> wrote:
> On Mon, Oct 15, 2012 at 9:43 AM, Tom Evans <tevans...@googlemail.com> wrote:
>>
>> On Mon, Oct 15, 2012 at 1:50 PM, Zheng Li <dllizh...@gmail.com> wrote:
>> > get_or_create shouldn't give duplicate entry error
>> > anyone help.
>> >
>>
>> This is incorrect, and a common misconception: get_or_create() is not
>> atomic. If this happens, you will get duplicate key errors:
>
>
> No, get_or_create IS intended to be atomic.
>

I can be intended to be whatever it wants, but since there is no
atomic database operation to get or create a tuple, there is no
guarantee of atomicity.

>>
>>
>> Thread A calls get_or_create(a='a', b='b')
>> Thread B calls get_or_create(a='a', b='b')
>> Thread A get_or_create looks for entry in DB, not found
>> Thread B get_or_create looks for entry in DB, not found
>> Thread B creates entry in DB
>> Thread A get_or_create tries to create entry in DB
>
>
> Internally, get_or_create code in thread A will now attempt to GET the
> object created by thread B. It will not automatically reflect the error to
> the caller. See:
>
> https://github.com/django/django/blob/stable/1.4.x/django/db/models/query.py#L430

I regularly - once every few months - see get_or_create raise
IntegrityError due to duplicate key on MySQL 5.0/MyISAM/Django 1.3. So
whilst that is the intention of the code, it isn't what happens. I'm
happy to blame MySQL.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Karen Tracey
On Mon, Oct 15, 2012 at 9:43 AM, Tom Evans  wrote:

> On Mon, Oct 15, 2012 at 1:50 PM, Zheng Li  wrote:
> > get_or_create shouldn't give duplicate entry error
> > anyone help.
> >
>
> This is incorrect, and a common misconception: get_or_create() is not
> atomic. If this happens, you will get duplicate key errors:
>

No, get_or_create IS intended to be atomic.


>
> Thread A calls get_or_create(a='a', b='b')
> Thread B calls get_or_create(a='a', b='b')
> Thread A get_or_create looks for entry in DB, not found
> Thread B get_or_create looks for entry in DB, not found
> Thread B creates entry in DB
> Thread A get_or_create tries to create entry in DB
>

Internally, get_or_create code in thread A will now attempt to GET the
object created by thread B. It will not automatically reflect the error to
the caller. See:

https://github.com/django/django/blob/stable/1.4.x/django/db/models/query.py#L430


>
> Where I say 'thread', you could also read 'process'. If you are
> capable of serving multiple requests simultaneously, this can happen,
> even if you aren't using threads.
>
> If this is a problem for you, use a transaction aware DB instead of
> MySQL. It won't solve the issue, but at least you will be able to
> unroll the transaction.
>

The issue with MySQL here is when you ARE using its transactional DB
engine, InnoDB, AND using its (default) "repeatable read" transaction
isolation level. In that case, the DB will refuse to return the object
created by thread B to thread A if thread A has already "read" the
non-existence of such a row. See:

https://code.djangoproject.com/ticket/13906

This particular issue can be fixed by changing the transaction isolation
level to "read committed". Although I have heard various people say this
can cause "other problems" with MySQL apps, I've never seen a concrete
example of one, so switching to "read committed" would be my preferred way
to use get_or_created if I had to use MySQL/InnoDB.

Karen
-- 
http://tracey.org/kmt/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Tom Evans
On Mon, Oct 15, 2012 at 1:50 PM, Zheng Li  wrote:
> get_or_create shouldn't give duplicate entry error
> anyone help.
>

This is incorrect, and a common misconception: get_or_create() is not
atomic. If this happens, you will get duplicate key errors:

Thread A calls get_or_create(a='a', b='b')
Thread B calls get_or_create(a='a', b='b')
Thread A get_or_create looks for entry in DB, not found
Thread B get_or_create looks for entry in DB, not found
Thread B creates entry in DB
Thread A get_or_create tries to create entry in DB

Where I say 'thread', you could also read 'process'. If you are
capable of serving multiple requests simultaneously, this can happen,
even if you aren't using threads.

If this is a problem for you, use a transaction aware DB instead of
MySQL. It won't solve the issue, but at least you will be able to
unroll the transaction.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Reinout van Rees

On 15-10-12 14:50, Zheng Li wrote:

get_or_create shouldn't give duplicate entry error


Perhaps you have existing data that violates your unique-together 
constraint? Data that existed before that constraint was in place?


Check it directly in your database by searching for that a=a, b=b entry.


Reinout

--
Reinout van Reeshttp://reinout.vanrees.org/
rein...@vanrees.org http://www.nelen-schuurmans.nl/
"If you're not sure what to do, make something. -- Paul Graham"

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-15 Thread Zheng Li
get_or_create shouldn't give duplicate entry error
anyone help.

On 2012/10/13, at 11:06, Wei Wei wrote:

> I am new to Django. But does the error message literally mean you have 
> duplicated records against your unique_together constriction?
> 
> On Sat, Oct 13, 2012 at 9:47 AM, Zheng Li <dllizh...@gmail.com> wrote:
> class AB(models.Model):
> a = models.ForeignKey(A)
> b = models.ForeignKey(B)
> c = models.IntegerField(default=0)
> d = models.FloatField(default=0)
> e = models.IntegerField(default=0)
> f = models.FloatField(default=0)
> class Meta:
> unique_together = (('a', 'b'),)
> 
> I have a class like above.
> when I call get_or_create, sometimes IntegrityError: (1062, "Duplicate entry) 
> error happens.
> a, _ = AB.objects.get_or_create(a=a, b=b)
> 
> I really have googled and worked on it for a while, but still nothing.
> anyone can help?
> Thanks in advance.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
> 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-12 Thread Wei Wei
I am new to Django. But does the error message literally mean you have
duplicated records against your unique_together constriction?

On Sat, Oct 13, 2012 at 9:47 AM, Zheng Li <dllizh...@gmail.com> wrote:

> class AB(models.Model):
> a = models.ForeignKey(A)
> b = models.ForeignKey(B)
> c = models.IntegerField(default=0)
> d = models.FloatField(default=0)
> e = models.IntegerField(default=0)
> f = models.FloatField(default=0)
> class Meta:
> unique_together = (('a', 'b'),)
>
> I have a class like above.
> when I call get_or_create, sometimes IntegrityError: (1062, "Duplicate
> entry) error happens.
> a, _ = AB.objects.get_or_create(a=a, b=b)
>
> I really have googled and worked on it for a while, but still nothing.
> anyone can help?
> Thanks in advance.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



get_or_create gave IntegrityError: (1062, "Duplicate entry) error sometimes

2012-10-12 Thread Zheng Li
class AB(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
c = models.IntegerField(default=0)
d = models.FloatField(default=0)
e = models.IntegerField(default=0)
f = models.FloatField(default=0)
class Meta:
unique_together = (('a', 'b'),)

I have a class like above.
when I call get_or_create, sometimes IntegrityError: (1062, "Duplicate entry) 
error happens.
a, _ = AB.objects.get_or_create(a=a, b=b)

I really have googled and worked on it for a while, but still nothing.
anyone can help?
Thanks in advance.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError at /add/ PRIMARY KEY must be unique

2012-09-27 Thread akaariai
.create() creates the object into DB, then .save(force_insert=True)
tries to insert the same object with the same ID again -> integrity
error. Seems like you don't need the second save at all.

 - Anssi

On 27 syys, 15:39, Amyth Arora <aroras.offic...@gmail.com> wrote:
> Not quite sure, but it seems like the save() method is being called twice
> so it is trying to create insert an entry with a primary key that already
> exists.
>
>
>
>
>
>
>
>
>
> On Thu, Sep 27, 2012 at 2:23 PM, enemybass <dominikan...@gmail.com> wrote:
> >  http://wklej.org/id/837631/- models, traceback, urls, views, database
> > structure
>
> > After adding data to database I have error (data is added correctly but
> > displays an error):
>
> > Exception Type: IntegrityError at /add/Exception Value: PRIMARY KEY must be 
> > unique
>
> > def add(request):
> >    if request.user.is_authenticated():
> >            user = request.user
> >                    b = Product.objects.get(id=3)
> >                    e = b.basket_set.create(name='basket_name', owner=user)
> >            e.save(force_insert=True)
>
> >    return render_to_response('basket.html')
>
> > How to fix it?
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To view this discussion on the web visit
> >https://groups.google.com/d/msg/django-users/-/mdIBvzeje1gJ.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.
>
> --
> Thanks & Regards
> 
>
> Amyth [Admin - Techstricks]
> Email - aroras.offic...@gmail.com, ad...@techstricks.com
> Twitter - @mytharorahttp://techstricks.com/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError at /add/ PRIMARY KEY must be unique

2012-09-27 Thread Amyth Arora
Not quite sure, but it seems like the save() method is being called twice
so it is trying to create insert an entry with a primary key that already
exists.


On Thu, Sep 27, 2012 at 2:23 PM, enemybass <dominikan...@gmail.com> wrote:

>  http://wklej.org/id/837631/ - models, traceback, urls, views, database
> structure
>
>
> After adding data to database I have error (data is added correctly but
> displays an error):
>
>
>
> Exception Type: IntegrityError at /add/Exception Value: PRIMARY KEY must be 
> unique
>
>
> def add(request):
>   if request.user.is_authenticated():
>   user = request.user
>   b = Product.objects.get(id=3)
>   e = b.basket_set.create(name='basket_name', owner=user)
>   e.save(force_insert=True)
>   
>   return render_to_response('basket.html')
>
>
> How to fix it?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/mdIBvzeje1gJ.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Thanks & Regards


Amyth [Admin - Techstricks]
Email - aroras.offic...@gmail.com, ad...@techstricks.com
Twitter - @mytharora
http://techstricks.com/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



IntegrityError at /add/ PRIMARY KEY must be unique

2012-09-27 Thread enemybass
 http://wklej.org/id/837631/ - models, traceback, urls, views, database 
structure


After adding data to database I have error (data is added correctly but 
displays an error):



Exception Type: IntegrityError at /add/Exception Value: PRIMARY KEY must be 
unique


def add(request):
if request.user.is_authenticated():
user = request.user
b = Product.objects.get(id=3)
e = b.basket_set.create(name='basket_name', owner=user)
e.save(force_insert=True)

return render_to_response('basket.html')


How to fix it?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/mdIBvzeje1gJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Jon Blake
Thanks, Ian, I did miss that. Bookmarked for future reference.

On Saturday, September 1, 2012 3:16:38 PM UTC+10, Ian wrote:
>
> On Fri, Aug 31, 2012 at 10:03 PM, Jon Blake  
> wrote: 
> > Querying column timestamp of view user_objects for tables, sequences and 
> > triggers appears to confirm my understanding of what base.py does. I'll 
> drop 
> > and recreate my user account, and try again. I'll advise how this goes. 
> Does 
> > the Django doco have any specific documentation for the Oracle back end? 
> If 
> > so, I missed it! I'm happy to provide specific doco for the Oracle back 
> end 
> > if that would assist... 
>
> Yes, please see: 
>
> https://docs.djangoproject.com/en/1.4/ref/databases/#oracle-notes 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/cs7WQZmkJGQJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Jon Blake
I've just dropped and re-created my user account with required privileges, 
and all has gone as expected. Table auth_permission has 18 rows.

At the point where I'm prompted to create a superuser account, I made the 
mistake of resizing my terminal window, which resulted in exception 
EOFError being raised on the call to raw_input() in procedure 
create_superuser(). Sigh, and start again... This exception can be handled 
by calling raw_input() in a try block, and handling exception EOFError by 
(for example) shifting the cursor up one row by printing chr(27) +'[A' . 
HTH.

Again, many thanks. I'm on my way with Django - looking like a great 
framework!
  Jon

On Saturday, September 1, 2012 2:03:42 PM UTC+10, Jon Blake wrote:
>
> Thanks, Ian and Amyth, for your responses.
>
> I encountered the CREATE TRIGGER privilege issue early in my trials with 
> Django with the Oracle database back end - Django propagated an Oracle 
> "insufficient privileges" exception. That was quickly sorted by granting 
> the required privilege to my user account.
>
> On looking at ticket #17015 you pointed me to, it looks like I might have 
> stumbled over the same issue as in the reply to ikelly. My user did not 
> have the CREATE TRIGGER privilege the first time I tried to run syncdb, but 
> did have the CREATE_TABLE and CREATE_SEQUENCE privileges. After granting 
> the missing privilege and running syncdb again, I then got the ORA-01400 
> exception on table auth_permission.
>
> I'm guessing that the first table that oracle back end base.py creates is 
> auth_permission, and that the table and its primary key sequence were 
> successfully created, because the user had the required privileges. Module 
> base.py then terminated on attempting to create the trigger for the table. 
> After granting CREATE TRIGGER and running syncdb again, base.py noted that 
> table auth_permission exists, so nothing more needed to be done for that 
> table. Module base.py then went on and created the remaining tables, 
> sequences and triggers. Missing trigger auth_permission_tr -> no primary 
> key raised from auth_permission_sq -> ORA-01400 on table auth_permission 
> inserts.
>
> Querying column timestamp of view user_objects for tables, sequences and 
> triggers appears to confirm my understanding of what base.py does. I'll 
> drop and recreate my user account, and try again. I'll advise how this 
> goes. Does the Django doco have any specific documentation for the Oracle 
> back end? If so, I missed it! I'm happy to provide specific doco for the 
> Oracle back end if that would assist...
>
> Once again, many thanks
>
> Jon
>
>
> On Saturday, September 1, 2012 1:23:28 AM UTC+10, Ian wrote:
>>
>> On Friday, August 31, 2012 12:10:54 AM UTC-6, Amyth wrote:
>>>
>>> Hey Jon,
>>>
>>> I guess this is because of a bug in django. Django already has a open 
>>> ticket for this bug. Check it out 
>>> here
>>> . 
>>>
>>>
>> As described in that ticket, the reason for the problem is probably just 
>> that the Django user does not have the CREATE TRIGGER privilege, which it 
>> needs.  The bug in Django is just that this condition is not detected and 
>> reported at the time the table is created, instead of getting a rather more 
>> obscure error message at the time the table is populated.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/MrFmP3gYrF0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Ian Kelly
On Fri, Aug 31, 2012 at 10:03 PM, Jon Blake  wrote:
> Querying column timestamp of view user_objects for tables, sequences and
> triggers appears to confirm my understanding of what base.py does. I'll drop
> and recreate my user account, and try again. I'll advise how this goes. Does
> the Django doco have any specific documentation for the Oracle back end? If
> so, I missed it! I'm happy to provide specific doco for the Oracle back end
> if that would assist...

Yes, please see:

https://docs.djangoproject.com/en/1.4/ref/databases/#oracle-notes

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Jon Blake
Thanks, Ian and Amyth, for your responses.

I encountered the CREATE TRIGGER privilege issue early in my trials with 
Django with the Oracle database back end - Django propagated an Oracle 
"insufficient privileges" exception. That was quickly sorted by granting 
the required privilege to my user account.

On looking at ticket #17015 you pointed me to, it looks like I might have 
stumbled over the same issue as in the reply to ikelly. My user did not 
have the CREATE TRIGGER privilege the first time I tried to run syncdb, but 
did have the CREATE_TABLE and CREATE_SEQUENCE privileges. After granting 
the missing privilege and running syncdb again, I then got the ORA-01400 
exception on table auth_permission.

I'm guessing that the first table that oracle back end base.py creates is 
auth_permission, and that the table and its primary key sequence were 
successfully created, because the user had the required privileges. Module 
base.py then terminated on attempting to create the trigger for the table. 
After granting CREATE TRIGGER and running syncdb again, base.py noted that 
table auth_permission exists, so nothing more needed to be done for that 
table. Module base.py then went on and created the remaining tables, 
sequences and triggers. Missing trigger auth_permission_tr -> no primary 
key raised from auth_permission_sq -> ORA-01400 on table auth_permission 
inserts.

Querying column timestamp of view user_objects for tables, sequences and 
triggers appears to confirm my understanding of what base.py does. I'll 
drop and recreate my user account, and try again. I'll advise how this 
goes. Does the Django doco have any specific documentation for the Oracle 
back end? If so, I missed it! I'm happy to provide specific doco for the 
Oracle back end if that would assist...

Once again, many thanks

Jon


On Saturday, September 1, 2012 1:23:28 AM UTC+10, Ian wrote:
>
> On Friday, August 31, 2012 12:10:54 AM UTC-6, Amyth wrote:
>>
>> Hey Jon,
>>
>> I guess this is because of a bug in django. Django already has a open 
>> ticket for this bug. Check it out 
>> here
>> . 
>>
>>
> As described in that ticket, the reason for the problem is probably just 
> that the Django user does not have the CREATE TRIGGER privilege, which it 
> needs.  The bug in Django is just that this condition is not detected and 
> reported at the time the table is created, instead of getting a rather more 
> obscure error message at the time the table is populated.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/LXuXcxvnlnkJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Ian
On Friday, August 31, 2012 12:10:54 AM UTC-6, Amyth wrote:
>
> Hey Jon,
>
> I guess this is because of a bug in django. Django already has a open 
> ticket for this bug. Check it out 
> here
> . 
>
>
As described in that ticket, the reason for the problem is probably just 
that the Django user does not have the CREATE TRIGGER privilege, which it 
needs.  The bug in Django is just that this condition is not detected and 
reported at the time the table is created, instead of getting a rather more 
obscure error message at the time the table is populated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/BKHoqoZkF6oJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-31 Thread Amyth Arora
Hey Jon,

I guess this is because of a bug in django. Django already has a open
ticket for this bug. Check it out
here
.

On Fri, Aug 31, 2012 at 7:17 AM, Jon Blake  wrote:

> Just discovered Django and trying out the Django 1.4 tutorial with an
> Oracle backend database. In my database, I have created user django with
> privs create session, create table, create sequence, create trigger. The
> DATABASES dictionary in settings has been edited to set the default
> settings to the Oracle engine, and the database name, user and password
> specified.
>
> When I run:
>
> $ python manage.py syncdb
>
> I see tables are created, but I also get a traceback ending with:
>
> File "/usr/lib/python2.7/site-packages/django/db/backends/oracle/base.py",
> line 675, in execute
> return self.cursor.execute(query, self._param_generator(params))
> django.db.utils.IntegrityError: ORA-01400: cannot insert NULL into
> ("DJANGO"."AUTH_PERMISSION"."ID")
>
> I did not see a prompt to create a superuser account.
>
> Oracle SQL*Developer shows that schema django contains 9 tables (including
> auth_permission), 16 indexes, 7 triggers and 8 sequences. Table
> django_content_type contains three rows, and the others are empty.
>
> Can anyone advise on how to resolve the ORA-01400 error?
>
> Run-time environment:
>   O/S: Fedora 14
>   Django: 1.4.1
>   Python: 2.7
>   DB: Oracle Database 11.1.0.6.0
>   cx_Oracle client: 11.1.0.6.0
>
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/O5XePWI1ee4J.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Thanks & Regards


Amyth [Admin - Techstricks]
Email - aroras.offic...@gmail.com, ad...@techstricks.com
Twitter - @a_myth_
http://techstricks.com/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Syncdb Error With Oracle Database - IntegrityError Exception

2012-08-30 Thread Jon Blake
Just discovered Django and trying out the Django 1.4 tutorial with an 
Oracle backend database. In my database, I have created user django with 
privs create session, create table, create sequence, create trigger. The 
DATABASES dictionary in settings has been edited to set the default 
settings to the Oracle engine, and the database name, user and password 
specified.

When I run:

$ python manage.py syncdb

I see tables are created, but I also get a traceback ending with:

File "/usr/lib/python2.7/site-packages/django/db/backends/oracle/base.py", 
line 675, in execute
return self.cursor.execute(query, self._param_generator(params))
django.db.utils.IntegrityError: ORA-01400: cannot insert NULL into 
("DJANGO"."AUTH_PERMISSION"."ID")

I did not see a prompt to create a superuser account.

Oracle SQL*Developer shows that schema django contains 9 tables (including 
auth_permission), 16 indexes, 7 triggers and 8 sequences. Table 
django_content_type contains three rows, and the others are empty.

Can anyone advise on how to resolve the ORA-01400 error?

Run-time environment:
  O/S: Fedora 14
  Django: 1.4.1
  Python: 2.7
  DB: Oracle Database 11.1.0.6.0
  cx_Oracle client: 11.1.0.6.0



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/O5XePWI1ee4J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: IntegrityError at /register/ auth_user.username may not be NULL

2012-03-28 Thread laurence Turpin


On Mar 28, 9:38 pm, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Wednesday, 28 March 2012 20:31:09 UTC+1, laurence Turpin wrote:
>
> > I'm getting the following error with my registration  section of my
> > program.
>
> > IntegrityError at /register/
> > auth_user.username may not be NULL
>
> > I am using django 1.3.1 and python 2.7.2 and I'm using sqlite3 as the
> > database.
> > I am a newbie and I'm learning Djanogo from the book "Learning website
> > development with Django"
>
> > The registration form is displayed ok  and I'm able to fill it out and
> > it is when I click register that the problem occurs.
>
> > /// 
> > /// 
> > /
>
> > My views.py  looks like the following and register_page is the
> > relevant function here:
>
> > 
>
> >     def clean_username(self):
> >         username = self.cleaned_data['username']
> >         if not re.search(r'^\w+$', username):
> >             raise forms.ValidationError('Username can only contain
> > alphanumeric characters and underscores')
> >             try:
> >                 User.objects.get(username=username)
> >             except ObjectDoesNotExist:
> >                 return username
> >             raise forms.ValidationError('Username already taken. ')
>
> Looks like you have an indentation problem in clean_username - the lines
> under the first "raise forms.ValidationError" should be one level to the
> left, otherwise they will never be reached and the method will never return
> the cleaned value for username.
> --
> DR.

Thank you Danial you are absolutely right. I tried what you said and
it works fine now.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



  1   2   3   >