Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Don't refill Django forms with Browser Back Button
I'm asking a question and the answer could help me a lot. When I'm filling my Django form, I press a validate button in order to store data form. Then, I am redirected on a new page (form resume page, home page, ...). But in my browser, if I click on Back Button, my form is already filled with previous data and I can modify data. My question is : How I can prevent browser from refilling form data when navigating back with Django ? I found this Stackoverflow question : there But the answer doesn't seem to work. It's an old answer and I'm supposing it exists an other way to do that ? -
Convert array dictionary to a dictionary python
I want to convert this array to dictionary without the word array. {1: array([[ 38.13823661, 48.52341785]]), 2: array([[ 19.60433883, 45.63071969]])} -
User input to run a custom graph search in Django?
I have a couple of different graphs I want to run topological sort's on. I want to be able to take user input (a word) to begin running a top sort on the relevant graph. How do I go about connecting the user input to my topo search? And in terms of django file structure where would should I put the graph and search code, would it go into views or should they be in their own file and imported in? I've been thinking about how this would work and I'm assuming I would take the input as a get request and the topo sort using the input a the source vertex but I'm not sure. -
Natural sort on Django Queryset
I am working on a system that lists out a range of products sorted by their product code. The product codes are made up of two letters for the followed by a number, for example EG1. I currently sort these products by doing a simple Product.objects.order_by('product_code'), however as there can be multiple digit product codes (for example EG12), these will come out above ahead of the single digit codes. i.e EG1, EG11, EG12, EG13 ... EG19, EG2, EG20 etc I know that adding leading zeros to the product codes will fix this (i.e EG01 rather than EG1) but as there is already printed literature and an existing site using EG1 this is not an option. Is there a way to fix this to show these products in the correct order? -
what happened when we restart django or refresh webpage?
I am using django to develop a website, I use rpy2 to invoke R package - cdkr. This is my weird problem: When I start django project, the first time I can get correct answer; When I refresh the webpage or submit the same form again, it cannot work, ang get these error message: Error in .jcall(cn, "Ljava/lang/Object;", "get", as.integer(i - 1)) : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 I use runserver_plus to debug, I can run the code only once, when I run it again, I will get the same error: # the first time I run "r_result = robjects.r(rcode)" robjects.r(rcode) Start calculate molecular descriptor. Check packages. Start interprite molecular smiles. Start plot structure. Start calculate descriptors of structure. Start export descriptors. Start predict CCS values. Start output result. But... # the second time I run "r_result = robjects.r(rcode)" robjects.r(rcode) Start calculate molecular descriptor. Check packages. Start interprite molecular smiles. Start plot structure. Start calculate descriptors of structure. Traceback (most recent call last): File "<debugger>", line 1, in <module> robjects.r(rcode) File "/usr/lib64/python2.7/site-packages/rpy2/robjects/__init__.py", line 359, in __call__ s += str.join(os.linesep, tmp) return s RRuntimeError: Error in .jcall(cn, "Ljava/lang/Object;", "get", as.integer(i - 1)) : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 This is my … -
Django models.FileField.clean() method deprecated or never hit?
From everything I can find, the FileField.clean() method should be executed when a file is added to a model, but the method is simply never executed. Note that I'm referring to the models.FileField object, not forms.FileField. See: related stackoverflow question class ContentTypeRestrictedFileField(models.FileField): def __init__(self, *args, **kwargs): # Log that it hits here super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): # THIS IS NEVER HIT data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs) return data -
Error: PYTHON DJANGO PRAW REDDIT-API
building locally a Django 1.8 web app in a Python 2.7 virtual env using Praw 4.4.0. The project is called demonstration and has an app called app Atm, This is part of the result when going to: http://127.0.0.1:8000/app/profile/ app/views.py has the following code for profile: # views.py from django.shortcuts import render, HttpResponse import requests import praw # Create your views here. def profile(request): reddit = praw.Reddit(client_id='client_id', client_secret='client_secret', username='username', password='password', user_agent='user_agent') # assume you have a Reddit instance bound to variable `reddit` subreddit = reddit.subreddit('redditdev') print(subreddit.display_name) # Output: redditdev print(subreddit.title) # Output: reddit Development print(subreddit.description) # Output: A subreddit for discussion of ... As you can see in the second image, the name of the subreddit gets printed. Great. Well, not so great. That was written in the code, so it's not picking up from Reddit, see: subreddit = reddit.subreddit('redditdev') print(subreddit.display_name) # Output: redditdev Once it actually tries to go to Reddit and suck up the data, this is the result: print(subreddit.title) # Output: reddit Development print(subreddit.description) # Output: A subreddit for discussion of ... [01/Mar/2017 14:50:02]"GET /app/profile/ HTTP/1.1" 500 93288 Using Debug mode = True, one can see the following in the page: Problem: somehow, Reddit is not liking my … -
Django order by queryset by requests values (id__in)
I query a Django table by a list of IDs hclistofcases = testcase.objects.filter(id__in="[182, 180, 184, 179, 178, 181, 183")) That words an returns a queryset, however the queryset is not in the list order (i.e. record 182 first and 183 last). Is there a way to ensure that the quesryset is returned in the list order? I am currently using sqlite as the database Any hep would be appreciated Thanks Grant -
importing a class from a file in a seprate package
I am using python and django. my directory structure looks like this **hospitality211 (package)** _init_ **users (package)** _init_ models.py (other py files) **venue** (package) _init_ models.py I am trying to import a class from the model.py file in the venue package into the model.py file in the user package. I have tried the following from hospitality211.venue.models import Venue from venue.models import Venue import venue none of these are working. I am importing from packages so I am not sure why this is happening -
Django: User user model not loaded
from django.contrib.auth import get_user_model from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ['username', 'email', 'password'] I'm getting: "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." I don't know what's happening. I'm new to Django. The version I'm using is 1.10.6 and Python 2.7.12. What's the correct way to do this? -
Migrate from DateTimeField to DateField
I have a model that contains a created_at field that is a models.DateTimeField. I want to migrate it to a models.DateField as the time is no longer necessary to have. I change the mode, ran makemigrations, and applied it to my database. I foolishly assumed that the data would be migrated. No so, as all the created_at fields are now None. How can I convert the existing data so the date is still available? -
Django: Two Forms with a ModelChoiceField
I have one form with a ChoiceField, which submit immediately after selecting. Then I get data for my second ChoiceField and show depend of the first choice different data for the field. Now, I want to submit the data from both forms. What is the best strategy? I prefer solutions without js. forms.py: class Form1(forms.modelForm): group = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={'onchange': 'this.form.submit();',})) class Form2(forms.modelForm): member = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={}), empty_label='') class Meta: ... def __init__(self, user_name, group, *args, **kwargs): super(Form2, self).__init__(*args, **kwargs) The problem is that if i submit the second form, that i don't get the data from the first form. There error message is: Select a valid choice. That choice is not one of the available choices. I can also add code. -
Passing an HTML input field value to urls.py using href
I can't figure out how to pass a value from an input field to my urls.py file. I am trying to use the mcode ID value, but obviously that is the wrong approach. I have been searching for a solution for 2 days with no luck, so any advice would be greatly appreciated. Thanks. <!-- ----------------------------------------------------------------- --> <div> <form > <div class="input-group"> <input type="text" class="form-control search-block" id="mcode" placeholder="Enter your Master Code"> <span class="input-group-btn"> <a button class="btn btn-primary" type="button" href="{% url 'master:detail' mcode.value %}">OK</button></a> </span> </div> </form> -
how to login with phone number in django [on hold]
is there any method that handle to different users that once login with user name and password and other one login just with phone number? -
django many to many through
I'm trying to implement a coaching system and I'm a little lost about serialization in django.I have a many to many through model to control the appointments and I want to get all data about the coach/coachee involved in the relationship. class Appointment(models.Model): """docstring for Appointment""" coach = models.ForeignKey(User, related_name='coaches', on_delete=models.CASCADE) coachee = models.ForeignKey(User, related_name='coachees', on_delete=models.CASCADE) schedule_date = models.DateField(auto_now=False, auto_now_add=True, blank=True) due_date = models.DateField() summary = models.TextField(max_length=200) Using the following serializer I can get the primary keys involved but I'd really like to get the coach and coachee details in one request. #return appointment data class AppointmentSerializer(serializers.HyperlinkedModelSerializer): """docstring for AppointmentSerializer""" class Meta: model = Appointment fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition') -
ValueError: invalid literal for int() with base 10: 'SOME STRING'
I keep receiving this error. Initially, I've added a field in my code: `class Personne(models.Model): matricule = models.CharField(max_length=10) amis = models.ManyToManyField("self", null=True) faculte = models.ForeignKey(Faculte)` I had to change it to `faculte = models.ForeignKey(Faculte,default='SOME_STRING')` to remove the error during the migration but it's still being displayed. I am new to Django, anyone got an explanation why there is this Value error? error Thank you, -
django - Q object that don't assert if one or more fields don't exist
Lets say I have the following models: Model A: date category something ... and: Model B: date category ... I want to create a single Q object that will filter by date, category, and something, but only if it exists in the model I apply the filter on. In other words, a single Q that I can apply on both A and B models, just that with B the something filter will be ignored since this field doesn't exist in B. If I try a naive implementation, eg a Q with date, category and something in it, when applied on B model I get the following error: FieldError: Cannot resolve keyword 'something' into field. Choices are... Which makes sense since B really don't have a field named something in it. But I want to change that behavior and make it work and just ignore the non-existing field instead of throwing an exception. Is that possible? -
Get Python/Django query into proper json format
I have just begun learning jquery and would like to implement a table into my Django application. I need to get the data into this form... var tabledata = [ {id:1, name:"Oli Bob"}, {id:2, name:"Mary May"}, {id:3, name:"Christine Lobowski"}, {id:4, name:"Brendon Philips"}, {id:5, name:"Margret Marmajuke"}, ]; Right now by doing ... import json data_json = list(Player.objects.values('name','id')) row_json = json.dumps(data_json) I get it in a form like [{"name": "Bojan Bogdanovic", "id": 11384},....] For all the examples that I have seen this is usally enough but because id and name need to be without quotes, what is the best way to approach this problem to get my query into the proper format. -
how to Order_by & Slice EmbeddedDocumentListField mongoengine
I am using mongoengin at Django. EmembeddedList I want to sort and slice data, but I can not. Is there a way to do it? class Thread(Document): thread_content = StringField(required=True) comments = EmbeddedDocumentListField(Comment) registration_date = DateTimeField(default=datetime.now) class Comment(EmbeddedDocument): user = StringField(required=True) comment_content = StringField(required=True) registration_date = DateTimeField(default=datetime.now) thread = Thread.objects(id=thread_id).fields(slice__comments=[0, 10]).order_by('-comments__registration_date').first() -
Posting form data during allauth signup
I've currently got a form requesting some data from the user. When the user clicks submit, if they are not logged in a bootstrap modal appears with an allauth signup/login form and the contents of the first form is copied in using jquery as hidden fields to submit alongside their signup/login. This works if they submit correct signup/login details as I have access to the first forms data in def signup. However, if the user makes any mistakes in the signup data they are redirected to /accounts/signup/ and once the user makes corrections to their signup the first forms data is no longer accessible. Any ideas how I can make sure these extra form fields are always saved alongside the signup/login? -
calling jquery from a Django view
I am using a django and have a page where user can click on a link in a django table (django-tables2) to be able to edit a record: My table model looks as follows: class DummyTable(tables.Table): edit = tables.LinkColumn('dummy_edit', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') class Meta: model = DummyModel attrs = {'class': 'paleblue'} def render_edit(self, record): edit_url = reverse("edit") # Change this properly. return mark_safe('''<a href="%s">Edit</a>''' % (edit_url + '?id=' + str(record.pk))) The render_edit function renders the Edit column with a link to the page where I can edit the record. My urls.py configuration for this page looks as follows: from django.views.generic import TemplateView url(r'^edit/$', TemplateView.as_view(template_name='edit.html'), name='edit'), Finally, the edit.html page uses jquery dialog box and I am just using the demo sample as: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Dialog - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#dialog" ).dialog(); } ); </script> </head> <body> <div id="dialog" title="Basic dialog"> <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p> </div> </body> </html> Now all this … -
Create editable for user User Account
So my question is what should I look for creating a page which will allow user to add some information after the registration. I took a look at Django Profiles, but it requires lower version of Python (2.7), if I'm not mistaken. Another thing is I need to create two types of users - I'm thinking of maybe @permission to implement it, but another point is that I want to include something like checkbox while registration, and if user chooses one type of user, he will be allowed to see default account page for this type of user which he should fill up. I'm running Django 1.10.5 and Python 3.6.0. Thanks in advance. -
Python difflib matching objects
I am trying to use difflib in order to match objects against each other. person.models.py class Person(models.Model): first_names = models.CharField(...) last_names = models.CharField(...) skill = models.ManyToManyField('property.Skill') ... def matching_persons(self): match_list = [] own_skill = self.primary_skill.all() matches = Person.objects.filter(skill=own_skill).exclude(id=self.id) for match in matches: seq=difflib.SequenceMatcher(None, own_skill, matchskill.all()) name = match.first_names + ' ' + matching_candidate.last_names match = {'id': match.id, 'name' : name, 'ratio': seq.ratio()} matches.append(match) return matches property.models.py class Skill(models.Model): skill = models.CharField(...) template.html <tbody> {% for match in object.matching_candidates %} <tr> <td>{{ match.id }}</td> <td><a href="../../../crm/candidate/profile/{{ match.id }}" target="_blank">{{ match.name }}</a></td> <td>{{ match.ratio }}</td> </tr> {% endfor %} </tbody> This already matches persons based on their skills and also gives them a ratio in percent (e.g. 90% match). However the order in which the skills appear in a person matters e.g. ("soccer, basketball" != "basketball, soccer"). Are there any setting I need to change in difflib or should I rater use something completely different to match these skills against each other? -
Why won't my Django form render?
I'm following the guide to upload a file here and my form will not render. When I run it in the shell I also get the error message <unbound method DocumentForm.as_p>. The template page is loading correctly because I am able to see "This is the form page" from the file_upload_form.html. What Do I have wrong? forms.py from django import forms from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document', ) models.py from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage # Create your views here. from .forms import DocumentForm from .models import Document def file_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'src/templates/file_upload_form.html', { 'form': form }) file_upload_form.html (template): {% extends "base.html" %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> This is the form page <p><a href="{% url 'main_db_model:home' %}">Return to home</a></p> {% endblock %} -
PyCharm debug vs django-debug-toolbar
Does the built-in debugger in PyCharm include the same functionality as django-debug-toolbar for debugging Django projects, or do I "still" need it?