Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Unresolved attribute reference 'objects'
In models.py I have class Memo: class Memo(models.Model): MonthName = models.ForeignKey(Months, on_delete=models.CASCADE) ProjectName = models.ForeignKey(Project, on_delete=models.CASCADE) Hours = models.IntegerField(blank=True, null=True) # ProjectManager = models.ForeignKey(ItEmployee, on_delete=models.CASCADE) def __str__(self): return str(self.MonthName) + ' - ' + str(self.ProjectName) In views.py I am getting warning Unresolved attribute reference 'objects' for class Memo: from django.http import HttpResponse from History.models import Memo def memos(request): all_memos = Memo.objects.all() html = '' for memo in all_memos: url = '/memo/' + str(Memo.MonthName) + '/' html += '<a href="' + url + '">' + Memo.ProjectName + '</a><br>' return HttpResponse(html) -
Django: FieldError: Invalid field name(s) for model
When i'm trying to use update or create query it's gives error FieldError: Invalid field name(s) for model Here it is my models.py class Mymodel(Base): name = models.CharField(max_length=50) query = models.TextField() args = models.TextField() server_details = models.TextField() Now I want to update or create query of Mymodel Here it is my data dict kwargs={ "name": "PQR", "query": "ABC", "args": "{}", "server_details": "XYZ" } Here I'm trying to do obj, created = Mymodel.objects.update_or_create( id=params.get('id'), defaults=kwargs ) When I'm trying to update_or_create its gives following error FieldError: Invalid field name(s) Mympdel: 'name', 'query' -
Update View showing blank forms when I try to edit in my Django website
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. 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): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts … -
Ajax making a get after a post in Django
I am trying to update a product list using Ajax once a user submits a new product. I have an Ajax get once the page loads (to initially load all the products and populate a <li> with them) and require this function once again when a user adds a product, so it is displayed instantly without refresh. Currently upon success of ajax post (form completion and submission) in the success: function() I call the following (get/ being a URL where I return a JsonResponse) $.ajax({ type: 'POST', url: 'new/', data: product_data, success: function () { $.get("get/", function(data) { $.each(data, function(i, product) { console.log("i:" + i, "product: " + product) }); }); } }); This returns me the objects I require however I only want to append the last object to the <li> in my HTML or I'd be adding another list of duplicates. How could I do this effectively? -
Django Admin: How to enable the use of the CustomManager() of the related to the inline model?
class MainModel(models.Model): pass class ThirdModel(models.Model): objects = CustomManager() def __str__(): # Here I use the to_attr defined in the CustomManager() class ChildModel(models.Model): main_key = models.OneToOneField(MainModel) content = models.ManyToMany(ThirdModel) ChildModelInline(admin.TabularInline): model = ChildModel MainModelAdmin(admin.ModelAdmin): model = MainModel inlines = (ChildModelInline, ) In the admin page, when I add a new ThirdModel using the default SelectMultiple widget of the ChildModelInline in the MainModelAdmin instance, apparently, the CustomManager() of the ThirdModelis not used. Details of the ThirdModel: The CustomManager has a Prefetch() with to_attr attribute. The calls to this attribute in the __str__() method raise an AttributeError. The above happen only when I save the added new entry. Otherwise, the names of the available instances appear without errors in the widget. -
Django Get and Filter
I have a design question on django. Can someone explain to me why the Django ORM 'get' doesn't return a queryset? To the best of my understanding, a queryset should/is the result of a db query. With that logic, isn't a get query a queryset? Also, from my research towards this question, I found out the get query calls the model manager while the queryset doesn't. Is there a reasoning behind all of this? -
Django Middleware breaking form submission?
When I add middleware, the forms on the page with templateresponse stop working: submission causes loading for several minutes, and then results in a load-balancer error. The form, process_img method, and bot view all work exactly as expected when the middleware isn't defined in settings.py. The code: In settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' 'polls.views.ExampleMiddleware' ] MIDDLEWARE_CLASSES = [ 'polls.views.ExampleMiddleware' ] Middleware definition in views.py: class ExampleMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): if 'right' in request.POST: response.context_data['response'] = 'Sweet, thanks!' elif 'wrong' in request.POST: response.context_data['response'] = 'Awww, sorry' return response Relevant view in views.py: def bot(request): img_form = ImageUploadForm() context = {'img_form':img_form} if request.method=='POST': img_form = ImageUploadForm(request.POST, request.FILES) if img_form.is_valid(): myfile = request.FILES['image'] context = process_img(myfile) return TemplateResponse(request, 'polls/bot.html',context) return TemplateResponse(request, 'polls/bot.html',context) Details: Python 3.5, Django 1.11, hosting on Python anywhere. What's breaking the form submission and how do I fix it? -
Django Pyrebase
I am trying to connect my Django website with firebase. There is not enough material for that,luckily I got this https://github.com/thisbejim/Pyrebase but I am not able to understand where to write this code .I am newbie to Django. I have written this code in pyrebase.py file: import pyrebase config = { apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo", authDomain: "minor1-5e62c.firebaseapp.com", databaseURL: "https://minor1-5e62c.firebaseio.com", projectId: "minor1-5e62c", storageBucket: "minor1-5e62c.appspot.com", messagingSenderId: "69802125895" }; firebase=firebase.initializeApp(config); and when I am running it on python terminal,I am getting this error: Traceback (most recent call last): File "D:\Django2\mysite1\personal\dd.py", line 4, in apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo", NameError: name 'apiKey' is not defined I have my project evaluation on 13th November . Someone please help me. -
Return all foreign keys used in this queryset
I'm struggling to explain what I want to do (hence I am unable to actually find a post about this) so hopefully someone can help me out. I have couple models and all are tied to the Product model class Product(models.Model): category = models.ManyToManyField(Category) collection = models.ForeignKey(Collection) item_type = models.ForeignKey(ItemType) colour = models.ManyToManyField(Colour) product_name = models.CharField(max_length = 250, default='') product_name_pl = models.CharField(max_length = 250, default='') last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) product_comment = models.CharField(max_length = 300, default='', blank=True) product_comment_pl = models.CharField(max_length = 300, default='', blank=True) display_order = models.PositiveIntegerField(blank=True) def __str__(self): return self.product_name e.g. class Collection(models.Model): collection_name = models.CharField(max_length = 250) slug = models.SlugField(unique=True, default='m') description = models.TextField(blank=True) image = models.FileField(upload_to='images/collections/', blank=True) collection_type = models.ManyToManyField(CollectionType) display_order = models.PositiveIntegerField(default=999) def __str__(self): return self.collection_name or class Colour(models.Model): colour_name = models.CharField(max_length = 250) slug = models.SlugField(unique=True, default='m') description = models.TextField(blank=True) image = models.FileField(upload_to='images/types/', blank=True) def __str__(self): return self.colour_name The idea is when I retrieve a set of products by using the Collection, I want to have a list of available colours in the current selection and maybe a count of how many of each product each colour has. What I'm mostly looking for is a point towards a correct direction in the queryset … -
how to set a method in Django rest framework's veiwSet not require authentication
I have viewset like below : from rest_framework import viewsets from paas.serializers import UserSerializer import logging logger= logging.getLogger(__name__) class UserViewSet(viewsets.ViewSet): def list(self,request): pass def create(self,request): logger.info(request.data) current_user = UserSerializer.create() also, I use the DRF Token based authentication in my code. how can I simply say that this create method don't require authentications? as you know after implementing authentication with the token, all request's should have Token in header's, and any request dosn't have will get 403 error.