Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve and update multiple models at once in Django
I'm new to django and im currently using version 1.8 but I have two models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT, null=True, blank=True) call_id = models.CharField(blank=True, max_length=10) checking_out = models.BooleanField(default=False) available = models.BooleanField(default=True) ... class Person(models.Model): ... books_allowed = models.PositiveSmallIntegerField() books_out = models.PositiveSmallIntegerField(default=0, blank=True) day_limit = models.PositiveSmallIntegerField() ... I am going to be having a checkout page that displays a persons name and has input fields depending on the number of books they are allowed to have and the number of books they already have out so if person A can only check out 6 books and he already has 2 books to his name, there will be 4 fields but not all 4 fields have to be filled out because person A might only check out 2 books or 1 or etc. What I am having a hard time figuring out is how can I create the form, would I use model forms or is there another way to build a form that does not require all fields filled because keep in mind person X doesn't have to check out his max amount of books allowed all at once. Once I do … -
Django pgettext doesn't create context
in my Django (2.0.2) running in Python 3.6.3 I've created some Models as usual. To be able to work with the admin panel in the user's language, I've set the model's and model field's verbose_names to _('context','verbose_name') where _ aliases to pgettext_lazy. When running "makemessages -l de" it creates the django.po file as expected, containing all my strings. Different from my expectations, the blocks look like #: app/models.py:123 msgid "context" msgstr "" instead of #: app/models.py:123 msgctxt "context" msgid "verbose_name" msgst "" What could I possibly do wrong? All strings translated with gettext_lazy work fine. -
Which is better for production? Flask-Restful+SqlAlchemy vs Django-Rest
I have few months experience in Python Backend and am comfortable with Flask-Restful. I am creating a production app which is going to have a few thousand users. Should I go with Django-rest because it is prepackaged or stick with Flask-Restful with SQLAlchemy? -
Where to write AWS signing code
I'm trying to validate my AWS keys for S3 storage for my Django project. So I've found this tutorial from the offical site. It shows various Python code but it doesn't say where to write it? What file do I put this code in? -
Django group by one column but display multiple
I have 40 results of posts in Django. POST: id, title, website_id WEBSITE: id, name And these posts belong to 7 websites. I would like to group by website_id so only 1 post will be displayed per a website. I've tried this: post_list.values('website_id').annotate(Count('website_id')) or post_list.values('id', 'title').values('website_id').annotate(Count('website_id')) It will display 7 results, but only 2 columns: "website_id" and "website_id__count" I would like to display also other columns: post.id, post.title, post.website_id. I've tried different configurations, such as: post_list.values('id', 'title', 'website_id').annotate(Count('website_id')) Now, it displays all columns, but 40 results instead of 7, because it groups by post.id instead of post.website_id. Do you know how to display all columns but only 7 results, instead of 40? Thanks. -
How do I create pagination and search based on related models?
So based on the view below, that is working perfectly, I also want to change it that I can create pagination and search also for courses that belong to a specific faculty. Models hierarchy is this: faculties > departments > studies > courses. @login_required def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'courses2': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) -
UNIQUE constraint failed: auth_profile.user_id Django Allauth
I have a create_or_update_user_profile methods to the User model, whenever a save event occurs, but I added a new method set_initial_user_names to save a url, then now it shows me an error IntegrityError at /accounts/social/signup/ UNIQUE constraint failed: auth_profile.user_id class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=170, blank=True) avatar_url = models.CharField(max_length=256, blank=True) facebook_url = models.CharField(max_length=40, blank=True) twitter_url = models.CharField(max_length=40, blank=True) instagram_url = models.CharField(max_length=40, blank=True) web_url = models.CharField(max_length=40, blank=True) class Meta(): db_table = 'auth_profile' def __str__(self): return self.user.username @receiver(user_signed_up) def set_initial_user_names(request, user, sociallogin=None, **kwargs): preferred_avatar_size_pixels = 256 picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format( hashlib.md5(user.email.encode('UTF-8')).hexdigest(), preferred_avatar_size_pixels ) if sociallogin: if sociallogin.account.provider == 'twitter': name = sociallogin.account.extra_data['name'] user.first_name = name.split()[0] user.last_name = name.split()[1] if sociallogin.account.provider == 'facebook': user.first_name = sociallogin.account.extra_data['first_name'] user.last_name = sociallogin.account.extra_data['last_name'] picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format( sociallogin.account.uid, preferred_avatar_size_pixels) if sociallogin.account.provider == 'google': user.first_name = sociallogin.account.extra_data['given_name'] user.last_name = sociallogin.account.extra_data['family_name'] picture_url = sociallogin.account.extra_data['picture'] profile = UserProfile(user=user, avatar_url=picture_url) profile.save() @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() IntegrityError at /accounts/social/signup/ UNIQUE constraint failed: auth_profile.user_id -
How to romove models in django 1.11?
I started learning django recently. I just created a music app in my project. I added a album colum in models.py. At first I set that to null=True. But later I removed that. After couple of times when I tried to make migration it shows an error like below. I tried by deleting that attribute but than another attribute 'artist' shows same problem. I can't understand why? And how to fix that? **You are trying to add a non-nullable field 'album' to song without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py** -
How do I add a link to a Custom Boolean Field and pass parameters using Django_Tables2
So I've been having lots of fun with Django_Tables2 and I have it all working really nicely which is great. My table renders with a series of columns from my database which are booleans. These are columns such as 'Completed' etc. Instead of having True and False I have created a custom definition for my boolean fields which renders glyphicons-ok and glyphicons-remove as appropriate. See code below class BootstrapBooleanColumn(BooleanColumn): def __init__(self, null=False, **kwargs): if null: kwargs["empty_values"]=() super(BooleanColumn, self).__init__(**kwargs) def render(self, value): value = bool(value) html = "<span %s></span>" class_name = "glyphicon glyphicon-remove" if value: class_name = "glyphicon glyphicon-ok" attrs={'class': class_name} attrs.update(self.attrs.get('span', {})) return mark_safe(html % (AttributeDict(attrs).as_html())) My columns are therefore coded accordingly as follows: completed = BootstrapBooleanColumn(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Completed'}}) However now I'd like to be able to click on one of the icons and have it toggle and update my database accordingly (ie switch from False to True and vice versa.) but I can't seem to be able to pass the parameters and I'm getting myself into a knot. I tried wrapping the in an anchor def render(self, value): value = bool(value) html = "<a href='/tasks/toggle/3'><span %s></span></a>" which triggers my url with a hard coded id of '3' but I … -
API endpoint as a django model
I want an API endpoint to be linked to a model that supports relationships. For example, if I have an endpoint http://api-url/users which gives all users, I want to create a model 'Order' with a field 'user' which is a ForiegnKey to a User model linked to the API. -
Attributes in django form model
hi i have django form model and i to want add my custom class for it but still i getting error: TypeError: init() got an unexpected keyword argument 'attrs' My django code: class ContactForm(forms.ModelForm): class Meta: model = ContactFormModel fields = ('name', 'email', 'phoneNumber', 'message',) widgets = { 'name': CharField(attrs={'class': 'myfieldclass'}), } Thanks for your helps. -
Django Model Form clean method not being called
I have used a Django model form to create HackathonTeam instances. The issue I am facing here is that custom clean method that I have used is not being called. All the other default validations are happening correctly. # models.py class HackathonTeam(models.Model): name = models.CharField(max_length=30) leader = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='leader_teams') hackathon = models.ForeignKey(Hackathon, on_delete=models.CASCADE, related_name='hack_teams') vacancies = models.PositiveIntegerField(default=0) current_members = models.ManyToManyField(CustomUser, related_name='member_teams') skills_required = models.ManyToManyField(Skill, related_name='hack_requirements') cutoff_date = models.DateTimeField(null=True, blank=True) # Someone may not wish to have a cut-off date closed = models.BooleanField(default=False) # forms.py ######## class HackathonTeamForm(forms.ModelForm): class Meta: model = HackathonTeam exclude = ['leader', 'current_members', 'closed'] def clean(self): print("Inside clean") cleaned_data = super(HackathonTeamForm, self).clean() print(cleaned_data) if HackathonTeam.objects.filter(hackathon=cleaned_data.get("hackathon"), name=cleaned_data.get("name")).exists(): print(1) raise forms.ValidationError("A team with the same name already exists.") return cleaned_data # views.py ######### @login_required(login_url='users:login') def add_hackathon_team(request): if request.method == 'POST': form = HackathonTeamForm(request.POST) if form.is_valid(): cd = form.clean() print(cd) print("Data is valid") # form.save() team = form.save(commit=False) team.leader = request.user team.save() return redirect('users:view_hackathon_team', pk=team.id) else: form = HackathonTeamForm() return render(request, 'users/add_hackathon_team.html', {'form': form}) The print statement in the view is being printed and new Teams are created as well. The only issue is that the clean method is not called and duplicate Teams can be created as well. -
How to upgrade to Django 2.0
I've been traying to upgrade my django versión and I've coudnt. xxx@yyyyyy:~# python Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 11, 10, u'final', 0) xxxx@yyyyyyy:~# pip install -U Django The directory '/home/user/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/user/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) xxxx@yyyyyy:~# pip --no-cache-dir install -U Django Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) How it coud be up-to-date my django version if enter code hereit is not 2.0 it is (1, 11, 10, u'final', 0) And If I do an ls -s to know the files owners: xxxx@yyyyyyy:~# ls -s /home/gechichure/.cache/pip … -
Django queryset ProgrammingError: column does not exist
I'm facing a big issue with django. I'm trying to save object containing foreignKeys and 'ManyToMany` but i always get this error ProgrammingError: column [columnName] does not exist I've made serveral times all migrations but it doesn't works. I have no problem when i work with models that does not contain foreign keys. I have tried to delete the migration folder. It's seems my database doesn't want to update fields. I need to force it to create these column but i don't have any idea. class Post(models.Model): post_id = models.CharField(max_length=100,default="") title = models.CharField(max_length=100,default="") content = models.TextField(default="") author = models.ForeignKey(Users, default=None, on_delete=models.CASCADE) comments = models.ManyToManyField(Replies) numberComments = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(null=True) def __str__(self): return self.post_id when i'm trying to retrieve this i have : ProgrammingError: column numberComments does not exist As i said before i made makemigrations and migrate, i even deleted the migration folder. Any idea ? -
Attaching `ng-model` to Select widget gives "?undefined:undefined?" `option` value attribute
I have a form in Django. Here's my forms.py. The option values are stored in variable subPlansList, a list of tuples. class RegisterForm(UserCreationForm): subPlan= forms.CharField(label=_("Choose plan"), widget=forms.Select(choices=subPlansList, attrs={"id":anIDVariableSetSomewhereElse, "class":"custom-select", "ng-model":"reg.subs"})) And here's register.html... <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript"> var app= angular.module("LoginRegApp",[]); app.config(function($interpolateProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); }); app.controller("LoginRegCtrl",function($scope,$http){ }); </script> <form id="register-form" name="regForm" method="post"> {% csrf_token %} {% for field in registration_form %} <p>{{ field }}</p> {% endfor %} <button ng-model="reg.btn">Register</button> </form> But here's what the input looks like when my browser loads it. <select name="plan" ng-model="reg.subs"> <option value="? undefined:undefined ?"></option> <option value="default">Which plan?</option> <option value="plan_1">$10 a month</option> <option value="plan_2">$5 a week</option> </select> How do I stop angular from adding that extra option tag at the start of the select tag? -
Django poll app modification
I am trying to write a Django App for my company website. I have essentially started with the polls app tutorial and am looking to make a number of modifications to this to create my own app that will be used on my website. Firstly I would like to start with a homepage with a button on to click through to the polls app. Secondly I would like to click straight through to question 1 with the radio buttons. Thirdly once the user has clicked "vote" I would like to go straight to the second question. Thanks for your help I hope this is simple to understand. -
How to make Python property object human-readable - Rendering it through Django templates
I have this property that should display the total price for each product, and I call it in my views and render it. On the rendered page, it just shows up as <property object at 0x0000023CDA655048> How am I supposed to make this human-readable? I know this is really simple, and I can't figure out how. I tried the following within my cart.py file that the class and property function belongs to: def __str__(self): return self.total_price @property def total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) I called it in my views.py like: def get_cart(request): cart = Cart(request) total = Cart.total_price return render(request, 'buylist/cart.html', {'cart':cart, 'total':total}) within a for loop, I rendered it for each item in my cart.html and called it like: Total: {{total}} I am expecting to see the human-readable total price for each product on each product's line, but instead I'm just seeing the actual property object. I'm sure it's something really simple I'm missing haha, but I've been stuck on this for a minute! If you could help, that would be awesome. -
Is django way of prefetching many to many related objects more efficient than sql join?
Django docs state that “to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one. prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. “ The part that confuses me is ‘to avoid the much larger result set’. But why is it should be avoided and doesn’t prefetch related queries it anyway just in a separate query thus creating even more overhead? -
ayuda con el cli de heroku por favooor [on hold]
Cada vez que intento ejecutar una acción en el cli de heroku como por ejemplo "heroku login" o "git push heroku master" me salta el siguiente error:UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate. Ya he probado a reinstalar el cli y nada. Por favor AYUDA.(Uso Heroku con Django) -
Display Multiple Queryset in List View
i'm trying to display multiple queryset with multiple models as a timeline and sort em by time instead of displaying one queryset after the other my current code looks like that : <div class="user-info col-md-8"> {% for obj in user.marks_set.all %} <p>{{ obj.module }}</p> <p>{{ obj.grade }}</p> <p>{{ obj.date }}</p> {% endfor %} {% for obj in events %} {{ obj.content }} {% endfor %} </div> all models have date field , i'm trying to display everything and order em by date instead of displaying all marks and after that all events -
Adding SSL To My Django App Running In Daemon Mode With Mod_WSGI
I have done some research and cannot find a solution that works for me... My current apache2.conf file: <VirtualHost xxx.xx.xxx.xxx:8080> ServerName website.com ServerAlias www.website.com ServerAdmin admin@website.com DocumentRoot /home/USER/web/website.com/djagno_project/app/ ScriptAlias /cgi-bin/ /home/web/cgi-bin/ Alias /vstats/ /home/USER/web/website.com/stats/ Alias /error/ /home/USER/web/website.com/document_errors/ #SuexecUserGroup USER USER CustomLog /var/log/apache2/domains/website.com.bytes bytes CustomLog /var/log/apache2/domains/website.com.log combined ErrorLog /var/log/apache2/domains/website.com.error.log <Directory /home/USER/web/website.com/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/USER/web/website.com/django_project/app:/home/USER/tmp php_admin_value upload_tmp_dir /home/USER/tmp php_admin_value session.save_path /home/USER/tmp </Directory> <Directory /home/USER/web/website.com/stats> AllowOverride All </Directory> <IfModule mod_ruid2.c> RMode config RUidGid USER USER RGroups www-data </IfModule> <IfModule itk.c> AssignUserID USER USER </IfModule> IncludeOptional /home/USER/conf/web/apache2.website.com.conf* Alias /static /home/USER/web/website.com/django_project/app/static <Directory /home/USER/web/website.com/django_project/app/static> Require all granted </Directory> <Directory /home/USER/web/website.com/django_project/project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/USER/web/website.com/django_project/app/> AllowOverride All Options +Includes </Directory> LoadModule wsgi_module "/usr/local/lib/python2.7/dist-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIScriptAlias / /home/USER/web/website.com/django_project/project/wsgi.py WSGIDaemonProcess www.website.com socket-user=USER group=USER processes=2 threads=25 WSGIProcessGroup www.website.com WSGIApplicationGroup USER LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined SSLEngine on SSLCertificateFile /home/USER/conf/web/ssl.website.com.crt SSLCertificateKeyFile /home/USER/conf/web/ssl.website.com.key SSLCACertificateFile /home/USER/conf/web/ssl.website.com.crt RewriteEngine on RewriteCond %{HTTP_HOST} ^website\.com RewriteRule ^(.*)$ https://www.website.com$1 [R=permanent,L] RewriteCond %{HTTP_HOST} ^www\.website\.com RewriteRule ^(.*)$ https://www.website.com$1 [R=permanent,L] </VirtualHost> WSGIPythonHome "/usr/local/.virtualenvs/PROJECT" Everything was working fine before I started to use SSL Before I added SSL, my static files were being loaded … -
Django foreign keys are not saving properly
So I am trying to create a study with multiple meals. Whenever I save the meals in the post method, the last meal is saved and also overrides the previous two with its own data. models.py class MotionStudyInstance(models.Model): # ###############ADD MEAL INFORMATION####################### meal_one = models.ForeignKey(Meal, related_name='first_meal', on_delete=models.CASCADE, null=True, blank=True) meal_two = models.ForeignKey(Meal, related_name='second_meal', on_delete=models.CASCADE, null=True, blank=True) meal_three = models.ForeignKey(Meal, related_name='third_meal', on_delete=models.CASCADE, null=True, blank=True) forms.py class MealForm(forms.ModelForm): class Meta: model = Meal exclude = ('general_info',) class MotionStudyInstanceForm(forms.ModelForm): class Meta: exclude = ('meal_one', 'meal_two', 'meal_three',) views.py class MotionStudyInstanceFormView(LoginRequiredMixin, View): form_class_seven = MealForm form_class_eight = MealForm form_class_nine = MealForm ...is form valid stuff works... motion_study_instance_one.meal_one = meal_one motion_study_instance_one.meal_two = meal_one motion_study_instance_one.meal_three = meal_three when I assign these variables, the third meal is overriding the first two. Am I missing something? How can this be fixed? The data is being saved and I am getting no errors (not all code is posted), but things just are not saving properly. Thanks for any help! -
Unable to save related object
I have my models like this. class Subscriber(models.Model): skillset = models.TextField(verbose_name='Skill Set') slug = models.SlugField(unique=True, default='') class SoloDeveloper(models.Model): first_name = models.CharField(max_length=30, verbose_name='First Name') last_name = models.CharField(max_length=30, verbose_name='Last Name') subscriber = models.OneToOneField(Subscriber, related_name='solo_dev', on_delete=models.CASCADE) I am trying to save the solo developer and assign it to the one to one field of the Subscriber. def solo_dev_edit(request, slug): subscriber = Subscriber.objects.get(slug=slug) subscriber_form = SubscriberForm() solo_dev_form = SoloDevForm() if request.method == 'POST': subscriber_form = SubscriberForm(data=request.POST, instance=subscriber) solo_dev_form = SoloDevForm(data=request.POST) if all[subscriber_form.is_valid(), solo_dev_form.is_valid()]: sub = subscriber_form.save(commit=False) solo_dev = solo_dev_form.save() sub.solo_dev = solo_dev sub.save() return redirect('solo_dev_view', slug=subscriber.slug) else: subscriber_form = SubscriberForm() solo_dev_form = SoloDevForm() return render(request, 'main/solo_dev_edit.html', { 'sub_fm': subscriber_form, 'solo_dev_fm': solo_dev_form, }) This fails saying null value in column "subscriber_id" violates not-null constraint DETAIL: Failing row contains (9, john, doe, null). What am I doing wrong? -
django routes error adding a new url
I'm coming from Rails into Django and i'm struggling with the URL patterns. I'm trying to follow the django filters tutorial for a simple search form. I have my search working correctly, but when I add a new URL I get maximum recrusion depth exceeded, can't import views, or search module not found. The error will vary depending on how I My folder structure is the following: filters mysite - project folder search - app in my project folder I have the following urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), url(r'^mysite/', include('mysite.urls')), ] In my search app I have the following urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^result/$', views.result, name='result'), ] After the user searches for a product and selects it in the results, the submit in the template should take them to the url result for the result of the single product selected. -
django.channels async consumer does not appear to execute asynchronously
I have added django.channels to a django project in order to support long running processes that notify users of progress via websockets. Everything appears to work fine except for the fact that the implementation of the long running process doesn't seem to respond asynchronously. For testing I have created an AsyncConsumer that recognizes two types of messages 'run' and 'isBusy'. The 'run' message handler sets a 'busy flag' sends back a 'process is running' message, waits asynchronously for 20 seconds resets the 'busy flag' and then sends back a 'process complete message' The 'isBusy' message returns a message with the status of the busy flag. My expectation is that if I send a run message I will receive immediately a 'process is running' message back and after 20 seconds I will receive a 'process complete' message. This works as expected. I also expect that if I send a 'isBusy' message I will receive immediately a response with the state of the flag. The observed behaviour is as follows: a message 'run' is sent (from the client) a message 'process is running' is immediately received a message 'isBusy' is sent (from the client) the message reaches the web socket listener on …