Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign key's queryset based on other foreign key in the admin form?
I have two foreign keys in a model State and City. Initially in the django's admin form I have all all the states and cities listed in the drop down. I want that if I select any state I only get the city in that state. How can I do this in Django admin's form? -
Django what is best way to build query
I wonder what is the way to build a query. I'm was trying to use SubQuery or Prefetch, prefetch_related, select_releated but i can't get better results from which I start. I have situation where I'm getting object instance. object = get_object_or_404(Object, id=pk) then i need to get more data. object.id, object.name, object.description, object.update_frequency, object.resources.values_list('extension'), object.tags.values_list('name'), object.resources.count(), object.resources.values_list('file'), object.resources.values_list('licence'), object.edited each row is different query. How in best way reduce query number? -
ubuntu18.04+uwsgi+django: unsupported hash type
When I am deploying my django site to an Ubuntu 18.04 Server,I found that using python manage.py runserver works well.But when I use uwsgi to run this django site,a unsupported hash typeerror keeps occuring at the submission of my login form. Environment: Ubuntu 18.04/anaconda3(use conda to manage virtualenvs)/python3.6/uwsgi2.0.17/django2.0/ error detail:this is where the exception come from:user = authenticate(username=username, password=password) Exception Type: ValueError Exception Value: unsupported hash type my uwsgi ini file: [uwsgi] chdir = /www/wwwroot/django-xxx/ plungins = python,gevent socket = 127.0.0.1:8080 module = apps.wsgi:application gevent-early-monkey-patch = True gevent-wait-for-hub = True gevent = 10 workers = 3 master = True vacuum = True user = root logto = /www/wwwroot/django-xxx/uwsgi.log Traceback: File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./apps/sspanel/views.py" in user_login 94. user = authenticate(username=username, password=password) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/init.py" in authenticate 70. user = _authenticate_with_backend(backend, backend_path, request, credentials) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/init.py" in _authenticate_with_backend 115. return backend.authenticate(*args, **credentials) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/backends.py" in authenticate 22. if user.check_password(password) and self.user_can_authenticate(user): File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/base_user.py" in check_password 111. return check_password(raw_password, self.password, setter) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/hashers.py" in check_password 50. is_correct = hasher.verify(password, encoded) File "/anaconda3/envs/django-sspanel-7/lib/python3.7/site-packages/django/contrib/auth/hashers.py" in verify 256. encoded_2 = self.encode(password, salt, … -
Problem in replacing body contents with ajax from a django HttpResponse
I'm using Django as server and trying to update contents in a body tag periodcally with ajax. The ajax part looks like this: <html> <head> <meta charset="utf-8"> <title>A Pyecharts Demo</title> {% for jsfile_name in script_list %} <script src="{{ host }}/{{ jsfile_name }}.js"></script> {% endfor %} <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <script> setInterval(function() { $.ajax({ url:"/first_pyecharts/", type:'POST', data:{ 'last_update':'{{ last_update }}', 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: "html", success: function (html) { document.getElementById("body").innerHTML = html } }); }, 10000); </script> <body id="body"> <!-- contents to be replaced --> </body> related codes in views.py: if last_update is None: update_context(cur) template = loader.get_template('pyecharts.html') return HttpResponse(template.render(context, request)) elif latest > datetime.strptime(last_update, '%Y-%m-%d %H:%M:%S'): update_context(cur) template = loader.get_template('pyecharts.body.html') return HttpResponse(template.render(context, request)) else: template = loader.get_template('pyecharts.body.html') return HttpResponse(template.render(context, request)) The server returns an HttpResponse with template either rendered by previously stored or new context based on 'last_update' submitted from ajax. Here the template 'pyecharts.html' is the complete page with 'html', 'head', 'script' and 'body' parts as shown above. While 'pyecharts.body.html' only contains the contents within the 'body' part, which is used to update the 'body' tag inside the webpage. But When ajax gets its response from Django, it seems to have replaced the whole page with the response, … -
django rosetta show multiple language sources
In the Rosetta admin interface, is it possible to see another language beside the original language in the PO file? Say my PO file has msgids in English, and I have them translated to Spanish. Now I want to translate to other languages. I want to show the Spanish text in the UI (in addition to the original msgid in English). I see rosetta has a settings called ROSETTA_ENABLE_REFLANG which creates a language selector, but no matter what I pick in has no effect. -
Django receiving data from UDP and storing in DB, only if condition coming from websockets set to true
I'm trying to implement a rather complex architecture for a desktop application (not to be distributed, so it's ok to use technology usually adopted for servers - please don't tell me to use electron or .NET). It basically must store data coming from a UDP stream (with new data frequency at ~90Hz). The application should also open a websocket server and accept new clients, specifically from a tablet. The tablet user should be able to set a flag, enabling or disabling data storage. This is a very simple block scheme of the system I already used Django before, but for more standard usage (CMS, REST APIs, etc). After some research, I found some tools I could use to build the system: 1 - Celery, which to my understanding enables running asynchronous tasks (I guess I could use it to store the data coming from the UDP stream, maybe after accumulating a hundred values or so) 2 - Django channels, which should help me in the websocket communication 3 - Twisted, to receive UDP messages. What confuses me is how to integrate these components, and exchange data between them. Looks like twisted is a completely separated server, so how can i … -
Filter items on date (Django)
I make a simple todo list. First, I display a list of all dates on which items have been added. views.py def allDates(request): date = Todo.objects.extra(select={'custom_dt': 'strftime("%d-%m-%Y", "created_at")'}).values_list('custom_dt', flat=True).order_by('-custom_dt').distinct() # display all dates return render(request, 'todo/alldates.html', {'date':date}) alldates.html {% for dat in date %} <a href="{% url 'detaildate' %}"><h1>{{ dat }}</h1></a> # link to see items added to this date {% endfor %} After I try to create a method that filters the items by date I clicked on views.py (detaildate) def detailDate(request): detail = Todo.objects.order_by('-created_at') return render(request, 'todo/detaildate.html', {'detail':detail}) I have this result, display all items, but i need only from date I link How I can display - filter items by date in link ? -
Django RedirectView with slug in the URL
I'm getting RedirectView with Django and I would like to know how I can pass a slug in my url. In my Django web application, users can set one or multiple document(s) in a cart and open a modal with personal informations before to submit the form and get an email with checked document(s). This url in my application looks like this : http://localhost:8000/freepub/home?DocumentChoice=<code>&DocumentSelected=Add+document <code> corresponds to a unique document code (ex: PUBSD15-FR-PDF or PUBSD01-EN-EPUB) But this url is a bit complicated, because it should be add to another application. That's why I'm using RedirectView in order to make easier this url : url(r'^freepub/direct/download/(?P<code>[\w\.-]+)/', RedirectView.as_view(url="http://localhost:8000/freepub/home?DocumentChoice=(?P<code>[\w\.-]+)&DocumentSelected=Add+document"), name='go-to-direct-download') Issue : If I write in my url : http://localhost:8000/freepub/direct/download/PUBSD15-FR-PDF The redirection is : http://localhost:8000/freepub/home?DocumentChoice=(?P<code>[%5Cw%5C.-]+)&DocumentSelected=Add+document How I could take into account the code in my url instead of (?P<code>[%5Cw%5C.-]+) ? Thank you -
pdftotext-buildpack is not getting installed on heroku
I am getting this when deploying my python app. remote: -----> pdftotext-buildpack app detected remote: -----> pdftotext-buildpack: Installed to app/bin remote: -----> nginx-buildpack app detected remote: -----> nginx-buildpack: Installed nginx/1.9.5 to app/bin remote: -----> nginx-buildpack: Added start-nginx to app/bin remote: -----> nginx-buildpack: Added start-nginx-solo to app/bin remote: -----> nginx-buildpack: Default mime.types copied to app/config/ remote: -----> nginx-buildpack: Default config copied to app/config. remote: -----> Discovering process types remote: Procfile declares types -> release, web but getting following error when i am trying to access pdftotext FileNotFoundError: [Errno 2] No such file or directory:`/usr/bin/pdftotext` -
What happens if multiple runcrons is executed
I have multiple cron jobs written in Django and I'm using package django-cron. If I run the following command multiple times, what will happen? python manage.py runcrons I want if second runcrons sees that some cron job is executing by the first runcrons, simply ignore it and don't wait for the first one to be completed! -
form.is_valid always false
I've been trying to figure out why form.is_valid always return false but I still haven't figured it out yet and it doesn't help that I've just started with Django. Model class Post(models.Model): STATUS_CHOICES = ( ('d', 'Draft'), ('p', 'Published'), ) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=120, null=True, blank=True) text = models.TextField(max_length=500, null=True, blank=True) slug = models.SlugField(max_length=40, unique=True) publish_date = models.DateTimeField(null=True) status = models.CharField(choices=STATUS_CHOICES, max_length=1,default='d') Form class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','author','slug','text','publish_date','status') widgets = { 'title': forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Title'}), 'author': forms.Select(), 'slug': forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Slug'}), 'text': forms.Textarea(attrs={'class' : 'form-control', 'placeholder' : 'Text'}), 'publish_date': forms.DateInput(attrs={'class' : 'form-control', 'placeholder' : date.today}), 'status': forms.NullBooleanSelect(attrs={'class' : 'form-control'}), } View def admin(request): if request.user.is_authenticated: if request.user.is_staff: users = User.objects.all().order_by('date_joined').reverse()[:5] posts = Post.objects.all().order_by('created').reverse()[:5] publications = Publication.objects.all().order_by('created').reverse()[:5] form = PostForm() args = {'profile' : users ,'posts' : posts, 'publications' : publications, 'form' : form } if request.POST: print('request is posting') if form.is_valid(): form.save() else: print('Error in saving') return render(request, 'webadmin/index.html',args) else: return index(request) else: return redirect('/webmaster/login/') I do hope that you can help me, Thank you OWO)/ -
Adding code and methods to Django Model breaks it
I have a Django model similar to this: class Person(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.TextField(unique=False) I wanted to add code to a person, outside of the models.py file. So I tried to import it, inherit from it and add code:e.g: class MyPerson(db.Person): def __init__(self, person_name): super(MyPerson, self).__init__(name=person_name) def print_person_info(self): print(self.name) I get an error similar to this one: RuntimeError: Model class db.persons.models.Person doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. although of course in my settings.py file I do add my persons app to the INSTALLED_APPS I guess I can add the code directly inside models.py but it seems to be very inconvenient as I want to add more code there, and for several models. Any ideas? Is it in general OK/Recommended to inherit from the model? -
When to use 'def __unicode__(self):' in models.py - Django
When in models should be used 'def unicode(self):'? In Python's documentation, we can see something like: class Author(models.Model): name = models.CharField(max_length=50) email = models.URLField() def __unicode__(self): return self.name But I do not see any difference in action when i have, or i do not have it: def __unicode__(self): return self.name My class using 'name' works the same. Class view below: class Entry(models.Model): headline = models.CharField(max_length=255) authors = models.ManyToManyField(Author) (I tried to use this in django admin, for example 'admin.site.register(Entry)') When to use 'def unicode(self):' and when should it not be used and what is its function?? -
request.POST from Django with Javascript submit form
I would like to get your help on my issue. Usually, when I submit a POST request in Django with a submit button, I take the button name like this : <button id="document-button" type="submit" name="UpdateDocument">Submit</button> And in my view : if "UpdateDocument" in request.POST: ... do something But in my code, I need to submit my form with Javascript onchange method. Hence, I don't have any button to submit my form : <form id="select-animal-form" action="" method="POST"> {% csrf_token %} <fieldset> <legend><span class="name">Select Animal</span></legend> {{ form.animal_list }} </fieldset> </form> <script> $('#select-animal-form').on('change', function(){ $(this).submit(); }); </script> I would like to pick up the submit request.POST for this form. I wrote this : if request.POST and not "UpdateDocument" in request.POST: ... do something But even buttons Next or Previous in my pagination are called in this part. I just want to call in this part the submit form. How I can do that ? Thank you -
django Q as chained .filter()
There are 2 models connected with a many-to-many relationship. class Record(): working_on_record = models.ManyToManyField( UserProfile, related_name="working_on_record", blank=True) class UserProfile(): name = CharField... The UserProfile is just a basic user model. Now I want to query a search for records and check if all keywords are matched but if I do: query = Q() c1 = UserProfile.objects.filter(name__icontains='peter') query.add(Q(working_on_record__in=c1), Q.AND) c2 = UserProfile.objects.filter(name__icontains='john') query.add(Q(working_on_record__in=c2), Q.AND) set3 = list(models.Record.objects.filter(query)) Set3 is empty, despite there is a record which has two people working on it whose names are "john smith" and "peter parker". If I replace "john" in c2 by "parker" I get all records where "peter parker" is working on it. But if I chain the filter methods: set4 = list(models.Record.objects .filter(working_on_record__in=c1) .filter(working_on_record__in=c2) ) set4 is not empty and contains the record I want. Is it possible to change the Q-query so that I get the behavior I want? Is it possible to filter with a Q-query on one many-to-many-relationship with different values from different objects connected with an AND? I don't like the idea of chaining the filter methods, because of multiple possible usages of the Q-query, so I would have to iterate at multiple occasions through all queries and chain them. -
Get all models involved in a queryset django
I have a model class users which contains users of my company class User(models.Model): ... name = CharField(max_length=100) email = CharField(max_length=100) ... ) Then my company collaborated to serve another company, so we decided to keep both the users within same users table. Hence we added a source_id field in the Model, So now it looks like.. Where we keep default 1 that means user belongs to our company and for other we will user source_id as 2. class User(models.Model): ... soiurce_id=IntegerField(default=1) name = CharField(max_length=100) email = CharField(max_length=100) ... ) But the complete code is written to work for single source only. Even the same user can come from two different companies with same email address.. so i made (source_id,email) as unique constraint. Although i am getting the source in request flow. So i tried overriding the get and filter by appending the source_id in the queryset of user manager, But that fails if we user will be joined with other tables For Ex: Houses.objects.filter(user__email="abc@xyz.com") in this, it will call houses model manager and the queries will not be overridden with the filter and I will get both the users. Is there is any way I forceful inject source_id in … -
Django + Nginx save uploded file to other server and reverse file
I have 2 servers: first for Nginx and Django and second server for storage Nginx and app server IP: 192.168.1.1 storage server IP: 192.168.1.2 Nginx installed on two servers. In Django config media path: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Nginx config is in the first server: server { listen 80; server_name 192.168.1.1; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log ; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { proxy_pass http://192.168.1.2/; } location / { uwsgi_pass unix:/tmp/uwsgi/app.sock; include uwsgi_params; } location /static/ { alias /home/ubuntu/app/static/; } } and storage server Nginx config: server { listen 80; server_name 192.168.1.2; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log ; location /media/ { alias /home/ubuntu/app/media; } } Questions: How can Django save (upload file) to the storage server (192.168.1.2)? better if suggest solutions with minimum changes in code. How Nginx can reverse files from a storage server? the end user just typing 192.168.1.1 -
Mapbox Geocoder gives index error (internal server error)
I'm using mapbox geocoder for finding latitude and longitude from zip-codes.Problem is it sometimes work just fine and somtimes doesn't work at all.When it doesn't work,it return index error out of bounds,but in my terminal also shows internal server error. What can be done it this situation? My code is bellow: def get_context_data(self, **kwargs): context = super(SingleCenterDetailView, self).get_context_data(**kwargs) zip_code = self.object.center.zip_code geocoder = Geocoder(access_token=mapbox_access_token) response = geocoder.forward(str(zip_code)) response = response.geojson()['features'][0] resp = response.get('center') geo = [resp[0],resp[1]] context['geo'] = geo return context And the problem is in line response = response.geojson()['features'][0] becouse when it works good,when I print this line it shows dict like this {'text': '53-334', 'context': [{'text': 'Wrocław', 'wikidata': 'Q1799', 'id': 'place.8365052709251970'}, {'short_code': 'PL-DS', 'text': 'Dolnośląskie', 'wikidata': 'Q54150', 'id': 'region.25860'}, {'short_code': 'pl', 'text': 'Poland', 'wikidata': 'Q36', 'id': 'country.340'}], 'geometry': {'coordinates': [17.026519, 51.096412], 'type': 'Point'}, 'center': [17.026519, 51.096412], 'type': 'Feature', 'relevance': 1, 'bbox': [17.024936, 51.095263, 17.028411, 51.09752], 'place_name': '53-334, Wrocław, Dolnośląskie, Poland', 'place_type': ['postcode'], 'properties': {}, 'id': 'postcode.5334805015388220'} when it doesn't work it prints nothing (thats this index error) So my question is,can anything be done to solve this? I mean,if this sometimes work and sometimes does not then its probably mean that for some zip-codes it cannot find latitude … -
Django progressive web app caching and fetching of templates issue
I am trying to run my django application with a progressive web application, but it seems to be an issue that for my service worker to run, it needs to run in the same folder as all my templates. Unfortunately, on django applications, templates are organised into different modules/apps. Based on tutorials - the service worker file(sw.js) needs to be in the same folder as the templates that will be cached see Service worker is caching files but fetch event is never fired . but based on the tutorial on youtube at https://youtu.be/70L8saIq3uo?t=1252 it looks like it can be done by including the {% url “urltobecached” %}. But that brings to the question how to get the sw.js file to read from all the templates that needs to be cached since they need to be all inside the same folder as sw.js which is in the static folder. I wasn't able to locate any resource that can solve this issue. Anyone has any experience on this to suggest how to do this? Below is a sample of all the relevant code home.html {% load staticfiles %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Testing</title> … -
Django listview capture value from url then pass to template
I captures value from url using def get_queryset(self): name= self.request.GET.get('name') Now want to pass this varible to template. Just like: your have searched: {{ name }} -
How to save form(foreign key) values to database in class-based views with multiple databases in django
In django i am using multiple databases and the name of one of them is 'virtual'.virtual is not a default database After submitting the Clientipform ,it displays the following error Cannot assign "'30001'": "FT_CLIENT_IP_DETAILS.iMasterID" must be a "CLIENT_MASTER" instance. i am thinking that the error is due to foreign keys.here 30001 is a foreign key in FT_CLIENT_IP_DETAILS in models.py class FT_CLIENT_ACCOUNTS_MASTER(models.Model): iClientaccID = models.AutoField(primary_key=True) class CLIENT_MASTER(models.Model): iMasterID = models.AutoField(primary_key=True) class FT_CLIENT_IP_DETAILS(models.Model): iSno = models.AutoField(primary_key=True) iMasterID = models.ForeignKey(CLIENT_MASTER,on_delete=models.CASCADE, default='',db_column='iMasterID') iClientAccID =models.ForeignKey(FT_CLIENT_ACCOUNTS_MASTER, on_delete=models.CASCADE,default='',db_column='iClientAccID') vcClientIP=models.CharField(max_length=16,default=0) class Meta: db_table='FT_CLIENT_IP_DETAILS' in forms.py class Clientipform(forms.ModelForm): Masterchoice=[("","All")] Accountchoice=[("","All")] iMasterID=forms.ChoiceField(label="Master",choices=Masterchoice+[ (o.iMasterID, str(o.vcClientName)) for o in CLIENT_MASTER.objects.using('virtual').all()],error_messages= {'required': 'Master is required' }) iClientAccID=forms.ChoiceField(label="Account",choices=Masterchoice+[ (o.iClientaccID, str(o.vcSystemID)) for o in FT_CLIENT_ACCOUNTS_MASTER.objects.using('virtual').all()], error_messages={'required': 'Account is required' }) vcClientIP=forms.CharField(label="IP(s)",widget=forms.Textarea, error_messages={'required': 'Account is required' }) class Meta: model=FT_CLIENT_IP_DETAILS fields = ['iMasterID','iClientAccID','vcClientIP'] in views.py class AddIP(CreateView): template_name = 'clientip/client_ip_dropdown.html' form_class = Clientipform def form_valid(self,form): model = form.save(commit=False) model.save(using='virtual') return HttpResponseRedirect(reverse('clientip:home')) success_url = reverse('clientip:home') -
Why Django want to alter table with proxy model?
I'm using Django 1.8, Python 2.7.15. Junior dev. I created a model Test with many to many field to Django Group model: class Test(models.Model): group = models.ManyToManyField(Group) I've made a migration, my project was working, all was good. Now I had to create Group's proxy model with specyfic managers: class ExtendedGroup(Group): get_all = AllGroupsManager() objects = DefaultGroupManager() class Meta: proxy = True And I had to change my Test model group field (is has methods that must use new managers... so I have to use ExtendedGroup): I'm changing ManyToManyField relation from Group to ExtendedGroup. class Test(models.Model): group = models.ManyToManyField(ExtendedGroup) ExtendedGroup is proxy model so I think Test's group field should be related to Group even if I use ExtendedGroup (becouse it is proxy model). But when I run server I got ProgrammingError: column test_test_group.extendedgroup_id does not exist When I "makemigrations" I can see that Django want to Alter group field with new relation to model (ExtendedGroup) that actually does not have any tables in database becouse it is proxy model. operations = [ migrations.AlterField( model_name='test', name='group', field=models.ManyToManyField(to='mainpage.ExtendedGroup'), ), ] What is going here? Is it right? Why Django want to create relation to model that does not have any tables? … -
Why the forms is important in django.
If we are writing forms.py how we will design it better because the python files not containing front-end code. If any one can provide sample code on both way. 1. Using forms. Py 2. Using html -
Full path of request from entering Django server to a view
Case: on application Django+DRF+Angular while trying to download file I am redirected to a raw DRF template with 401 - Authentication credentials were not provided. But when I login into Django admin - download works ok. When I try debugging my view - I see that request does not even reach that view. Question: How can I debug this? How can I track full request path to my view, so I can find the place where it fails? May be in a Middleware or somewhere else? From where should I begin? -
Should I test methods in Django models?
Is there any reason to test model methods or I should assume that Django works properly and leave them untested? Here is my model and couple methods from it: class SlackTeam(models.Model): ... def get_user(self, user_id): return self.users.filter(user_id=user_id).first() def deactivate(self): self.active = False self.initiator.access_token = '' self.initiator.save() self.initiator = None self.deactivated_at = timezone.now() self.save() if hasattr(self, 'slackbot'): self.slackbot.delete() def set_initiator(self, user): self.initiator = user self.save(update_fields=['initiator']) @classmethod def initialize(cls, team_id, name): return cls.objects.update_or_create( team_id=team_id, defaults={'name': name})[0] @classmethod def get_by_team_id(cls, team_id): return cls.objects.filter(team_id=team_id).first()