Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'bundle' reserved word in django??`
I have a project I am working on and I create a table called bundle. I also have a foreignkey in another table that references the bundle table. When i try to access the foreignkey, it tells me that bundle is a keyword that is reserved. I also tried checklist and get the same error. I looked online and it didnt show that bundle or checklist is a reserved or keyword. can anyone help me with this. Here is the code that I have and is giving me the error. It is the second of the two lines. Thank you. bundles = Bundle.objects.filter(group = currentGroup).all() items = Items.objects.filter(bundle.group = currentGroup).all() File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 695 items = Items.objects.filter(bundle.group = currentGroup).all() ^ -
How to integrate Google API Client library with Django Rest Framework
I'd like to implement authentication between the Android client and Django Rest Framework server. I finally settled on this method. Now I would like to know how to integrate Google's API Client Library with Django Rest Framework. Specifically, how do I create the requests.Request() object in Django Rest Framework? -
Python/Django: How to handle simple search in advanced search engine?
I am working on advance search engine that allow multiple-layered of search(advance search) but I am not sure on how to carry simple search with the search form that contain multiple search fields. E.g: In the form I got a textbox, a dropdownlist that contain several types of fruits and a submit button. The problem is when I decide just to carry a simple search by just simply enter some string into the textbox without choosing the types of fruit and leaving it as the default value " ", when I submitting the form it generated URL: "http://127.0.0.1:8000/result/?q=something&fruit_type=+". Is there a way to remove the "&fruit_type=+" from the URL? <form action="/result/" method="get"> <input type="text" id="search_box" name="q"/> <input type="submit" id="sbm_button" value="SEARCH" class="inputbtn"/> <br /> <select name="Fruits"> <option value=" ">Fruits</option> <option value="apple">Apple</option> <option value="orange">Orange</option> </select> </form> Below is the view.py file: def search(request): if 'q' in request.GET: q = request.GET['q'] fruit_type = request.GET['Fruits'] return render(request, 'result.html', { 'query' : q, 'fruit' : fruit_type, }) It will return the q and fruit_type to result.html with the generated URL which had mentioned above. Is there a way to ignore the Fruits dropdownlist within the form(submitting the form and ignoring the dropdownlist)? Thank you. -
How to setup simple token based authentication in Android?
I want to setup a token based authentication in Android. The way I want/imagine this to work is like this: The Android client makes a POST request to the server together with the token, client_id, client_secret which it retrieved from the Account Manager.. The server reads the token, finds the user associated with the token and processes the POST request. If the POST request arrived without a token in step 2, the server creates the User, a token for the User and sends that token to the client which stores it in the AccountManager for future use. The server will ofcourse, before returning the token to the client, also process the POST request as in step 2. Is that a common technique? That's what I understood this Django Rest Framework article describes. Let me know please if this is the way to go. Otherwise, what do I do? I prefer not to use passwords at all. Why use passwords if the user has a phone with a Google Account? -
Saving entity with many to many self field throws exception
I am trying to provide an Admin interface for Category tree. My Categories are able to have several parents. I use many-to-many self field in order to provide that. Also I have some categories which were created using sql. models.py class Category(models.Model): id = models.AutoField(primary_key=True) active = models.BooleanField() description = models.CharField(max_length=255, blank=True, null=True) title = models.CharField(max_length=255, blank=True, null=False) url = models.CharField(max_length=255, blank=True, null=True) parents = models.ManyToManyField('self', through='CategoryParents', symmetrical=False, blank=True) def save(self, *args, **kwargs): if self.id is None: self.id = Category.objects.latest('id').id + 1 super(Category, self).save(*args, **kwargs) def __str__(self): if self.description is not None: return self.title + ": " + self.description else: return self.title class Meta: managed = False db_table = 'category' verbose_name = 'Category' verbose_name_plural = 'Categories' class CategoryParents(models.Model): category = models.ForeignKey(Category, related_name='category_id') parent = models.ForeignKey(Category, related_name='parent_id') class Meta: auto_created = True managed = False db_table = 'category_parents' unique_together = (('category', 'parent'),) def __str__(self): if self.parent.id is 1: return self.category.title else: return self.parent.title + "->" + self.category.title admin.py class CategoryForm(forms.ModelForm): parents = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Parents', is_stacked=False, ) ) class Meta: model = Category fields = ('title', 'id', 'description', 'url', 'active') def __init__(self, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) # if self.instance: # self.fields['parents'].initial = self.instance.parents.all() def save(self, commit=True): category = … -
Mathjax does't work in django when linebreaks filter is used in django-template,but renders successfully without this filter
Mathjax does't work in django when linebreaks filter is used in template that is $$ {{text|linebreaks}} $$ doen't work but $$ {{text}} $$ renders successfully . But the problem is it's not responsive hence linebreaks filter is needed. Is there anyway that mathjax can render and be responsive (changes with screen-size) -
Where should I start to make a django website that finds recipes using ingredients, any book or tutorial recommendation ? [on hold]
I am a beginner in python and would like to make a website where you can search the recipes using ingredients. I am a frontend developer. Any recommendations where I should start ? -
Django - update child form as table on parent template
I have a Customer model and each customer has specific products that they buy which stored in the Template model. I have a customer detail view that displays the TemplateForm as a table. I'm trying to edit the existing instances in this table. Because there are multiple products for each customer I'm getting a MultipleObjectsReturned error when trying to load the url. When I remove the instance argument from my form I can see all of the proper template data. Not sure where to go from here. models.py class Customer(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, null=True, blank=True) class Template(models.Model): customer = models.ForeignKey(Customer) product = models.ForeignKey(Product) views.py def browse(request, slug): template_name = 'customer_browse.html' customer = get_object_or_404(Customer, slug=slug) products = Template.objects.get(customer=customer) if request.method == 'POST': form = TemplateForm(request.POST or None, instance=products) if form.is_valid(): return redirect('customers') else: form = TemplateForm(instance=products) return render(request, template_name, {'customer': customer, 'form': form}) html <form method="post"> {% csrf token %} <table> <thead> ... </thead> <tbody> {% for template in customer.template_set.all %} ... </tbody> </table> -
Python/Django =- ModuleNotFoundError: No module named 'restaurants'
traceback (most recent call last): File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'restaurants' -
Django: function not being executed randomly but only sometimes
Working on developing an online game that is based around a user clicking a button and the game timer resetting to 10 seconds if it is already under 10 seconds (like auction sites), setting that user's username as the top user for the game, and using 1 of that user's tokens. The button works almost all of the time, but occasionally when a user clicks the button, a token of theirs will be used, but the timer will not reset to 10 seconds if it is already under 10 AND the top user for the game will not be updated to display their username. Here is the function that handles the button click on the game page. If the user does not have any tokens it will redirect them to the store page. If the user is already the top user or the game is over (game_object.status = 0) then they will simply be redirected back to the same page without a token being played or the game being updated: def game_page(request, game_id): game_object = Game.objects.filter(id=game_id)[0] context = {'game_object': game_object} if request.GET.get(str(game_object.pk)) and request.user.profile.get_tokens() > 0: if game_object.get_top_user() != request.user.username and game_object.status == 1: request.user.profile.use_token() game_object.update_game(request.user.profile.user) # fail safe if … -
Django / Linking User Profile To Models
I've Post and Comment models and a custom User Profile with OneToOneField. I extended the user profile But I couldn't use user profiles or user's username on my templates. I got posts and comments. I want to see which user created posts ... Post and Comment fields are on my blog app. I want to link django user or my user profile with Post and Comment fields. e.g : I want to see User1 : User1 First Post Name User1: User1 Second Post Name User2: User2 First Post Name users.Profile models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile') user_image = models.ImageField(upload_to="blog/assets", default="blog/assets/people-photo.jpg", null=True) birth_date = models.DateField(null=True, blank=True) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) blog.Comment and blog.Post models.py class Comment(models.Model): entry_comment = models.TextField(max_length=160) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') #author = models.ForeignKey(User, default=1) def __str__(self): return self.entry_comment def descendants_comments(self): ct = ContentType.objects.get_for_model(self) childs = Comment.objects.filter(content_type=ct, object_id=self.pk) result = [] for child in childs: result.append(child) return result class Post(models.Model): subject = models.CharField(max_length=20) entry = models.TextField(max_length=160) comments = GenericRelation(Comment) #author = models.ForeignKey(User, default=1) def get_absolute_url(self): return reverse('index') def __str__(self): return self.subject -
Django queryset orderby matching m2m fields
I have a Question model, with m2m relation to Topic, so a Question can have multiple Topics now given a list of Topics, I wanna get the related Questions, ordered by matching level. That means partially topic-matching Question is allowed, but it ranks behind the ones that match all topics. I already have the part to get the questions, but I don't know how to do the ordering. questions = Questions.objects().filter(topics__id__in=topics) questions = questions.order_by(???) -
django very simple login or signup code but is_valid always return false
my simple code.. view.py @csrf_protect def signup(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): <<===== Always is_valid return false new_user = User.objects.create_user(**form.cleaned_data) login(request, new_user) return HttpResponseRedirect('/join_ok/') else: # If is_valid() False then I want see data return HttpResponse(form) <<== print data is no problem else: form = UserForm() return render(request, 'join.html', {'form': form}) join.html <h2>Join</h2> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="join" /> </form> forms.py from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] class LoginForm(forms.ModelForm): class Meta: model = User fields = ['username', 'password'] is_valid() always return False Very basic code. I just want to test login. But there was a problem in the very basic part. -
Initialise formset from queryset
I'm trying to populate forms in a formset from a queryset. forms.py class PickForm(forms.ModelForm): prediction = forms.ChoiceField(choices=PICK_OPTIONS) class Meta: model = Pick exclude = [] widgets = { 'id' : forms.HiddenInput(), 'user' : forms.HiddenInput(), 'match' : forms.TextInput(attrs={'class': 'form-control', 'readonly' : 'True'}), 'prediction' : forms.Select(attrs={'class': 'form-control'},) } UserPickFormSet = inlineformset_factory(User, Pick, form=PickForm, extra=len(matches)) views.py UserPickFormSet = inlineformset_factory(User, Pick, form=PickForm, extra=len(matches)) if self.request.POST: data['picks'] = UserPickFormSet(self.request.POST) else: data['picks'] = UserPickFormSet(queryset=Pick.objects.filter(user=self.request.user, match__in=matches)) return data template <form action="" method="post">{% csrf_token %} {{ picks.management_form }} <table class="table"> <tr><td>Match</td><td>Prediction</td></tr> {% for f in picks %} {{ f.as_table }} {% endfor %} </table> <input type="submit" value="Submit Predictions" > </form> This produces a formset for each record in the queryset but doesn't fill the forms with the current data. What am I doing wrong? -
Javascript: Add the same form multiple times if the user requests it
I am building a website where a user can create a survey. One of the things I want to be able to do, is to allow the user to create as many questions as they want to for each survey they want to. The way I plan on doing this is having a base form on the html page, and then, using javascript, have an add button which will add the form over and over again, as the user repeatedly presses the 'add question' button. How would I go about this? -
How to handle associating a User with a Model?
I'm building an app that uses Django (well the Django Rest Framework) and I'd like to associate a User with a my Model as runtime. How do I achieve that I'm not 100% clear. So, I'll receive a POST request in my View: if request.method == 'POST': .... serializer.save() And then, the flow will go to the post save receiver: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) I suppose that in my Model, I'll need a reference to the User. But how do I get a new or existing User and associate the new element with that User in the View? I suppose this will be my Model: class UserPostData: some_info = models.DateField() user = models.OneToOneField(User) But how do I handle associating the User with the Model I just saved in the view? if request.method == 'POST': .... serializer.save() -
Deploying Django to AWS Elastic Beanstalk
I'm attempting to deploy Django 1.11 and Python 3.6 to Elastic Beanstalk following this tutorial: https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/ However when I go through the steps to create my instance and try and run eb open. The webpage that opens gives me a 404 url not found error. Some tutorials said I needed to create a directory .ebextensions with a django.config file in so I've done that and linked the path of my wsgi.py file but the problem persists. I was wondering if anyone had any idea of what may be causing this problem as I'm entirely new to AWS so unsure of what it could be. Thanks -
How to use token based authentication in Django Rest Framework
I want to implement token based authentication in my application that uses Django Rest Framework and a Android client. The way this works, as far as I understand, is I need to send the client ID and the client secret to the API end point together with the access token. The access token is gotten from the Django Rest Framework as so: Token.objects.create(user=instance) I have a few question that I'd like to clarify to glue all of this together. How do I handle the client ID and the client secret in Django Rest Framework? How do I associate the user with the model that the user have saved? The user will be sending me pictures, and for each picture, I'd like to associate the User with the Picture. How do I send back the token to my Android client to save it in the Android's Account Manager? How do I store the client ID and the client secret in Android? I can't simply store them as a String. Someone could find the string literal in the APK. -
Django KeyError after returning instance (Serializer)
im facing following problem: Im inserting a Cantonment (Household) into my database with an address and a accomodation (Sofa/Bed ...). Everything works fine (inserting) but after everything is correctly inserted the returned instance of the created object (cantonment) is throwing an error: Got AttributeError when attempting to get a value for field accomodations on serializer CantonmentCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Cantonment instance. Original exception text was: 'Cantonment' object has no attribute 'accomodations'. The query used is in this example ( Query used ). As i said insert is working, but returning the instance is throwing an error. Adding source='accomodation_set' would probably work for showing the correct output, but then i cannot insert any data. Is there a way i can use a different serializer for returning an instance (which is created). If you need more information ( models ) tell me :) Appreciate your help class CantonmentCreateSerializer(serializers.ModelSerializer): address = AddressSerializer() accomodations = AccomodationSerializer(many=True) # other profile class Meta: model = Cantonment fields = ('id','user','name', 'description', 'type', 'stay_type', 'geom', 'address', 'accomodations') read_only_fields=('id', 'user',) def create(self, validated_data): with transaction.atomic(): # Create Cantonment first and link it to the address and … -
Django UpdateView doesn't get the values of the object I want to edit
So I'm creating a django website and I have a button of edit. After the edit is clicked there is pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. for example- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): … -
CommandError: You appear not to have the 'psql' program installed or on your path
I'm using Windows, no virtualenv. I have psycopg2 installed with Pip, and the latest version of PostgreSQL installed as well. When I run ./ manage.py dbshell, I get the following error: CommandError: You appear not to have the 'psql' program installed or on your path. When I run ./ manage.py dbshell psql, I get this: usage: manage.py dbshell [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] manage.py dbshell: error: unrecognized arguments: psql I have read a few other posts on this error like this but I don't understand why this is not working for me. I have all the settings properly configured, and all the proper apps installed. My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '********', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
how do I make django and tornado communicate with each other
I have a social networking kinda an app in Django and I wanna integrate real-time notifications and messaging functionality in my app. my friends could build a tornado app but I wanna basically connect them together (my guess are I have to make a REST API correct me if I'm wrong) how can I do these kinda tasks from Django Authenticate automatically to a WebSocket(tornado) as I logged in my django app import all of my friends send tornado signal to send notifications if the user didn't receive a message things like that how do I do stuff like that. (BTW I don't wanna use django channels as it's fairly new) -
Python recognize classes as modules in import
I have a Django app with following structure: my_app --models ----__init__.py ----MyModelClass.py --utils ----__init__.py ----MyBase.py --admin.py --urls.py My models __init__.py file contains: from .MyModelClass import MyModelClass # noqa My utils __init__.py file contains: from .MyBase import MyBase # noqa Then when I tried to import MyModelClass in MyBase file with this: from ..models import MyModelClass or this: from apps.my_app.models import MyModelClass I got module instead of class. And then I should use: MyModelClass.MyModelClass.objects.all() P.S And even I got error when tried with this: from ..models.MyModelClass import MyModelClass -
Django form field update
I have a Django form that lets users choose a tag from multiple tag options. The problem I am facing is that even when the tag list gets updated, the model form does not get the updated tag list from database. As a result, new tags do not appear in options. Here is my code: class EnglishTagForm(forms.Form): tag_choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter( agentId=Agent.objects.get(name='English Chowdhury'))] tag = forms.CharField(widget=forms.Select(choices=tag_choices, attrs={'class':'form-control'})) def __init__(self, *args, **kwargs): super(EnglishTagForm, self).__init__(*args, **kwargs) self.fields['tag'].choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter( agentId=Agent.objects.get(name='English Chowdhury'))] This form is being instantiated in view. My question is what changes should I do so that tag_choices gets updated from database on every instantiation. -
How to use Android auth token for DRF?
I want to use tokenbased authentication with Django Rest Framework and Android. I think I need to get the Auth token from Android and then send it to Django Rest Framework. But in the docs it says that I need to generate the token: token = Token.objects.create(user=...) print token.key How do I use the token send to me by the Android client: conn.setRequestProperty("Authorization", "OAuth " + token); In Django Rest Framework it says: For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: Does that mean if I do: conn.setRequestProperty("Authorization", "Token " + token); and send that to the server, Django Rest Framework will associate the token with the user automatically?