File replacer mix-in
Hey. I needed a fix to make some (but not all) models in an existing app delete the previous content of a FileField after update. I figured out a workaround, but should I be wary of anything with this implementation, or is there a better way to do it? Thanks. -Mick. from djano.contrib.contenttypes.models import Model class OrderedModel(Model): dev save(self): # Some custom save code to facilitate ordering class FileReplacerMixin(): def save(self): # Code to check each FileField for changes and delete as appropriate. # Now I can have Ordered or Unordered models which # either replace files or keep the previous content around, such as: class OrderedModelWhichReplacesFiles(OrderedModel, FileReplacerMixin): def save(self): # Call the mix-in to replace files FileReplacerMixin(self) # Call the parent class's save function super (OrderedModelWhichReplacesFiles, self).save() -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@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: v1.2 message framework - messages created outside of the request cycle
I've encountered same issue. My solution is simple model and middleware: class OfflineNotification(models.Model): user = models.ForeignKey(User) message = models.TextField() level = models.PositiveSmallIntegerField(default=20) created = models.DateTimeField(auto_now_add=True) class OfflineNotificationsMiddleware: def process_request(self, request): if request.user.is_authenticated(): notifications = OfflineNotification.objects.filter(user=request.user).distinct('message') for notification in notifications: messages.add_message(request, notification.level, notification.message) if notifications: OfflineNotification.objects.filter(user=request.user).delete() Hope it will help you. On Jul 8, 12:27 am, jyunis wrote: > Hey all, > > I'm currently developing an application using Django's deprecated user > messaging functionality and one of the features I depend on is the > ability to set messages for a particular user from a back-end process, > i.e. outside of the request cycle. In my backend process, I have > access to the User object, but of course not the request object. > > I see that the new Django 1.2 message framework does not support this, > but I am wondering if that use case has been addressed in any other > way. I hate to continue development using a deprecated feature, but > the lack of offline messaging from the message framework is a > significant barrier to migration. > > -- > Jeremy -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@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: @login_required & Redirect...best practice?
When I have a view that's @login_required -- and the user isn't logged > in -- what's the best way to deal with the URL they wanted in the > first place? Assuming they log in properly and I want to then > redirect them on to where they intended to go in the first > place...what's the best practice? @login_required will redirect to your login page a site the "next" param e.g. /accounts/login?next=/where/you/where The base url for that login page can be set in settings.py as LOGIN_URL https://docs.djangoproject.com/en/1.3/topics/auth/#the-login-required-decorator >From the login page you will want to set "next" param in post form used for >login (or use the built in form in the auth module) Mick -- 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: Chat
If you are using XMPP (which I do recommend) you'll want to check out the JS library Strophe (http://strophe.im/) which handles XMPP over HTTP. You will still need a server side BOSH endpoint, either a connection manager that allows you to connect to existing xmpp servers, like gtalk or jabber.org. https://github.com/twonds/punjab Or use the built in support for BOSH in Ejabberd, or Openfire. An example of django + strophe +ejabberd project is speeqe.com It is a multiuser chat site. The source is on github: https://github.com/thepug/Speeqe _Mick On Friday, June 17, 2011 at 7:37 AM, illuminated wrote: > You'd have to first decide the chat server platform... > > In case you go down the Jabber/XMPP road (and choose something like > Ejabberd or OpenFire or something else), you can use the pyxmpp > (http://pyxmpp.jajcus.net/) or xmpppy (http://xmpppy.sourceforge.net/) > library. > > On Jun 16, 5:34 pm, Nadae Ivar BADIO wrote: > > Hi, > > > > I am programing a chat with python django anyone have a example for me > > please. > > -- > 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: Serving static/dynamic files under same suburl
Nginx can test to see if a file is available, and if it exist load that instead of proxying the request to django. location / { alias /var/www/static/; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; } } Now if /var/www/static/foo.js exists, but /var/www/static/bar.js does not foo.js will be served as a static file by nginx and the bar.js request will be passed to django where you can use a template to dynamically serve it. Mick On Monday, June 27, 2011 at 8:23 AM, Jani Tiainen wrote: > Apparently I didn't made myself clear enough. > > So let me clarify: > > I have two files that must be accessed using following urls: > > /myapp/views/foo.js > /myapp/views/bar.js > > foo.js is a static file and can (and should) be served by using static > serving, like webserver. > > bar.js instead is a file that contains django template directives and > must be served through django template rendering mechanism. > > On Jun 27, 5:14 pm, Shawn Milochik wrote: > > This can (and probably should) be handled by your Web server. > > > > For example, in nginx you may be serving the Django app with something > > like this: > > > > location / { > > proxy_passhttp://127.0.0.1:8400; > > } > > > > And for static content nginx may direct the request elsewhere. This > > example directs > > any requests ending in '.html' to a static folder. > > > > location ~ ^/.*\.html{ > > root /var/www/my_static_content; > > } > > -- > 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: oAuth 2.0
In the README for python-oauth2 (https://github.com/simplegeo/python-oauth2) there is a good example in the "Logging into Django w/ Twitter" section. _Mick On Wednesday, March 2, 2011 at 2:36 PM, Олег Корсак wrote: > hello. Is there any tutorial/example about oAuth 2.0 built into Django > and through python-oauth2-1.2.1 ? thanks > -- 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: oAuth 2.0
First are you trying to preform actions on the user's behalf on a thrid party site, or are you trying to authorize third parties to take an action on behalf of a user of your site? (are you a Client or a Server in this case?) if you are a Client you need to request a request_token for the service you are authenticating with, redirect the user to an authorization url for them to login/authorize you, and then exchange the request token for an access_token. That is what the python-auth2 django example code does. If you are a Server wanting to hand out keys to authenticate your service's users, there is a Server class in python-oauth2 that will be very helpful (especially in checking request signatures) But I dont know of any example django code (Someone else might). _Mick On Thursday, March 3, 2011 at 2:51 AM, Олег Корсак wrote: > Yes. But I'm stuck with first step... As I understood - first of all I need > to ask for request_token from my server. Done this. But what kind of token > and how server needs to return? > - Исходное сообщение - > > In the README for python-oauth2 > > (https://github.com/simplegeo/python-oauth2) there is a good example in > > the "Logging into Django w/ Twitter" section. > > > > > > > > > > _Mick > > On Wednesday, March 2, 2011 at 2:36 PM, Олег Корсак wrote: > > > hello. Is there any tutorial/example about oAuth 2.0 built into Django > > > and through python-oauth2-1.2.1 ? thanks > > > > -- > > 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: oAuth 2.0
> And then Server needs to return token. The problem is that I can't find > how to do this in python-oauth2 way (not with Django). > Right now I have: > def request_token(request): > data = {'token': 'token123'} > return HttpResponse(simplejson.dumps(data), content_type = > 'application/javascript; charset=utf8') > > but this is for testing purpose only. I don't even know what token > should look like. python-oauth2 doesnt support generating new tokens, just verifying based on them. It is up to how you want to generate tokens, and where to store them. Perhaps use the uuid module built into python(http://docs.python.org/library/uuid.html), or some other way of creating unique strings. some people (twitter) like to include the account id in the token, which certainly helps debug at times, but isnt at all needed. Mick -- 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.
Django Searchfilter not functioning I don't understand why
views.py class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter,OrderingFilter,] search_fields = ['first_name'] def get(self,request): users=User.objects.all() serializer=UserSerializer(users,many=True) return Response(serializer.data) def post(self, request): serializer = UserSerializer(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) def delete(self, request, pk, format=None): user = self.get_object(pk) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields='__all__' models.py class User(models.Model): user_id = models.AutoField(primary_key=True) first_name = models.CharField(_("Firstname"),max_length=255,null = False) last_name =models.CharField(_("last_name"),max_length=255,null = False) -- 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/4a995b10-5924-4066-a59f-c5479b6654c5%40googlegroups.com.
Django mail
I am using django rest auth I want to fire a mail to the user if the user hasn't verified in one day after sign up automatically. How to do ? -- 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/ab040c0a-c9a8-4165-ae47-fd9fe93df0fe%40googlegroups.com.
Django Mails
I want the admin and the user themselves both to verify the mail on the user registration.And then only the user is being validated. -- 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/a1363076-8bec-41cc-8f11-dfed41cd9a24%40googlegroups.com.
Password Reset Template customization
I am trying to override the default template of the password reset but I am getting in email the tags instead of proper formatting of the HTML page 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 view this discussion on the web visit https://groups.google.com/d/msgid/django-users/37f0595c-5a6c-4d78-9169-75ecc85f6d12%40googlegroups.com.
Password Reset Template customization
I am not able to customise the default django rest auth password reset template.Can anyone please 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 view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1c8bdf17-b7b9-4b6d-beed-32fe60082b4f%40googlegroups.com.
gdal installed still
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your setting s. -- 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/f5552467-2dfb-48d3-88f5-f66ab5abc258%40googlegroups.com.
note sharing
Hello guys Please anyone help me out I am not able to figure out the internal sharing with selected? Django website where users can privately create and share notes. All users will have an account and they will be able to signup then login to their account. Once logged in they will be able to write notes in the web app. While creating the note they will have the option to share the note with another user of the web app. The app will contain a page where the user can see the notes that they have created and the notes that have been shared with them. Thank you -- 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/ab4a9079-ccd1-4ed7-8061-fb539b740367o%40googlegroups.com.
Please help I want to list down all the users with the sharewith from the frontend in backend I used Many to Many field and also my data is not getting into database
views.py def notesadd(request): form = NoteForm(request.POST or None) if form.is_valid(): form.save() form=NoteForm() context = { 'form': form } print('submitted') return render(request, 'notes.html', context) models.py class Notes(models.Model): sharewith = models.ManyToManyField(User, blank=True, null=True) subject = models.CharField(max_length=10, null=True) uploadingdate = models.DateTimeField(null=True) notesfile = models.FileField(null=True) description = models.TextField(max_length=50,null=True) def __str__(self): return self.sharewith.user.username forms.py class NoteForm(forms.ModelForm): class Meta: model=Notes fields = [ 'sharewith' , 'subject', 'uploadingdate', 'notesfile', 'description' ] notes.html {% extends 'navigation.html' %} {% block body %} {% csrf_token %} Subject: {{note.subject}} Description: Choose Notes: Share With {{form.username}} Submit {% endblock %} admin.py from django.contrib import admin from .models import Notes admin.site.register(Notes) -- 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/c669fa9c-a4ec-45ed-8409-abe85ce5982do%40googlegroups.com.
Django
How to make custom url in the Django,I want to extract title from the HTML template and then get it displayed in url -- 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/79b53c2a-774f-4fa2-90c3-a9e2e9b333e6%40googlegroups.com.
django
|as_crispy_field got passed an invalid or inexistent field -- 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/18ec9c79-2011-444c-80ac-0f5a212a1103%40googlegroups.com.
I am filling up the form but my filled out items are not rendering into database and also the session is not working
views.py from django.views.generic import FormView, TemplateView from django.shortcuts import render,redirect from .models import modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10 from .forms import FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10 def FormStep1View(request): forms = FormStep1() return render(request, 'form_1.html', context={'form': forms}) def addForm1(request): form = FormStep1(request.POST) if form.is_valid(): u=modelstep1() u.name = form.cleaned_data['name'] u.email = form.cleaned_data['email'] u.link_sent = form.cleaned_data['link_sent'] u.title = request.POST.get('name') u.content = request.POST.get('email') u.content = request.POST.get('link_sent') u.save() request.session['name'] = u.name request.session['email'] = u.email request.session['link_sent'] =u.link_sent return redirect('/form/2/',context={'form': form}) def FormStep2View(request): forms = FormStep2() return render(request, 'form_2.html', context={'form': forms}) def addForm2(request): form = FormStep2(request.POST) if form.is_valid(): v=modelstep2() v.country=form.cleaned_data['country'] v.city=form.cleaned_data['city'] v.year_of_birth=form.cleaned_data['year_of_birth'] v.current_grade=form.cleaned_data['current_grade'] v.university=form.cleaned_data[' university'] v.school=form.cleaned_data['school'] v.native_language=form.cleaned_data['native_language'] v.phone_number = form.cleaned_data['phone_number'] v.email_business=form.cleaned_data['email_business'] v.social_media=form.cleaned_data['social_media'] request.session['country'] = v.country request.session['city'] = v.city request.session['year_of_birth'] = v.year_of_birth request.session['current_grade'] = v.current_grade request.session['university'] = v.university request.session['school'] = v.school request.session['native_language'] = v.native_language request.session['phone_number'] = v.phone_number request.session['email_business'] = v.email_business request.session['social_media']= v.social_media return redirect(request, '/form/3/', context={'form':form}) def FormStep3View(request): forms = FormStep3() return render(request, 'form_3.html', context={'form': forms}) def addForm3(request): form = FormStep3(request.POST) if form.is_valid(): x=modelstep3() x.internship_idea = form.cleaned_data['internship_idea'] x.startup_business = form.cleaned_data['startup_business'] x.goals = form.cleaned_data['goals'] x.established_year = form.cleaned_data['established_year'] x.number_of_employees = form.cleaned_data['number_of_employees'] x.months = form.cleaned_data['months'] x.website = form.cleaned_data['website'] x.cell_number_business = form.cleaned_data['cell_number_business'] x.co_founder_details = form.cleaned_data['co_founder_details'] x.social_media_business = form.cleaned_data['social_media_business'] x.save() request.session['internship_idea'] = x.internship_idea request.session['startup_business'] = x.startup_business request.session['goals'] = x.goals request.session['established_year'] = x.established_year request.session['number_of_employees'] = x.number_of_employees request.session['months'] = x.months request.session['website'] = x.website request.session['cell_number_business'] = x.cell_number_business request.session['co_founder_details']= x.co_founder_details request.session['social_media_business'] = x.social_media_business return redirect(request,'/form/4/',context={'form':form}) def FormStep4View(request): forms = FormStep4() return render(request, 'form_4.html', context={'form': forms}) def addForm4(request): form = FormStep4(request.POST) if form.is_valid(): y=modelstep4() y.funding = form.cleaned_data['funding'] y.domain = form.cleaned_data[' domain'] y.stage_business = form.cleaned_data['stage_business'] y.initial_idea = form.cleaned_data['initial_idea'] y.business_plan = form.cleaned_data['business_plan'] y.stage_website = form.cleaned_data['stage_website'] y.presence_on_social = form.cleaned_data['presence_on_social'] y.ventured_registered = form.cleaned_data['ventured_registered'] y.vent_type = form.cleaned_data['vent_type'] y.date_register = form.cleaned_data['d
I am not able to render my file fields in the Database so not able to upload image
forms.py class FormStep8(forms.Form): portraitphoto=forms.ImageField(label='Portrait photos of yourself') high_resolution=forms.ImageField(label='3 High Resolution pictures') company_logo=forms.ImageField(label='Company Logo') product_images=forms.ImageField(label='Product Images') location_img=forms.ImageField(label='Office Location Image') product_video=forms.FileField(label='Product Video') customer_testimonial_video=forms.FileField(label='Customer Testimonial video') models.py class modelstep8(models.Model): portraitphoto=models.ImageField() high_resolution=models.ImageField() company_logo=models.ImageField() product_images=models.ImageField() location_img=models.ImageField() product_video=models.FileField() customer_testimonial_video=models.FileField() error portraitphotoThis field is required.high_resolutionThis field is required.company_logoThis field is required.product_imagesThis field is required.location_imgThis field is required.product_videoThis field is required.customer_testimonial_videoThis field is required. -- 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/38fef6ae-2b89-4070-b46c-c1a905aa6258%40googlegroups.com.
Object of type date is not JSON serializable
TypeError at /addForm4 Object of type date is not JSON serializable Request Method: POST Request URL: http://127.0.0.1:8000/addForm4 Django Version: 3.0.1 Exception Type: TypeError Exception Value: Object of type date is not JSON serializable Exception Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py in default, line 179 Python Executable: C:\Users\Administrator\Scripts\python.exe -- 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/c6bda6c6-f2ba-407a-9b10-8a6fa1d203a8%40googlegroups.com.
Re: PIL on 10.6 = PAIN
You could try ActivePython: http://www.activestate.com/activepython/downloads Then {{{ $ pypm install pil The following packages will be installed to ~/.local (2.6): pil-1.1.7-1 Get: [pypm-free.activestate.com] pil 1.1.7-1 Installing pil-1.1.7-1 Fixing script ~/.local/bin/pilconvert.py Fixing script ~/.local/bin/pildriver.py Fixing script ~/.local/bin/pilfile.py Fixing script ~/.local/bin/pilprint.py [22:17:39 tre...@boa:~/Movies/tech] $ python ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:02:28) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import _imaging }}} Trent -- Trent Mick -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@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: ManyToManyField and get_or_create
I have the same problem, looks like it's a bug: https://code.djangoproject.com/ticket/18896 On Friday, 31 August 2012 18:55:39 UTC-4, Matt Long wrote: > > Bump? > > Almost exactly 4 years later, I've ran into this exact same issue in > Django 1.4. Attempting to use get_or_create through a ManyToMany field > results in an integrity error if the object already exists but is not yet > associated with the parent object. To use the OP's example, if a Tag with > name "foo" exists but is not yet associated with a given Thing instance, > using .tags.get_or_create(name='foo') will indeed raise an IntegrityError: > > foo_tag = Tag(name='foo') > foo_tag.save() > > a_thing = Thing(name='a') > a_thing.save() > a_thing.tags.get_or_create(name='foo') > > Traceback (most recent call last): > File "", line 1, in > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", > line 616, in get_or_create > super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs) > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line > 134, in get_or_create > return self.get_query_set().get_or_create(**kwargs) > File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", > line 449, in get_or_create > obj.save(force_insert=True, using=self.db) > File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", > line 463, in save > self.save_base(using=using, force_insert=force_insert, > force_update=force_update) > File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", > line 551, in save_base > 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", line > 203, in _insert > return insert_query(self.model, objs, fields, **kwargs) > File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", > line 1576, in insert_query > return query.get_compiler(using=using).execute_sql(return_id) > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", > line 910, in execute_sql > cursor.execute(sql, params) > File > "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line > 40, in execute > return self.cursor.execute(sql, params) > File > "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", > line 337, in execute > return Database.Cursor.execute(self, query, params) > IntegrityError: column name is not unique > > I've traced the problem to being that the ManyRelatedManager includes its > core_filters in its get_query_set method. This results in the "get" portion > of get_or_create to only return a hit if the Tag exists and is already > associated to the calling Thing instance. Given the nature of a > many-to-many relationship, it should not be a requirement that a Tag > already be linked to the calling Thing for get_or_create to find it; it > should be enough that the Tag simply exists. All that should happen in that > scenario is that the (existing) Tag's relationship with the calling Thing > be created/saved. > > On Monday, September 1, 2008 8:04:00 PM UTC-7, Cap wrote: >> >> I'm having problems using get_or_create with a ManyToManyField and I'm >> not sure whether the problem is me or Django. >> >> I have two models: >> >> class Tag(models.Model): >> name = models.CharField(max_length=256, unique=True) >> >> class Thing(models.Model): >> name = models.CharField(max_length=256) >> tags = models.ManyToManyField(Tag) >> >> When I try to add a tag that already exists, as: >> >> a = Thing(name='a') >> a.save() >> a.tags.get_or_create(name='foo') >> >> I get sqlite3.IntegrityError: column name is not unique. >> >> But when I do it like so: >> >> a = Thing(name='a') >> a.save() >> foo, created = Tag.objects.get_or_create(name='foo') >> a.tags.add(foo) >> >> I have no problems. >> >> I noticed that http://code.djangoproject.com/ticket/3121 seemed to >> address something like this, so I pulled the latest Django (8834), but >> the problems remains. >> >> Am I doing it wrong? >> > -- 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.