Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Python in web to recommend products in real time?
I wanted to know the step by step process for making this happen. I wanted to attach unique ID to user in a cookie and then store his interaction in a database. Then when he visits again he would be shown recommended content in a HTML DIV. How should i do this? P.S:I am basically new to python. -
Adding user to group on save
Hello, I'm using Django 1.9. Trying to add a user to group on creation or save. Using either user.groups or groups.user_set.add don't work, mix and match with pre- and post-save below. These answers aren't working for me, and so this isn't a dupe: Adding user to group on creation in Django Adding a user to a group in django Add users to groups in Django I have tried both methods in both pre- and post-save handlers. @receiver(pre_save, sender=User) def user_presave_handler(sender, instance, **kwargs): if instance.is_staff and not instance.is_superuser: # Grant all permissions try: instance.groups.add(Group.objects.get(name='staff_user')) except Group.DoesNotExist: pass @receiver(post_save, sender=User) def user_postsave_handler(sender, instance, **kwargs): if instance.is_staff and not instance.is_superuser: try: g = Group.objects.get(name='staff_user') except Group.DoesNotExist: pass else: g.user_set.add(instance) g.save() You can mix and match which method is used where, I have tried it. I don't use more than one method in testing. After hitting the save button on user admin page, the user is not shown as in the group. I double-checked that the handlers are getting called, user logic is correct, etc. Is there something I'm doing wrong, or something that has changed in 1.9 to break the old methods? Thanks! -
Created by user period jobs Django
I have a small website which plots Google Calendar data for registered user. I want to add a feature: user should be able to create mailing schedule (site will generate pictures and send them on email on chosen time). Task: user should be able to create/modify periodic jobs. Question: what is the best way to do this? I've checked Celery (brokers made me think it's too much for such a small project), things like django-cron doesn't provide jobs created by user as far as I see. -
How can I set a FK to be optional in Django
I'm trying to set that a Foreign Key field is optional. I have already added "null=True, blank=True" to the "group" field in my models.py file but it's also required. Here is my models.py code: class Record(Timestampable): uuid = CharField(max_length=256, primary_key=True, editable=False) code = CharField(max_length=32, blank=True) name = CharField(max_length=256, blank=True) group = ForeignKey('self', null=True, blank=True, related_name='members') Here is my serializers.py code: class RecordSerializer(ModelSerializer): class Meta: model = Record fields = ('uuid', 'code', 'name', 'group') -
CSRF issue when running settings_de
I am running Django 1.9. on MAC I have 2 settings files settings.py (for production) and settings_dev.py (for dev) On my machine I run the project with ./manage.py runserver --settings=molvero.settings_dev The problem is when I submit a form I get the Error CSRF verification failed. Request aborted. This start happening from the time the 2 settings files got very different. For some reason when I run ./manage.py runserver --settings=molvero.settings_dev when there is a form submission Django gets settings.py. I am sure that it is happening like that because I copy paste my DEV file in settings.py and everything runs good. Any Idea how I can fix that issue ? -
Docker-compose with django could not translate host name "db" to address: Name or service not known
I have currently a system built with docker-compose, it creates a Django application. Up until now I've used a database inside a container (postgresql) in my testing build. Now I've changed the database from this container to an RDS instance in AWS. Using Pg_dump I have recreated the database inside RDS and changed the settings.py, everything was supposedly normal. I have accessed the data from the database inside my webapp without any problems. Everything was ok until I had to make a migration. Without the database container the Django container gives me this message: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known My Docker-compose.yml file before the changes: version: '2' services: db: image: postgres:9.5 restart: always environment: POSTGRES_USER: testing POSTGRES_PASSWORD: tests POSTGRES_DB: test volumes: - /dbdata:/var/lib/postgresql/data django: build: ./django command: gunicorn contactto.wsgi:application -b 0.0.0.0:8000 restart: always volumes: - ./django:/usr/src/app - ./django/static:/usr/src/app/contactto/static ports: - "8000:8000" depends_on: - db Now after the changes: version: '2' services: django: build: ./django command: gunicorn contactto.wsgi:application -b 0.0.0.0:8000 restart: always volumes: - ./django:/usr/src/app - ./django/static:/usr/src/app/contactto/static ports: - "8000:8000" And the DATABASES from settings.py . Before: DATABASES = { 'default': { 'ENGINE': 'tenant_schemas.postgresql_backend', 'NAME': 'testing', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'db', … -
django oscar doesnt pick up customazations
I've forked address app and created a new models and forms.py file... while overriding base AbstractAddress model cause I didn't need the phone number mix in and a couple of other options problem is that oscar only picks up the model file customization and gives the following error while loading the wrong form class from oscar raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (postcode, country, line4, line2, line3, line1) specified for UserAddress -
Show title of model items on admin page
I have a model Article, how to how article title in admin panel 1 -
Django - Writing unit tests with mocks
I started working on a Django project recently. To start off with, I read the book on TDD with Python and the official documentation (for tests). And a few more blogs as well. One thing I notice is, they write tests that access the database models. Consider the following snippet from here def test_home_page_can_save_a_POST_request(self): request = HttpRequest() request.method = 'POST' request.POST['item_text'] = 'A new list item' response = home_page(request) self.assertEqual(Item.objects.count(), 1) new_item = Item.objects.first() self.assertEqual(new_item.text, 'A new list item') The test asserts whether the number of Item objects is 1. So the test actually adds and retrieves data from the database. Wouldn't that make the test slow? If the tests are parallelized, this test case may fail if there is another test which adds an Item object, right? How about patching methods / objects? The above snippet can be refactored like this @patch('my_app.views.Item') def test_home_page_can_save_a_POST_request(self, mock_item): request = HttpRequest() request.method = POST request.POST['item_text'] = 'A new list item' response = home_page(request) self.assertTrue(Item.objects.create.called) I am new to Django and I am not familiar with the practices. The tutorials I visited wrote tests that talk to database. I would like to know, whether that is the convention for testing in Django projects. … -
Adding a Non-Model Form in Django Admin
I am trying to add a non-model form in django admin interface and am not able to find any particular way to do it. This form would do some processing and change some data in the DB. But this is not related to a particular Model and should stand out. This form should not be available for the user to use. One thing I can do is add the form to the general view and prohibit using permissions but I was thinking since django admin interface already exists, it would be better to add that to the django admin interface. Is this possible to do in Django? -
Django - Optimize queries
I have the following model. class Car(models.Model): owner = models.ForeignKey('Driver') class Country(models.Model) name = models.CharField(max_length=255) class Driver(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() country = models.ForeignKey('Country') I want to select the name of drivers owning a car. Car.objects.all().values('owner__name') Do I need to use select_related() method, to avoid a join for each object, or it is redundant because implicit with values() method? Car.objects.all().select_related('owner').values('owner__name') In the same way, I want, this time, the name of countries with drivers owning a car. Which one is the best? Car.objects.all().values('owner__country__name') Car.objects.all().select_related('owner', 'country').values('owner__country__name') Car.objects.all().select_related('owner__country').values('owner__country__name') Then, I want to select all drivers aged over 50 years and having a car. Is there a way to do this in a single optimized query? owners = Car.objects.all().values('owner') Driver.objects.filter(id__in=owners, age__gte=50) -
Two Django Apps on one server
So I have been tasked with getting two apps running on one server, which I have done but we think I have misconfigured it as the URL is wrong to access the App and the app has weird errors that shouldn't occur. (Foo/Bar being the initial project already setup on the site and QMS being the app I have created and am trying to add). Possibly worth noting, I have tried other formats such as declaring both WSGIScriptAlias' in the first virtual host, this works however gives me the same URL format. The URLs are aimed to look like: mysite.com/foo/bar & mysite.com/QMS However the current URLS are: mysite.com/foo/bar & mysite.com/foo/QMS The error we are facing is a 'ProgrammingError' from Django where it believes that our DBs do not exist but we have proven they do and we have toyed with the migrations. Anyways on to the relevant config. So I have it setup currently like this: <VirtualHost _default_:443> ServerName web.mysite.com ServerAlias www.mysite.com WSGIScriptAlias /foo /var/www/html/foo/bar/wsgi.py DocumentRoot /var/www/html <Directory /var/www/html/foo/mediaroot> Require all granted </Directory> </VirtualHost> <VirtualHost _default_:443> ServerName web.mysite.com ServerAlias www.mysite.com WSGIScriptAlias /qms /var/www/html/qms/QMS/wsgi.py Alias /static /var/www/html/qms/staticroot/ <Directory /var/www/html/qms> Order allow,deny Allow from all </Directory> </VirtualHost> Thank you for reading and … -
Git- detached HEAD on server, inconsistencies in live/ local website & who can access the website
I am currently having some issues with a Django application that I am developing. The setup of the application is: I develop new features/ fix bugs on my local machine, using Git to manage version control. Whenever I am happy that a bug has been fixed, or that a new feature is working correctly, I merge the branch on which I have been developing with my local master, then push master to the server, pull it on the server, & restart the server. After pushing some changes to the server yesterday, I tested the changes that I had made, and everything appeared to be working correctly. However, when I got in this morning, I found that I was unable to browse to the live version of the website, as I got an error message stating that global name 'user' is not defined, but everyone else in the office is able to access the live version via the same URL. Having spent a while investigating why I am not able to access the website, it appears that the issue I am having is to do with the Google Calendars API, which I started trying to add to the site on a … -
How to add data from input (form) and then save it and view it in template in Django
This is what I did so far: urls.py #1 go to views and execute insert_user function urlpatterns = [ url(r'^insert_user/', views.insert_user, name='insert_user'), # first executed url(r'^register_user/', views.register_user, name='register_user'),# second ] views.py #2 give user request from folder loginsys, insert_user.html page def insert_user(request): return render(request, 'loginsys/insert_user.html') template/loginsys #3 form html format where user inserts data <form method="POST" action="/register_user/"> <input type="text" name="userID" placeholder="userID (4 characters)" value="" maxlength="4"> {% csrf_token %} <input type="text" name="password" placeholder="password (8 characters)" value="" maxlength="8"> <button type="submit">Add user</button> </form> Here user sends "userID" and "password" using "POST" method to django to url "/register_user/" second executed in urls.py then: views.py #4 register_user function is executed def register_user(request): user = Users() user.userID = request.POST.get('userID', '') user.password = request.POST.get('password', '') user_saved = user.save() user_showHTML = user.objects.get(pk=user_saved.pk) return render(request, 'loginsys/insert_user_succes.html', { 'userID': user_showHTML.userID, 'password': user_showHTML.password}) # probably nonsense :) Up I tried to save user request into models.py class and (last two lines) send it back to browser.. I'm stuck.. I saw some examples which included "forms.py" file but my app doesn't need that much complexity. models.py class Users(models.Model): userID = models.CharField(max_length=4) password = models.CharField(max_length=8) What I want to do is to add data to models.py, view it and check if userID and … -
Django: sorl-thumbnail cache file is not deleted in production environment
I use django-cleanup, sorl-thumbnail in my Django project. I have a model like this: from sorl.thumbnail import ImageField class Variation(BaseModel): image = ImageField(upload_to=draft_img_upload_location) And I use signal for sorl-thumbnail like this (recommanded by https://github.com/un1t/django-cleanup): from django_cleanup.signals import cleanup_pre_delete def sorl_delete(**kwargs): from sorl.thumbnail import delete delete(kwargs['file']) cleanup_pre_delete.connect(sorl_delete) So, In local environment, belows work: 1. When I delete Variation model in ADMIN PAGE, it deletes BOTH image file and image cache(created by sorl-thumbnail). 2. When I change just image file with other image in ADMIN PAGE, it delete BOTH 'prior image file' and 'prior image cache file(created by sorl-thumbnail)'. In production environment, I used AWS S3 and cloudfront for managing static and media file. So all sorl-thumbnail cache image files are stored in S3. But whenever I changed the image file with other image file in ADMIN PAGE, the prior image cache file(created by sorl-thumbnail) still remained. Lets say that sorl-thumbnail image url is https://example.cloudfront.net/cache/da/75/abcdefg_i_am_cached_image.jpg (from Google development tool). In this case, there were two image files exist in S3: abcdefg.jpg and /da/75/abcdefg_i_am_cached_image.jpg I changed abcdefg.jpg with the other image. Then, it completely deleted abcdefg.jpg in S3 storage. Now, I accessed https://example.cloudfront.net/cache/da/75/abcdefg_i_am_cached_image.jpg in my browser and guess what! It showed this sorl-thumbnail … -
Django not finding installed apps
Trying to dump data from django getting this issue, when I try to check app (which installed) in shell it's present. [kbuzz@wf-45-33-126-168 kb]$ python2.7 manage.py dumpdata > dump.json System check identified some issues: WARNINGS: ?: (1_6.W001) Some project unittests may not execute as expected. HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information. CommandError: Unable to serialize database: cannot import name simplejson [kbuzz@wf-45-33-126-168 kb]$ python2.7 Python 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import simplejson >>> -
Is it possible to merge a Model/Form validator in Django-Rest-Framework?
I've noticed that Django form and model validators should raise a django.core.exceptions.ValidationError, which is an immediate subclass of Exception. In DRF, however, my validator is expected to raise rest_framework.exceptions.ValidationError, which is not a descendant of Django's (it derives from rest_framework.exceptions.APIException(Exception)). Keeping myself DRY, how can I write a validator once, and use it in both, say, Django forms and a DRF serializer? Here is a related question where DRF does not catch a Django core ValidationError -
Easy way to set on_delete across entire application
I've been using the -Wd argument for Python and discovered tons of changes I need to make in order to prepare my upgrade to Django 2.0 python -Wd manage.py runserver The main thing is that on_delete is due to become a required argument. RemovedInDjango20Warning: on_delete will be a required arg for ForeignKey in Django 2.0. Set it to models.CASCADE on models and in existing migrations if you want to maintain the current default behavior. See https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.on_delete Is there an easy regex (or way) I can use to put on_delete into all of my foreign keys? -
How to combine a Django view with a form
It should be a common situation, but I cannot find the right approach in the Django documentation or in numerous Django-related tutorials on the internet. So probably I just don't know what to look for, or there is no special approach. I have just started with Django, so definitely lack a lot of knowledge but I am also looking for the best practices, not just workarounds. I have a view which displays a photo. So something like this in urls.py: app_name = 'photos' urlpatterns = [url(r'^(?P<photo_id>\d+?)', views.single_photo_page, name="single-photo"),] In views.py: @login_required def single_photo_page(request, photo_id: str): ... return render(request, 'photos/single_photo.html', {'photo': photo}) Inside single_photo.html, I render the photo details, including comments, and also manually create a form to accept new comments: <form action="{% url 'photos:single-photo' photo.id %}" method="post"> {% csrf_token %} <label for="comment-body">Add comment</label><br /> <textarea id="comment-body"></textarea> <input type="submit" value="Save" /> </form> Finally, inside single_photo_page(), I process the form input which I get via request.POST[comment-body] and return errors using django.contrib.messages. This approach works fine, but means that I do manually the stuff for which Django form functionality is designed. I couldn't find a way to embed a form into a view. -
Securely POST a request without login in django
I am developing a django server as a backend to an iOS app. Until now, I've been creating new users through a registration page through the browser. I would love though to be able to register new users through a form in my iOS app. I am using Django REST, for the mobile API to my django server. Unfortunately, to be able to POST any requests, I need authorization. This is perfectly fine, as the vast majority of the time, my users need to be logged in. The only time they are using my app when not logged in, is exactly when they're signing up (new user). Signing up means creating a new user. Creating a new user, means inserting new data to the database, which of course according to RESTful practices, means I need to use a POST request. But how do I do that without authorization, since I'm not logged in yet. I have two ideas on how to potentially do it, below, but I would love to know what the best practice is. 1) When new user goes to the sign up view, the django server can silently create a new user account, with default initial data. … -
Command on ssh through uwsgi and django app
i want to execute the uwsgi (to serve a Django App through Nginx) so i've created the unix user (my_user) and i've created the ssh keys to connect with other server. So when i try to run a command through a terminal, all works. But.. when i try to send the same command through Django, i get an error: SSHException at /utility/status/ No authentication methods available I've configured uwsgi with the correct uid and gid. Any suggestions? I run uwsgi with the root user (that can run the command on ssh too). If i run the uwsgi with the "my_user", all works! Why? -
Succinct way to handle Form Data on Django using the save() method
My web modules use a lot of forms. In particular, Django web forms. In times where there are many fields (say 15 - 20), I usually do this in the save method: class AddFruitForm(forms.Form): def save(self, request): fruit_name = self.cleaned_data.get('fruit_name', None) fruit_color = self.cleaned_data.get('fruit_color', None) price = self.cleaned_data.get('price', None) location = self.cleaned_data.get('location', None) package_color = self.cleaned_data.get('package_color', None) #Imagine another 10 fields and this is repeated fruit = Fruit( fruit_name = fruit_name fruit_color = fruit_color price = price location = location package_color = package_color #Add 10 more fields ) fruit.save(force_insert=True, force_update=False) My question is: Is there actually a more succinct way to write this? I'm pretty sure that there is but I'm missing it somewhere. -
Django Template to make a list to be sent as post
I am trying to make a mcq quiz and i have used the following code in template {% for MCQ in mcq %} <input type="radio" name="MCQ" value="{{ MCQ.id }}">{{ MCQ.MCQ_Text }} {% endfor %} The problem is that a want to use MCQ_list = request.POST[MCQ] to access it as a list so how do i make a list in template or is there a better way to approach this -
FormView is not showing validation errors
My model.py looks: class VehicleInquiry(TimeStampedModel): inquiry_status = models.PositiveSmallIntegerField(_("inquiry status"), choices=INQUIRY_STATUS_CHOICES, default=1) ip = models.GenericIPAddressField(_("IP"), blank=True, null=True) full_name = models.CharField(_("full name"), max_length=100) address = models.CharField(_("address"), max_length=200) phone_code = models.PositiveSmallIntegerField(_("phone code") ) phone = models.CharField(_("phone"), max_length=20) email = models.EmailField(_("email")) is_subscribed = models.BooleanField(_("subscribed"), default=True) vehicle = models.ForeignKey(VehicleStock, on_delete=models.SET_NULL, blank=True, null=True, related_name="inquiries", verbose_name=_("vehicle") ) country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True, related_name="inquiries", verbose_name=_("country") ) arrival_port = models.ForeignKey(CountryPorts, on_delete=models.SET_NULL, blank=True, null=True, related_name="inquiries", verbose_name=_("arrival port") ) current_price = models.PositiveIntegerField(_('current price'), null=True, blank=True) inspection = models.BooleanField(_("pre-export inspection"), default=False) insurance = models.BooleanField(_("insurance"), default=True) total = models.PositiveIntegerField(_('total price'), null=True, blank=True) my form.py: class VehicleInquiryForm(forms.ModelForm): country2 = forms.TypedChoiceField( label=_("Country"), choices=[('','Arrival Country')]+[(country.id, country.name) for country in Country.objects.all().filter(visible=True).order_by('name')], required=True, ) phone_code = ChoiceFieldWithTitles( label=_("Country dialing code"), choices=[('','Dailing Code', 'Dailing Code')]+[(country.id, '{} (+{})'.format(country.name, country.phone_code), '+{}'.format(country.phone_code)) for country in Country.objects.all().filter(visible=True).order_by('name')], required=True, ) arrival_port = forms.TypedChoiceField( label=False, widget=forms.RadioSelect ) phone = forms.CharField( label=_("Phone"), max_length=20, required=True, validators=[phone_number_validator] ) full_name = StrippedCharField( label=_("Full name"), max_length=30, required=True, validators=[full_name_validator] ) address = StrippedCharField( label=_("Address"), max_length=200, required=True ) class Meta: model = VehicleInquiry exclude = ('inquiry_status', 'vehicle', 'current_price', 'total') def clean_country2(self): country_id = self.cleaned_data['country2'] try: country = Country.objects.get(id=country_id) except Country.DoesNotExist: raise forms.ValidationError(_('Please select the country')) return country_id def clean(self): cleaned_data = super(VehicleInquiryForm, self).clean() dialing_code = cleaned_data['phone_code'] try: dialing_country = Country.objects.get(id=dialing_code) except … -
django formset render again deleted inline form when errors occured
I am using https://docs.djangoproject.com/en/1.10/topics/forms/formsets/ and would like to check if delete of single inline form of the formset is permitted. If it is not allowed I would like to render it back (the deleted inline) with appropriate error. For now it is not rendered and errors are returned in non_form_errors. I am calling my custom check method, raising forms.ValidationError from within clean of FormSet