Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to establish relationship across two different database tables in django
I want to create two database. Each database will store a specific user information.I wanna to establishes one to one, one to many and many to many relationship between these different user's database tables. How these can be done in django any idea thanks in advance -
Django forms - Dynamically update ModelChoiceField Queryset
I want to update a form based on user selection of one field. Here is my models.py models.py class A(Model): text = CharField() class B(Model): a = ForeignKeyField(A) class C(Model): a = ForeignKeyField (A) b = ForeignKeyField(B) Assuming we use ModelChoiceField in forms.py. Now if a user is adding a C object, and he selects an A object, I want to populate B field with queryset=a.b_set. Is there any way to do this in django? Or if I have to use Javascript, is there a best practice as to how to integrate this with django? Thanks -
Select the latest updated comment in the template
I have such a model table class Comment(models.Model): STATUS = ( (1, 'normal'), (0, 'deleted'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) body = models.TextField() # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-date_created',) def __str__(self): return self.body I'd like to select the latest updated comments in the template: {% for comment in article.comment_set.all() %} {% if comment.date_updated is the latest %} {{ comment.date_updated | timesince}} {% endfor %} Is it possible to achieve this in template? -
How to set serializer custom field in create method of Model Serializer?
I'm working with a very simple model, but i'm stuck here. I just want the after creating a User, i sent him a Token. i created a customer serializer field. here is my Serializer class. class UserCreateSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank=True, read_only=True) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = get_user_model() fields = ('id', 'username', 'password', 'token', ) def create(self, validated_data): uname = validated_data['username'] password = validated_data['password'] user = get_user_model().objects.create( username=uname, ) user.set_password(password) user.save() data = self.get_initial() data['token'] = Token.objects.create(user=user) return user here is my CreateAPIView class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] every time when i POST a request to it, it doesn't response me with token, it always gives response without token. { "id": 41, "username": "J.Son", } -
django can't read my regex
i make an app called videos and it works correctly , but i want to make a forked page from videos page url looks like this videos/1,2,3,4,.... but i get a 404 error that says: Using the URLconf defined in newproject.urls, Django tried these URL patterns, in this order: 1. videos/ [name='index'] 2. videos/ ^(?P<quran_id>[0-9]+)$ [name='detail'] 3. admin/ The current path, videos/1/, didn't match any of these. i think the error was in the previous second url and i think that django can't read my regular expression . that is my videos/urls : from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index , name='index'), url(r'^(?P<quran_id>[0-9]+)$' , views.detail , name = 'detail'),] thanks to read -
check if a value from object has a character
Im testing how to check if a string has a character " or + and in this case i dont create a backlink for example this 2 samples are wrong "this is a category linked" << this create a error and this ` "+ tutorial" i need tutorial or This is a category linked without the <a ahref> atributes So i want check if a string contains " or + i try with on the template html i try {% if topic.category == '"' %}<a href="topic.slug"> {{topic.category}}</a>{%endif%} but this dont work, maybe i need check the string before pass to the template or is other bad aproach? -
Heroku git command get rejected?
Hello guys my " git push heroku master " command get rejected...why? im using w10 power shell..Before rejection it says "no default language could be detected for this app".Please help me guys..heroku error -
Applying Timezone aware to a queryset of objects with datetimes in UTC
I have a simple queryset that returns booking objects with a start_time and end_time in utc and have TIME_ZONE set to UTC in settings which I need. I know how to convert a single date time object from UTC to local but I'm struggling to apply it to my queryset of booking objects, so I can show a booking list to my users in their dashboard in local time. bookings = Booking.objects.filter(contractor=contractor).order_by('-booking_start') -
how to get a data from database of django and display it in html
I am new to django and i am trying to get data from the database based on a key and include it into html this is my models.py from django.db import models # Create your models here. class Car(models.Model): billing_number = models.BigIntegerField(primary_key=True) customer = models.CharField(max_length=100) price = models.IntegerField() purchase_date = models.DateTimeField() company = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.BigIntegerField() mfg_date = models.DateTimeField() shipping_date = models.DateTimeField() This is my forms.py from django.forms import ModelForm from .models import Car class CarForm(ModelForm): class Meta: model = Car exclude = () class CarAccessForm(ModelForm): class Meta: model = Car fields = ('billing_number',) This is my views.py from __future__ import unicode_literals from django.shortcuts import render from django.views.generic import TemplateView from django.http import HttpResponseRedirect, HttpResponse # Create your views here. from .forms import CarForm, CarAccessForm def add_car(request): if request.method == 'POST': # data sent by user form = CarForm(request.POST) if form.is_valid(): form.save() # this will save Car info to database return render(request,'saved.html') else: # display empty form form = CarForm() return render(request, 'add_car.html', {'car_form': form}) def get_car(request): if request.method == 'POST': # data sent by user form = CarAccessForm(request.POST) if form.is_valid(): form.save() # this will save Car info to database return render(request,'saved.html') else: # display empty … -
Sending email with attached file
I'm trying to send an email with an attached file with, it works fine until the attachment part. It gives me an error expected str, bytes or os.PathLike object, not NoneType here is the code am using ; html <form method="post"> {% csrf_token %} <hr> <span style="font-size: 5;" class="text-muted">Message details</span><br><br> <b> Message title: </b><input type="text" id="msgtitle" name="msgtitle"><br><br> <b>Message text:</b><br> <textarea name="msgtxt" id="msgtxt" rows="10" cols="50">Enter text here...</textarea> <hr> <span style="font-size: 5;" class="text-muted">You contact details:</span><br><br> <b>Email: </b><input type="email" id="email" name="email"><br><br> <b>Number: </b> <input type="number" id="number" name="number"><br><br> <input type="file" id="file" name="file"> <button class="btn btn-success" type="submit">Send</button> </form> views.py def class_msg(request, pk): current_ad = get_object_or_404(AdPost, pk=pk) title = request.POST.get('msgtitle') txt = request.POST.get('msgtxt') email = request.POST.get('email') number = request.POST.get('number') file = request.FILES.get('file') if request.method == 'POST': email_msg = "You have recievied this message from Jehlum.com user - Message text (( " + txt + " )) contact details of sender Email: " + email + " phone number: " + number + " ." email = EmailMessage('new message no Jehlum ' + title, email_msg, to=[current_ad.contact_email]) email.attach_file(file) email.send() return redirect('msg_succ') return render(request, 'msg/class_msg.html') -
Python 3 Upgrade: uninstall/reinstall 3.6-3.7 — Now I cannot install Django 2.1: Error msg: [ No module named Django ]
DISCLAIMER: 40 yrs. old and brand new to coding. 100% "self taught" i.e. internet articles/forum-posts. Probably made every n00b mistake available. THE ISSUE: On macOS... Uninstalled Python 3.6 — reinstalled Python 3.7 Uninstalled Django 2 — attempted reinstall of Django 2.1 (fails) My biggest issue right now is that I cannot figure out how to install Django. (See the end of this post for all testing I can think to do) NOTES: After learning Python syntax for a few months, I wanted to branch out into creating a very basic 101 web app. So I started learning Django. I realized I really had no idea where or how any of the moving parts: pip, python, django, PyCharm, the OS, et cetera... work together or where they were even installed. I'd never heard of... packages, package managers, pip, path, or Frameworks. So, I decided to try to do a deep dive and really learn how it all works. The best way I've always done that is to... undo it all, and put it all back together. Issues and Testing: In Terminal: python -m Django --version Results: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3: No module named Django Okay... Try to install Django: pip install Django==2.1 Results: Could … -
Django + Ajax;HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request
I'm creating a project using Django and I have trouble with adapting ajax into it. I am trying to create thumb up button using ajax. And when I pushed the button, this error happens on console. HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. Here is my code. js function thumbUp(entry) { var $entry = $(entry) var id = $entry.data('id') $.ajax({ url:'/thumb_up/entry/' + id, method: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } html is like this. <a data-id="{{ entry.id }}" onclick="thumbUp(this)"><span id="thumb-up">Like</span></a> <script> var csrf_token = '{{ csrf_token }}' </script> views.py is like this def thumb_up(request, entry_id): entry = Entry.objects.get(id=entry_id) thumb_up = ThumbUp.objects.filter(user=request.user, entry=entry) if request.method == 'GET' and not thumb_up: new_thumb_up = ThumbUp.objects.create(entry=entry)#associate with an entry and save it else: thumb_up.delete() return HttpResponseRedirect(reverse_lazy('blog:index')) Actually I already created delete function using jquery and it worked. But for this function, it doesn't work. What is wrong with it and how can I fix this? I'm not familiar with jquery. Anyone who can can give me tips? -
Django, How to render page just for once
I have a view method. def create_new(request): if request.method == "POST": form = PostCreateForm(request.POST) if form.is_valid(): post = Post.objects.create(user=request.user) return render(request, 'baseapp/create_new_second.html', {'form': form, 'post': post}) if request.method == "GET": form = PostCreateForm return render(request, 'baseapp/create_new_first.html', {'form': form}) and It's urls.py, there is re_path(r'^create/new/$', views.create_new, name='create_new'), So, html file is like(It's loading baseapp/create_new_second.html): <form method="post" action=".">{% csrf_token %}<button type="submit" id="create">Create</button></form> If I get baseapp/create_new_second.html by click create button on baseapp/create_new_first.html, there is some creating of Post object. (views.py- post = Post.objects.create(user=request.user)) But after rendered baseapp/create_new_second.html, If I browser page refresh by f5 or refresh button, There maybe recurring of this part: post = Post.objects.create(user=request.user) The result is, that everytime when I refresh the page on 'baseapp/create_new_second.html', new post is generated everytime. How can I prevent it? I want to prevent click f5-new post generation loop. -
Django: multiple admin page consuming same model but different auth mode
I'm trying to build a Django site which is capable of supporting multiple organizations. Each organizations will have its own staff and admin, and each staff can only login to the admin page of their organization, and CRUD data input from staff of the same organization as them. So far, I don't have any problem create multiple admin pages extending AdminSite. But I don't know how I can assign admin/staff account to their own organization so that they can only access their organization's Admin Page and the organization's data accordingly (a staff account now can enter any AdminPage). I'm also not sure what is the best way to filter data for each Admin Page. What I have in mind for now is adding one more 'group' column for my Data Model, and filter the query in each admin page based on the 'group' of the person querying. Any help and insight on this would be appreciated. -
Django - limiting query results resulting TypeError
I inserted 3 items in the database, and the following code can get all the 3 items: Movie.objects.all().order_by('first_show') But when I add the limit to it: Movie.objects.all().order_by('first_show')[0,1] It gives the TypeError exception: Why adding limit causes exception? -
heroku createsuperuser does not create a user. Does not make entry in auth_user table
(cfehome) C:\Dev\cfehome\verojewels>heroku run python manage.py createsuperuser Running python manage.py createsuperuser on ⬢ verojewels... up, run.7672 (Free) Username (leave blank to use 'u48267'): shruti Email address: shruti.karva@gmail.com Password: Password (again): Superuser created successfully. after this also, no entry in auth_user table is made -
'error': 'invalid_request', 'error_description': 'Invalid grant_type parameter or parameter missing'
I am trying to get access_token after getting code from my api provider. Here is my function; def get_token(): params = { 'grant_type' : GRANT_TYPE, 'client_id' : CLIENT_ID, 'client_secret' : CLIENT_SECRET, 'code' : CODE, 'redirect_uri' : REDIRECT_URI } HEADERS = { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } req = requests.post(ACCESS_TOKEN_URL, params=params, headers=HEADERS) result = req.json() print (result) # in order to see it on the console. return result However I am getting this error; {'error': 'invalid_request', 'error_description': 'Invalid grant_type parameter or parameter missing'} What could I do wrong here? -
Not able to served website using Apache server on digital ocean of Django based project
I had served my website on Apache server and it is Django based project. I was able to run my website from one month. Now when i have pulled my repository from github and now it is showing 500 error. When i am activating my virtual environment and i am running python manage.py runserver my_ip_address then it is showing everything proper in terminal but when i am trying to excess in my web browser then it is showing nothing. Then i have tried python manage.py runserver my_ip_address:8080 then it is working properly. When i have checked my apache server error.log|tail then it is showing some error which i am attaching error low below. I am using postgres and when i was pulling my repository for the last time then after python manage.py makemigrations it asked me to give one default time for one of my field and i have provided timezone.now. In last git pull i have changed many things but if there could have error then my python manage.py runserver my_ip_address:8080 in virtual host should not work but it is working properly. I have also restarted the apache server service apache2 restart and i have also used with sudo. … -
How to use Star rating for amp CSS with Django template Tag?
I want to only display the star rating on amp pages as per values available in the database using django template tags. How do I do that as my ratings are float type and also can that code be used for non-amp pages as well. <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script> <style amp-custom> .rating { --star-size: 3; /* use CSS variables to calculate dependent dimensions later */ padding: 0; /* to prevent flicker when mousing over padding */ border: none; /* to prevent flicker when mousing over border */ unicode-bidi: bidi-override; direction: rtl; /* for CSS-only style change on hover */ text-align: left; /* revert the RTL direction */ user-select: none; /* disable mouse/touch selection */ font-size: 3em; /* fallback - IE doesn't support CSS variables */ font-size: calc(var(--star-size) * 1em); /* because `var(--star-size)em` would be too good to be true */ cursor: pointer; /* disable touch feedback on cursor: pointer - http://stackoverflow.com/q/25704650/1269037 */ -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-tap-highlight-color: transparent; margin-bottom: 1em; } /* the stars */ .rating > label { display: inline-block; position: relative; width: 1.1em; /* magic number to overlap the radio buttons on top of the stars */ width: calc(var(--star-size) / 3 * 1.1em); } .rating > *:hover, .rating > *:hover … -
Django in memory sqlite3 with periodically saving on disk
On raspberry pi i have small database ~150KB and i store in it settings of my project. There is a web interface in django, with i can change this settings via channels. Database will be shared between django and my own code to see settings result in real time on GPIO. My code will only read settings from database. Some settings can be changed by html range input, so value will be changing fast and time to update record in database is long. I want database in memory, because time of update will be shorter, but also i need this database local on disk, so when user sudenly restart device, actual settings are saved. Is there any way to save in memory database to file few seconds after user changed something from web? -
How to use OAuth2 with Django's session to authenticate users
I'm building an app with React and Django, and I'm mainly using Django to respond with JSON to AJAX requests, after processing some data. I'd like to also use it to authenticate users with a variety of social media strategies. I went through the Google+ OAuth2 guides and have got to the stage where I am getting access tokens and all the other relevant information. But I'm not sure how to make this work with Django's session to authenticate users. -
how to convert regular expression of django 1.4 to django 2.0 style path?
url('add/(?P<journal_type>C[DR])/$', add_bank_entry), how to convert this line to django 2.0 version url pattern?what is this C[DR]? -
Configuring Eclipse/PyDev to work with projects on remote server and remote interpreter (workarounds and pitfalls)
I have the following set up: Ubuntu 16.04-64 on host; LXC container running Ubuntu 16.04-64 connected through ssh; several django projects (pure django, django-cms, wagtail cms) located in separate dirs in the container inside /home/ubuntu/dir1, dir2, dir3; each project dir has separate /env folder which holds virtualenv environments (dir1/env, dir2/env, dir3/env). I am trying to set up Eclipse(4.8.0)/PyDev(v.6.4.4.2018...) IDE on host to work on these projects. So far I came to the following solution: created ssh connection to container through RSE tools and imported each project dir (dir1, dir2, dir3) as PyDev Python projects to my workspace; mounted the entire container fs to the local dir on host (using instructions from user https://askubuntu.com/users/700824/pnti, given here https://askubuntu.com/questions/412477/mount-remote-directory-using-ssh#412478); provided path to python interpreters inside env folders and usr/lib/pythonX.X folders (in mounted container fs dir) through Properties > PyDev - Interpreter/Grammar settings. PyDev complains about not finding some *.py files inside /site-packages dir. I've checked manually - all the files seem to be there. "Packages" tab (first tab inside interpreter config window) is empty (cannot load data from provided directories including pip tools). “Libraries” and “Forced builtins” tabs seem to be ok. According to my understanding virtualenv copies all packages to the environment … -
logout request is not working
I've checked on all the questions similar to this and none worked for me, I'm using a very normal route urls.py path('logout/', views.logout_view, name="logout"), views.py def logout_view(request): logout(request) return redirect('home') so when the link is requested as /logout/ it just redirects to home, without loging out -
Django Load testing using locust giving Csrf token error
I am writing a script for load testing for my django application , but I am getting error as : raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" Here is my script: from locust import HttpLocust, TaskSet, task import requests class UserBehavior(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def login(self): response = self.client.get("/") csrftoken = response.cookies['csrftoken'] self.client.post('/check_login/',{'username': 'dum2', 'password': 'dum2@110518#mt'},headers={'X-CSRFToken': csrftoken}) @task(2) def index(self): self.client.get("/") @task(1) def profile(self): self.client.get("/home") class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 5000 max_wait = 9000 Any suggestions on how to rectify this error ?