Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - IntegrityError: duplicate key value
I'm using Django and PostgreSQL and i had to make some modification to my database like deleting and moving tables around. Now when i try to edit the records in those tables using the admin panel of Django, i get Server 500 Error with the following message: IntegrityError: duplicate key value violates unique constraint "database_pkey" DETAIL: Key(id)=(17523) already exists. How can i fix this? EDIT: I get this error for literally every field in every table i try to edit, so the database_pkey varies depends on the field. -
Page not found (404) django view
I am trying to wire up a view based on the django tutorial (1.8), and am for some reason not getting a basic url to work: Page not found (404) Settings INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'events', ) In the main folder, I have these_events/these_events/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^/', include('events.urls')), ] In the events app, I have these_events/events/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r"^$", views.search_db, name='search-db') ] these_events/events/views.py: from django.shortcuts import render from django.http import HttpResponse def search_db(request): return HttpResponse("hello, world") This has me befuddled as I followed the example, and this is the way I remember using django in the past. Thank you -
get_FOO_display equivalent for ChoiceBlock
I have a block as follows: class SomeBlock(blocks.StructBlock): choice = blocks.ChoiceBlock(choices=(('Y', 'Yellow'), ...)) # more fields class Meta: template = 'myapp/blocks/some_block.html' In my template I have: {% load wagtailcore_tags %} <div>{{ value.choice }}</div> This would display 'Y' as expected but how do I get it to display as 'Yellow'? These variations do not work (get no output): {{ value.get_choice_display }} {{ value.bound_blocks.get_choice_display }} -
Django REST serialize output - group by foreign keys
I have models like below. Restaurant Model class Restaurant(models.Model): name = models.CharField(max_length=40, verbose_name='Name') Menu Model class Menu(models.Model): name = models.CharField(max_length=40, unique=True, verbose_name='menu name') Item Model class Item(models.Model): restaurant = models.ForeignKey(Restaurant) menu = models.ForeignKey(Menu) name = models.CharField(max_length=500) price = models.IntegerField(default=0) I want to get the menus for the shop id. How can I group my results by menu for the restaurant id ? call GET /menus/restaurant_id Sample. { name: menu name 1 items: [ {item1}, {item2}] }, { name: menu name 2 items: [ {item1}, {item2}] } Thanks.. -
Django Unit Testing: cannot mock django.core.urlresolvers.resolve
I'm trying to mock the django.core.urlresolvers.resolve function, but it doesn't seem to be work. I've tested with custom functions and it works like a charm, but mock ignores resolve completely. Code: test_something.py: class SomethingTestCase(TestCase) def setUp(self): self.middleware = SomeMiddleware() self.request = Mock() self.request.session = {} @patch('django.core.urlresolvers.resolve', side_effect=lambda: None) def test_something(self): self.assertEqual(self.middleware.process_request(self.request), None) middleware.py class SomeMiddleware(object): def process_request(self, request): app = resolve(request.path).app_name print('App name: {}'.format(app)) This results in the following error: ====================================================================== ERROR: test_process_request_unauthenticated (something.tests.unit.test_middleware.SomethingTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "/home/user/projects/something/working/something/tests/unit/test_middleware.py", line 23, in test_process_request_unauthenticated self.assertEqual(self.middleware.process_request(self.request), None) File "/home/user/projects/something/working/something/middleware.py", line 14, in process_request app = resolve(request.path).app_name File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 534, in resolve return get_resolver(urlconf).resolve(path) File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 405, in resolve raise Resolver404({'path': path}) Resolver404: {u'path': u"<Mock name='mock.path' id='140678271233168'>"} My goal here is to make the resolve function returns something where I can get the app name. Why is mock.patch unable to override the resolve function? -
Django REST Framework - How to create an Order?
I am new at Django REST API, and my project has two models. Product (id, name, value) Order(id, client_name, product: ManyToMany(Product)) How can i create and order using the POST method? -
Fields of the instance are not displayed in the email template
Some fields of the instance does not show up in my email template. See below, the field user_phone is not displayed. I have view which get or create User: views.py # Get informations for creating the User user, created = User.objects.get_or_create( username=username, email=email, first_name=first_name, last_name=last_name, ) if created: user.groups.add(Group.objects.get(name='Clients')) user.profile.phone = telephone user.save() else: user.profile.phone = telephone user.save() I send an email to new user with there infos models.py @receiver(post_save, sender=User) def password_mail(sender, instance, **kwargs): if kwargs['created']: user_email = instance.email first_name = instance.first_name user_phone = instance.profile.phone subject, from_email, to = 'New account', 'mail@example.com', user_email text_content = render_to_string('accounts/mail_welcome.txt', {'first_name': first_name, 'user_phone': user_phone}) html_content = render_to_string('accounts/mail_welcome.html', {'first_name': first_name, 'user_phone': user_phone}) # create the email, and attach the HTML version as well. msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() And finally, this the email template: mail_welcome.txt {% autoescape off %} Hello {{ first_name }}, Here is you phone number : {{ user_phone }} {% endautoescape %} All the tags are displayed well except the user_phone. Is this because the way this field is saved in my view? Help appreciated :) -
DRF: Custom field error message
While creating simple login api using DRF, I encountered a problem. Two field email and password are required to login. If the fields are left blank following json message is shown: { "email": [ "This field may not be blank." ], "password": [ "This field may not be blank." ] } But I would like to customise the error message, say to something like, { "email": [ "Email field may not be blank." ], "password": [ "Password field may not be blank." ] } I tried the something like the following in validate() in serializers.py : if email is None: raise serializers.ValidationError( 'An email address is required to log in.' ) But it is not getting override, I'm not sure about the reason. -
~./zshrc : command not found: $
I'm currently going through Django tutorials on ProjectDjango.com. However I'm stuck on the very first bit! I'm told to enter the following into the command line : $ python -c "import django; print(django.get_version())" When I do this in the main CLI I get : ~ $ python -c "import django; print(django.get_version())" zsh: command not found: $ When I try it in the python terminal I get : >~ python Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >$ python -c "import django; print(django.get_version())" File "<stdin>", line 1 $ python -c "import django; print(django.get_version())" ^ SyntaxError: invalid syntax My research into this so far has led me to believe it could be a problem with my ./zshrc file, but this is way beyond my understanding of Macs, as a friend installed ohmyzsh for me. When I type echo $PATH in the CLI I get : /Users/davidmellor/bin:/usr/local/bin:/Users/davidmellor/bin:/usr/local/bin:/Users/davidmellor/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/davidmellor/anaconda/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/davidmellor/anaconda3/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/davidmellor/anaconda/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/davidmellor/anaconda3/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/davidmellor/anaconda/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/davidmellor/anaconda3/bin:/usr/bin:/bin:/usr/sbin:/sbin Which just seems messy to me! Thank you. PS This is my first SO post - apologies for the rubbish formatting. -
Send an email from the cron.py file
In the README.md of a Django project of which I have been part of the team recently, we have the way to define a cron job : Cron deployment/cron.template # /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH={{ venv_dir }}/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin * * * * * root python manage.py cron --minutely 01 * * * * root python manage.py cron --hourly 02 4 * * * root python manage.py cron --daily 22 4 * * 0 root python manage.py cron --weekly 42 4 1 * * root python manage.py cron --monthly 00 0 1 1 * root python manage.py cron --yearly @reboot root python manage.py cron --reboot # 06:00h AM: debits 00 6 * * * root $PYTHON_BIN manage.py cron --debits # 11:45h AM: deposits 45 11 * * * root $PYTHON_BIN manage.py cron --deposits Defining cron jobs Defining cron job is simple, just create a cron.py file in the loanwolf app and define your jobs using the desired interval as … -
Django - Exclude if fields are the same
My model looks like this: class Event(models.Model) ... capacity = models.IntegerField() date_from = models.DateTimeField() date_to = models.DateTimeField() ... Now, I want to retrieve the event count, except the ones that have date_from equal to date_to. My current query is: Events.objects.filter(capacity=100).exclude(date_from=F('date_to')).distinct().count() In other words: How do I exclude when 2 fields are equal? Am I doing it right? Is there any better way? -
Returning cleaned_data when overwriting clean() method in Django Model forms
I need to overwrite the clean() method in a Django Model form to perform additional uniqueness checks on the data entered. This page gives implementation details: https://docs.djangoproject.com/en/1.11/ref/forms/validation/ Copied here: def clean(self): cleaned_data = super(ContactForm, self).clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise forms.ValidationError( "Did not send for 'help' in the subject despite " "CC'ing yourself." ) However I'm confused why this method doesn't return cleaned_data at the end of the function? Surely that is the correct thing to do? -
Calling a class-based view of an app from another app in same project
I have this class based view: class Browse(APIView): ''' Browse associations ''' permission_classes = [TokenHasReadWriteScope] def get(self,request,format=None): reply={} status=200 try: filter_options={} name=request.query_params.get('name','').strip() if name: filter_options['name__icontains']=name associations=Association.objects.filter(**filter_options)values('id','name') page=request.query_params.get('page',1) paginator=Paginator(associations,20) data=paginator.page(page) except PageNotAnInteger: data=paginator.page(1) except EmptyPage: data=paginator.page(paginator.num_pages) except: status=400 reply['detail']=(_('ErrorProcessingRequest')) if status==200: reply['associations']=list(data) reply['total_num_of_pages']=paginator.num_pages reply['total_rows_found']=paginator.count return JsonResponse(reply,status=status) Now I have another app that is oriented towards internal users (different login and all) but I want to list the associations still. The above code is short and i don't mind pasting it there but just wondering if I can avoid DRY by calling the Browse from views.py of another app. Currently, I trie this from app 2: from app1.views import Browse b=Browse() #but I cant serialize it as it returns <app1.views.Browse object at 0x0000000006CE0E80> is not JSON serializable -
everse for 'results' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<pk>[0-9]+)/results/$']
I started on the generic views section of the Django tutorial on their website and i keep getting this error. I know this question has been asked before but these answer did not fix my issue. I was wondering could any see the error? I have removed imports to tidy the code. urls.py: app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Questions.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Questions template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Questions template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Questions, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args= (question.id,))) detail.html: <h1>{{ object.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question_id=object.id %}" method="post"> {% csrf_token %} {% for choice in object.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }} </label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> results.html: <h1>{{ question.question_text }}</h1> <ul> {% for choice in … -
Django with Unicorn and Nginx, creating gunicorn logs
I Launch my Django app in a docker container, using a startup script as per the below:- #!/bin/bash python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate /etc/init.d/celeryd start /etc/init.d/celerybeat start exec gunicorn itapp.wsgi -b 0.0.0.0:8000 Unicorn and ngnix every now and then give me a 502 error, so I went to look for logs and it looks by default gunicorn does not log any? im on version 19.7.1 so I added the to the exec guncicorn command: exec gunicorn itapp.wsgi -b 0.0.0.0:8000 --error-logfile /var/log/gunicorn/errors.log , --log-file /var/log/gunicorn/access.log Which I goy form the gunicorn documentation. however now Gunicorn fails to launch with the following error:- usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: , How can I create the gunicorn logs to debug these errors? Thanks -
What should I learn Django or MEAN considering I know Python for intermediate level? [on hold]
Being a college freshmen I don't have any prior knowledge to back-end or Front-end development. I know Python at intermediate level and in touch with it for past 1.5 years . Also considering the future scope what should I go for? I am a bit confused? Can you guys help me -
1.How to set lable to each widget in django_filters.DateFromToRangeFilter? 2.How can I change order in fields
How can I set lable 'Start date' to widget[0] and 'End Date' to widget[1] in DateFromToRangeFilter? class CasesFilter(django_filters.FilterSet): datelastupdate=DateTimeFromToRangeFilter() testtime=DateTimeFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'DD.MM.YYYY HH:SS'})) class Meta: model = ListOfCases fields=['id_test' , 'datelastupdate', 'testtime', 'active_flag', 'version' ] 2.Variables in 'fields' are displayed in a different order on the page. How can I change the order of variables? Tamplate: <div > <form action="" method="get" class="form-inline"> {{filter.form|crispy }} <div style="display:block; clear:both; margin-top:10px"> <input type="submit" value="Search" /> </div> </form> -
django 1.10 with non-ascii cache names
The problem actually raised from mezzanine comment form which stores the author's name in the response cache (as summarized below): set_cookie(response, "mezzanine-comment-name", post_data.get("name")) Which calls the django set_cookie function: response.set_cookie(name, value, expires=expires, secure=secure) So if the author's name contain non-ascii characters, a well known problem is raised by the server (I've tested it with nginx and also django local server): UnicodeEncodeError: 'ascii' codec can't encode characters in position ...: ordinal not in range(128) I've also tried to modify mezzanine source code and put .encode() after post_data.get("name") but there is an weird line in the first line of the response.set_cookie which revokes the encoding! value = force_str(value) -
Adding "Save as Draft" and preview feature in Django admin
How to add "save_as_draft" and "preview" option to my django project. I want to allow admin interface to save the blog posts as draft. and a preview button to preview how my blog post will look after publishing. I also tried integrating mezzannine with my django project. But there are not enough documentations for doing. In the FAQ of mezzannine documentations. They just written that users can easily integrate mezzannine with their django project. Is there a way i can customize the django admin interface? -
no encoder installed for (u'json',) from kombu
I think I am missing a step somewhere but I've been looking around and cant find it. When I run my celery task, I get thrown this error message no encoder installed for (u'json',) when I call get_task.delay(args). Am i suppose to have my own custom serialization? settings.py CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_TASK_SERIALIZER = 'json', CELERY_RESULT_SERIALIZER = 'json' I also tried get_task.apply_async((args), serializer='json'). This seems to hang. Nothing is running. I checked my workers, nothing shows up. -
Django lesson list with buttons
I want to display a list of lessons in django, that have a register or unregister button, depending on the users lesson-registrations. If a registration for the lesson exists, there is an unregister button. How can all the lessons be displayed with the right button? The models used are: class S_Lesson(models.Model): title = models.CharField(max_length=1000) description = models.CharField(max_length=4000) time_list = models.ManyToManyField(S_LessonTime) group_list = models.ManyToManyField(S_LessonGroup) def __str__(self): return self.title class S_LessonRegistration(models.Model): time = models.ForeignKey(S_LessonTime, on_delete=models.CASCADE, blank=True, null=True, default=1) group = models.ForeignKey(S_LessonGroup, on_delete=models.CASCADE, blank=True, null=True, default=1) lesson = models.ForeignKey(S_Lesson) def __str__(self): return str(self.lesson) + "(" + str(self.time) + "/" + str(self.group) + ")" class S_User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default="2") first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) lesson_registration_list = models.ManyToManyField(S_LessonRegistration, null=True) def __str__(self): return self.last_name + " " + self.first_name My views.py: @login_required(login_url='u:login') def LessonDetailsView(request, lesson_id): lesson_object = get_object_or_404(S_Lesson, pk=lesson_id) s_user = get_object_or_404(S_User, user=request.user.pk) return render(request, 'u/lesson-details.html', {'lesson_object': lesson_object, 's_user': s_user}) Template: <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th>Lessons</th> <th>&nbsp</th> </tr> </thead> <tbody> {% for lesson_item in class_object.lesson_list.all %} {% for lesson_registration in s_user.lesson_registration_list.all %} {% lesson_is_registered = False %} {% if lesson_registration.lesson.id == lesson_item.id %} {% lesson_is_registered = True %} {% if lesson_is_registered == True %} <tr> <td> <form id="unregister_{{ … -
Get data from model A to model B after filling the form of model B in django
I have following two models. What I want is Whenever I fill the data in model Book i.e its name (like name of Book says Java) It will automatically be saved also in Contributor model under field "name". Also I can manually be able to fill the "name" field in Contributor model in django Admin class Book(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Contributor(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name Data in model Book After Filling Data in model Book I want Data in model Contributor as this -
Render hyperlinks in django-wagtail template
I have a little problem, I created this model, and now I need a template for render the "related links section" in the bottom of a "post page" . class PostPageRelatedLink(Orderable): page = ParentalKey(PostPage, related_name='related_links') name = models.CharField(max_length=255) url = models.URLField() panels =[ FieldPanel('name'), FieldPanel('url'), ] I have no idea how to write html for that :) I wrote this, but obviously doesn't work <div class='related_links'> <h3>Related Links</h3> {% for item in page.related_links.all %} <a href='related_links'>{{ page.related_links.url }}</a> {% endfor %} </div> What is the right way to do this? Thanks for help! -
No exception raised when saving an empty field with null=False - Django
I have the following model: class User(models.Model): email = models.EmailField(max_length=254, null=False, unique=True) referral_code = models.CharField(max_length=10, null=False, unique=True) And used the Django shell to save a user instance with referral_code undefined: u = User(email="test@example.com") u.save() This did not raise an exception. My understanding was that null=False would require referral_code to be set - Is this not the case? How would I achieve that behaviour? -
auth.user not resolved error django
i added one field to my model and attached it to django user model through foreignkey. My model is, from django.db import models from django.contrib.auth.models import User # Create your models here. class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField() Username = models.ForeignKey(User,default=1) but while migration it is giving me error as 'valuerror: related model 'auth.user' cannot be resolved.' what does that mean and how to resolve that? I tried many things but did not work. Thanks in advance.