Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change / Filter dropdown list based based on ownership
This has got to be a common requirement but nothing I've found on SO or in Django docs that works for me. I'm really new to Django. My problem: I need to change the list of Areas that are presented in a form dropdown list according to the company that has Area ownership. In my app: Accounts (i.e Users) are members of Company. A Company manages an Area. Within the Area are a number of Routes. Routes can be added/updated/removed or assigned to different Areas by the Company. So on my forms I want to make sure that only Areas that belong to a Company are displayed in the dropdown list. Essentially a user would select an Area, then CRUD routes associated with the Area. class Company(models.Model): name = models.CharField(... account_number = models.CharField(... ... class Account(models.Model): name = models.OneToOneField(User... company = models.ForeignKey(Company) ... class Area(models.Model): owner = models.ForeignKey(Company) number = modes.PositiveIntegerField(... class Route(models.Model): owner = models.ForeignKey(Company) area = models.ForeignKey(Area) In forms.py class RouteCreateForm(forms.ModelForm): class Meta: model= Route fields= [ 'area', 'route_number', ... ] Adding: self.fields['area'].queryset = Area.objects.filter(owner_id = 2) provides the correct filtering but of course is not dynamic. I've a lot of variations on : def __init__(self, *args, **kwargs): … -
Django Class Based View With ModelChoiceField
I've been working with Django for about 3 months now and feel I'm getting a bit better, working my way up to class based views. On the surface they seem cleaner and easier to understand and in some cases they are. In others, not so much. I am trying to use a simple drop down view via ModelChoiceField and a form. I can get it to work with a function based view as shown below in my views.py file: def book_by_name(request): form = BookByName(request.POST or None) if request.method == 'POST': if form.is_valid(): book_byname = form.cleaned_data['dropdown'] return HttpResponseRedirect(book_byname.get_absolute_url1()) return render(request,'library/book_list.html',{'form':form}) Here is my form in forms.py: class BookByName(forms.Form): dropdown = forms.ModelChoiceField(queryset=Book.objects.none()) def __init__(self, *args, **kwargs): super(BookByName, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].queryset = Book.objects.order_by('publisher') This code works. When I have tried to convert to a Class Based View, that's when the trouble begins. I tried to do something like this in views.py: class BookByNameView(FormView, View): form_class = BookByName initial = { 'Book' : Book } template_name = 'library/book_list.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def get_success_url(self, *args): return reverse_lazy('library:book_detail', args = (self.object.id,)) When using this with the same form, I receive … -
After updating table id via csv file when trying to add new field getting - duplicate key value violates unique constraint
Problem. After successful data migration from csv files to django /Postgres application . When I try to add a new record via the application interface getting - duplicate key value violates unique constraint. Basically the app try to generate id's that already migrated. After each attempt ID increments by one so if I have 160 record I have to get this error 160 times and then when I try 160 times the time 161 record saves ok. Any ideas how to solve it? -
How can I allow user to be "sloppy" when entering a Django phone number?
I'm making a Django form to update users membership to a website. I want to be able to store phone numbers. I found django-phonenumber-field which is great. The only problem is that the form I created for the user to enter their phone number is too specific. If the user doesn't enter their number as "+99999999" then they get an input error. I would like for the user to be able to enter their number a variety of ways: 999-999-9999, 9-999-9999, (999)999-9999, etc. What's the best way to accomplish this? My code: models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Member(models.Model): """defines a member for annual registration""" name = models.CharField(max_length=255) mailing_address = models.CharField(max_length=255) home_phone = PhoneNumberField() other_phone = PhoneNumberField(blank=True) email = models.EmailField() forms.py from django import forms from .models import Member class MembershipForm(forms.ModelForm): """form for renewing membership""" class Meta: model = Member fields = ('name', 'mailing_address', 'home_phone', 'other_phone', 'email', ) Thank you for any help! -
Unable to find vulnerability in my django app backed by postgres
My django application hosted in cloud machine with a postgres setup on the same machine. It broke for no reason, by looking into the database, I observed all the tables were deleted, I am not getting any clue how it was deleted automatically. Even looking into the cpu or memory usage of the time when it was broken, all seems fine. This seems to be a attacked by someone, but I am not able to find out the path of the attacker so that it can be fixed. Below is the postgres log that look suspicious to me: 2017-09-27 15:04:19 IST ERROR: must be superuser to use server-side lo_export() 2017-09-27 15:04:19 IST HINT: Anyone can use the client-side lo_export() provided by libpq. 2017-09-27 15:04:19 IST STATEMENT: select lo_export(3660040808, 'ps3651619459') 2017-09-27 15:04:19 IST ERROR: function fun310002(unknown) does not exist at character 8 2017-09-27 15:04:19 IST HINT: No function matches the given name and argument types. You might need to add explicit type casts. 2017-09-27 15:04:19 IST STATEMENT: select Fun310002('chmod 777 ./ps3651619459') 2017-09-27 15:04:20 IST ERROR: function fun310002(unknown) does not exist at character 8 2017-09-27 15:04:20 IST HINT: No function matches the given name and argument types. You might need to add … -
Dockered Django + Celery (`celeryd` and `celerybeat`), tasks are executed but database (SQLite) is not modified. What is wrong?
I suppose the title says it all. I have Dockered Django application. There I have another containers (docker-compose) for celeryd and celerybeat. There I have tasks that adjust database values per minute. I ran it, I saw in my terminal that the tasks executed as below. celerybeat_1 | [2017-09-30 22:11:00,002: INFO/MainProcess] Scheduler: Sending due task airport_management.tasks.my_task (airport_management.tasks.my_task) This task is supposed to alter the database every minutes. It works with non-dockered version of my Django application. But, in Docker the database is not changed. Here is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./nginx:/etc/nginx/conf.d - ./static:/app/static - ./timezone:/etc/localzone depends_on: - web rabbit: image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5672:5672" - "15672:15672" web: build: context: . dockerfile: Dockerfile command: /app/start_web.sh container_name: django_airport volumes: - ./:/app - ./static:/app/static - ./timezone:/etc/localzone expose: - "8080" links: - rabbit depends_on: - rabbit celerybeat: build: context: . dockerfile: Dockerfile command: /app/start_celerybeat.sh volumes: - ./:/app - ./timezone:/etc/localzone links: - rabbit depends_on: - rabbit celeryd: build: context: . dockerfile: Dockerfile command: /app/start_celeryd.sh volumes: - ./:/app - ./timezone:/etc/localzone links: - rabbit depends_on: - rabbit How can I fix this? -
(1054, "Unknown column 'nan' in 'field list'") Django bulk_create
I am getting the following error when trying to insert data using Django's bulk_create method. It doesn't happen for all data being inserted. (1054, "Unknown column 'nan' in 'field list'") I don't really understand where the 'nan' is coming from, as I explicitly declare all my fields here. I am trying to insert a large amount of objects at a time to the database (around 10,000 or more) My code is as follows, where observation is another object, TemporaryPhotometry is the model being used: # With thanks to https://stackoverflow.com/questions/18383471/django-bulk-create-function-example for the # example on how to use the bulk_create function so we don't thrash the DB phot_objects = [ TemporaryPhotometry( calibrated_magnitude=function_to_make_calibrated_magnitude(), calibrated_error=uncertainty_stars[i], magnitude_rms_error=mage_2[i], x=x_2[i], y=y_2[i], alpha_j2000=ra_2[i], delta_j2000=de_2[i], fwhm_world=fwhm_2[i], flags=flag_2[i], magnitude=mag_2[i], observation=observation, ) for i in range(0, len(num_2)) ] TemporaryPhotometry.objects.bulk_create(phot_objects) I would greatly appreciate any help with solving this issue. Thank you. The full stack trace is the following: File "/var/www/image_processing/analysis/utils/calibration.py" in do_calibration 545. TemporaryPhotometry.objects.bulk_create(phot_objects) File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in bulk_create 443. ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in _batched_insert 1099. self._insert(item, fields=fields, using=self.db) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in _insert 1076. return query.get_compiler(using=using).execute_sql(return_id) File "/usr/lib64/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 1099. cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py" in execute 65. … -
How to correct relation "auth_user" does not exist LINE 1: INSERT INTO "auth_user" ("password", "last_login", "is_super
I am using postgresql as my database and using email instead of username to authenticate. However each time I attempt to register a new user I get this : relation "auth_user" does not exist LINE 1: INSERT INTO "auth_user" ("password", "last_login", "is_super... This is my code on Github These is the response when I created the database : These is the response when I ran the migrations : If you have time and interest I would love to solve this issue. Thank you in advance. -
Django not working inside "style" attribute
I'm trying to display a table with varying background colors depending on a score. I have the following: {% for thing in all_things %} <tr> <td width="25%">{{thing.name}}</td> <td width="25%">{{thing.age}}</td> <td width="25%" style="backgound-color: rgb({{thing.redcolor}},{{thing.greencolor}},0)">{{thing.score}}</td> <tr> {% endfor %} The table is showing properly, and when i print the thing.redcolor and thing.greencolor they show the values they're supposed to be (integers between 0 and 255), but the background color on the cells isn't working. Any help is appreciated. -
Django DB object filter first not getting new items
For some reason when I run this code it keeps looping over the same object and is not getting any new items from the database. In other words, the print output is just the same object over and over, when it should be iterating over items in the list. Here is my code: from mldb.models import Article article = Article.objects.filter(is_locked=False, is_downloaded=False).first() while article: article.is_locked = True article.save() print '******************************' date = article.datetime title = article.title url = article.url print('date: %s' % date) print('url: %s' % url) print('title: %s' % title) get_article(url, title, article) article = Article.objects.filter(is_locked=False, is_downloaded=False).first() Where mldb.models is: from django.db import models class Article(models.Model): url = models.CharField(max_length=1028) title = models.CharField(max_length=1028) category = models.CharField(max_length=128) locale = models.CharField(max_length=128) section = models.CharField(max_length=512) tag = models.CharField(max_length=128) author = models.CharField(max_length=256) datetime = models.DateTimeField() description = models.TextField() article = models.TextField() is_locked = models.BooleanField(default=False) is_downloaded = models.BooleanField(default=False) def __str__(self): # __unicode__ on Python 2 return self.name class Meta: app_label = 'mldb' I have also tried this but it also does not loop through objects: articles = Article.objects.filter(is_locked=False, is_downloaded=False) for article in articles: ... Any ideas? -
django is not displaying media directory
I have this configuration settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #Some dependencies 'django.template.context_processors.media' ], }, }, ] STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) In my urls.py from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'client' urlpatterns = [ url(r'^$', views.index, name='index'), #some others urls ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My media is uploaded in my root project, in the directory /media/ but, when I try to see those resources in the browser, are not displayed and return 404 error. What I have wrong in my configuration? -
fix django views counter
i am creating a blog using Django and i want to count views for each post, i am calling this function when user read the blog post: def post_detail(request, post_id): if 'viewed_post_%s' % post_id in request.session: pass else: print "adding" add_view = Post.objects.get(id=post_id) add_view.views += 1 add_view.save() request.session['viewed_post_%s' % post_id] = True return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)}) the problem is when logging out and log in again, the post views increase again so why django delete the sessions when user logout and how to fix this thanks in advance -
GenericForeignKeyField not shown in related model api
I want to use GenericForeignKeyField in Tastypie api to bind related social accounts to my api models. this is my tastypie model resource class SocialAccountResource(ModelResource): content_object = GenericForeignKeyField({ Customer: CustomerResource, CompanyInfo: CompanyInfoResource, Profile: ProfileResource }, 'content_object') class Meta: queryset = SocialAccount.objects.all() allowed_methods = ['get'] resource_name = 'social_accounts' and these are in my models.py class SocialAccount(models.Model): name = models.ForeignKey(SocialNetwork, null=True) social_network_link = models.URLField(null=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() company info model implementation: class CompanyInfo(models.Model): .... social_accounts = GenericRelation(SocialAccount) .... what i want is to show the social account for every type of model in tastypie like an inline. and the results in api is: Social Account Api Presentation screenshot and nothing shown in company info or customer api . what should i do to solve this problem -
Django admin inline form from child to parent
I have the following model: class Address(models.Model): street = models.CharField(max_length=255) ... class Person(models.Model): private_address = models.OneToOneField(Address) invoice_address = models.OneToOneField(Address) Now, in the admin form for a Person I would like to display an inline admin form for each of the addresses. I know that I could accomplish this by inverting the relation, but then the distinction between the private and the invoice address becomes more complicated. Am I missing something obvious here or is this not possible out-of-the-box? -
Python3.6 on CentOS certificate verify failed
My Django application is currently running on Python 3.4. I want to move it to 3.6, but I have an issue with SSL certificates. The same application works perfectly fine on python 3.4. It still works fine with python3.6 within Docker container and on Windows PC. The only problem is with CentOS and RedHat (both 6.5). My OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013. Full error: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)> What can I do to fix that? The problem is only for python 3.6.0 and python 3.6.1. Python 3.4 works fine with that code. -
Using pdb with supervisor
I am running my django app using docker compose. Ngninx and gunicorn are run via supervisor. However I can't seem to figure out how to debug using pdb. When I use: import pdb pdb.set_trace() After running the command docker-compose up, my app and database begin to run and the terminal screen remains active waiting for further output to display. When my code reaches pdb.set_trace(), the aforementioned terminal remains as is but the (pdb) interface does not appear. Would anyone know how I might be able to debug my application using pdb? Is there something else that I need to use? Thank you. -
post-save signal doesn't get called in Django
Whenever a new User instance is created, I want to create a Profile instance linked to it. To do this, I'm trying to use signals. here's code from models.py: @receiver(post_save, sender=User) def create_user_profile(sender,**kwargs): print(sender) And here's from view.py: @api_view(["POST"]) def register(request): username = request.data.get("username") first_name = request.data.get("first_name") last_name = request.data.get("last_name") email = request.data.get("email") password1 = request.data.get("password1") password2 = request.data.get("password2") user = User.objects.create_user(username,email,password1) if user: user = authenticate(username=username, password=password1) if not user: return Response({"error": "Login failed"}, status=HTTP_401_UNAUTHORIZED) token, _ = Token.objects.get_or_create(user=user) return Response({"token": token.key}) However, nothing gets printed to my Terminal when a new User is created. -
Django display a page title based on a variable stored in a view
I’m a bit stuck on how to display the titles for 2 pages that list articles of different categories using the same template. My article models have content, category (sport, politics, tech etc) and status. I want to display a page listing all sport articles and a page listing politics and I want to use the same template. I have tried storing the title as a variable in the view but this doesn't work Views.py def sport_landing(request): page_title = 'Sport' cat_landing = Article.objects.filter(status='published', category='sport', published_date__lte=timezone.now() ).order_by('-published_date') return render(request, "categorylanding.html", {'cat_landing': cat_landing} Template {% extends 'base.html' %} {% load humanize %} {% block content %} <div class="row category-landing-title"> <div class="col-xs-12"> {% page_title %} </div> </div> . . . Is this even the best way to do this? -
django how do I know which checkbox was checked
I did my best to find the answer, but didn't. My .html code: {% for beer in beers %} {{ beer.drink_name }} ................. {{ beer.price }} <div class="menu_choice"> <input name=beer_{{beer.id}} type="checkbox" class="inline" id="1"/> <select class="menu_choice_count"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </div></br> So there is a loop that prints data, a drop box and a check box. A list will be visible for the user. The user can then choose what to order and click 'order' button. Now based on the check box checked the particular item from the menu should be saved in my db. How do I do that? thank you all for your help. -
Allow one and only one field from fields subset in Django model
I have a model Model. This model have multiple attributes, three of them are: domaintld, subdomain, url - OneToOneFields. I'm trying to allow one and only one from these fields to be non empty. My approach works but I'm curious if it's there a better way to do this (I use PostgreSQL). def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.clean() super(Model, self).save(force_insert, force_update, using, update_fields) def clean(self): super(Model, self).clean() if not(((bool(self.url) ^ bool(self.domaintld)) ^ bool(self.subdomain)) and not(self.url and self.domaintld and self.subdomain)): raise exceptions.ValidationError("One and only one field can be used: url,domaintld,subdomain") -
How to prevent JWT Django (all-auth) from changing token when its username is updated?
I'm using all-auth / django-rest-auth for Authorization. When the User changes his/her username, Django (Django REST Framework) changes user's token and this makes user log-out from app; I set the app to logout if its user's token is invalid. What I want to do is that even if user changes username, email, or any field in User, it keeps token. Here is settings.py REST_USE_JWT = True AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', ) JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30), } ... Thanks! -
Changing help without refactoring the whole code
I have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc 1- If I pull NHL data inside a .csv file, will he be able to process information in Excel from that file? 2- Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. Please let me know if the question is unclear. -
Username and password authentication in django
I need to validate username and password in django app, below are the details view is, class HomeView(TemplateView): template_name = 'home.html' template_name2 = 'Logout.html' def get(self,request): form = LoginForm() posts=users_data.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) return render(request,self.template_name, {'form':form}) #template_name2 = 'Welcome.html' def post(self,request): form = LoginForm(request.POST) if form.is_valid(): #text=form.cleaned_data['post'] username = forms.cleaned_data.get("Username") password = forms.cleaned_data.get("Password") user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exist") return render(request, self.template_name1) else: form.save() return render(request, self.template_name2) else: return render(request, self.template_name1) after entering username and password it is giving me error and doing nothing. I am stuck at this point . Requesting for help. my form is, from django import forms from login.models import * from django.contrib.auth import authenticate,login,logout,get_user_model user=get_user_model() class SignupForm(forms.ModelForm): class Meta: model=users_data fields=('Name','Email','Username','Password') class LoginForm(forms.ModelForm): class Meta: model=users_data fields=('Username','Password') def clean(self): username = self.cleaned_data.get("Username") password = self.cleaned_data.get("Password") user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("This user does not exist") -
django-jquery-file-upload: filtering images only for a service
I've configured django-jquery-file-upload to upload files for a service. Here's the code for the view # encoding: utf-8 import json from django.http import HttpResponse from django.views.generic import CreateView, DeleteView, ListView from .models import Picture from .response import JSONResponse, response_mimetype from .serialize import serialize from accounts.models import UserService class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'accounts/upload-file.html' def form_valid(self, form): self.object = form.save() user_service = self.request.COOKIES.get('service_id', None) if user_service: exists = UserService.objects.filter(id=user_service) if exists: service = exists[0] obj = self.object obj.user_service = service obj.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') and from the models... # encoding: utf-8 from django.db import models from accounts.models import UserService class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) user_service = models.ForeignKey(UserService, related_name="uploads", blank=True, null=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) … -
What is the usage of dispatch in django class base view
Django ListView have a method dispatch(). According to Django documentation dispatch is The method that accepts a request argument plus arguments, and returns a HTTP response. Have been searching for more information but couldn't find any neither can understand properly. Can anyone explain me a bit deeper for a better understanding.