Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to start a thread and instantly get back to the main code?
I have a simple view and a complicated function inside of it: def addWord(request): def calculate(): <code> form = WordCreationForm(request.POST or None) if form.is_valid(): calculate() form.save() form = WordCreationForm() return render(request, 'add_word.html') I need calculate() to run independently. I don't need any callbacks. I just want to start it, and then immediately get back to saving the form. So, I did this: import threading def addWord(request): def calculate(num): <code> form = WordCreationForm(request.POST or None) if form.is_valid(): threading.Thread(target=calculate, args=(request.POST['num'],)).start() form.save() form = WordCreationForm() return render(request, 'add_word.html') But in this case, form still won't be saved and rendered again untill calculate() is done. So, what is the best way to start calculate() asynchronically? -
What is the use of PYTHONUNBUFFERED in docker file?
I was watching a tutorial to dockerize my django application. I did not understand why we use PYTHONUNBUFFERED as environment variable in DockerFile. Can you please help? Thanks -
make footer fixed on the bottom with tailwindCSS
I use tailwindCSS and confront a problem with make footer. base.html <body> {% include "partials/nav.html" %} {% block content %} {% endblock %} {% include "partials/footer.html" %} </body> footer.html <footer class="w-full h-64 bg-gray-900 static bottom-0"> {% load static %} <img src="{% static "images/logo_white.png" %}" width="70px"> <p class="text-white"> &copy~~~~~~</p> </footer> i tried static,absolute,fixed,relative... but .fixed cover the content block and relative make footer going upside. or .mb-0, .bottom-0 doesn't work. is it possible make footer fixed on the bottom? -
Create new post
I have a blog website and I have New Post button this is my post list function def PostList(request): post_list = Post.objects.all() context = {'post_list' : post_list} return render(request, 'blog/home.html', context) this is my post detail function def post_detail(request, slug): post_detail = Post.objects.get(slug=slug) context = {'post_detail' : post_detail} return render(request, 'blog/post_detail.html', context) and I want to create this function but I dont know how def post_new(request): post_new = Post.objects.get() Can anyone help me I am new to django -
how to create custom authentication for my django app my model in django
i have a model(name:coders) in my Django app model name coders username password email profile_pic so on how i can create authentication for this model in Django any idea's welcome -
dynamic timeline - passing content django
I want to create a dynamic timeline like of stack overflow's: so for that , I have template like this: <body> <div class="timeline"> <div class="container left"> <div class="content"> <h2>2017</h2> <p>Lorem ipsum..</p> </div> </div> <div class="container right"> <div class="content"> <h2>2016</h2> <p>Lorem ipsum..</p> </div> </div> </div> </body> As you can see this yields a static timeline with some css. Now, I have a bunch of blogs and I want to show those blogs in the user's profile page as a timeline filtered by date. So it should be like whenever the user creates a blog, that blog should occupy a place in the timeline based on the date posted. So for this, firstly I may have to pass all the blogs for a user as a context in the template with some query which I have already done. Now in the template, I have a context object named 'blogs' which basically is all the blogs by a specific user. Now, to pass those blogs as content in the timeline, what can I do? If I do plain for loop like this: {% for blog in blogs %} <div class="container left"> <div class="content"> <h2>2017</h2> <p>Lorem ipsum..</p> </div> </div> {% endfor %} that doesn't … -
MultiValueDictKeyError at /profiles/adminKaLogin/ Django
So I am trying to create a site which takes in input of vendor choices and time period from the user, and accordingly fetches data from the models. The first two radio buttons are to select the vendor, and the remaining are for specifying the time frame. I am getting the above mentioned error while doing the same. Given below are the relevant files: views.py: if 'form1' in request.POST: vendor_choice = request.POST["inlineDefaultRadiosExample1"] date_choice = request.POST["inlineDefaultRadiosExample1"] x = employee.objects.get(name = request.user) y = vendor.objects.get(id = vendor_choice) if date_choice == 1: d = transaction.objects.filter(ven_id=y, emp_id = x, timestamp__gte = datetime.date.today() - datetime.timedelta(days=30)) elif date_choice == 1: d = transaction.objects.filter(ven_id=y, emp_id = x, timestamp__gte = datetime.date.today() - datetime.timedelta(days=60)) else: d = transaction.objects.filter(vendor_id=y, emp_id = x, timestamp__gte = datetime.date.today() - datetime.timedelta(days=180)) return render(request, 'profiles/adminKaLogin.html', {'model':d}) Models.py class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(("Date"), default=datetime.date.today) The HTML: <form method="POST" action="/profiles/adminKaLogin/"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInline1" name="inlineDefaultRadiosExample" value="1"> <label class="custom-control-label" for="defaultInline1">Vendor 1</label> </div> <!-- Default inline 2--> <div class="custom-control … -
Django RuntimeWarning: DateTimeField received a naive datetime
I'm dockerizing my Django application. Since I changed my database from SQLite to Postgres the migration fails and I get this error: RuntimeWarning: DateTimeField Posts.created_at received a naive datetime (2020-01-19 14:26:30.893128) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.CannotCoerce: cannot cast type time without time zone to timestamp with time zone LINE 1: ..." TYPE timestamp with time zone USING "created_at"::timestam... I have searched the other issues and tried this fix https://stackoverflow.com/a/20106079/7400518 I was using datetime.now() then I changed it to timezone.now() but I'm still getting the same error. This is the related lines from models.py from django.utils import timezone class Posts(models.Model): created_at = models.DateTimeField(default=timezone.now(), blank=True) -
ERROR in creating the relationship between a person and it's relationship
error:matching query does not exist. hello or good evening in creating the customer account (profile) I had this problem by creating the link between a person and these relationships (friend) this is the code link thank you for your help views.py from video.models import Post, Friend class HomeView(TemplateView): . . def get(self, request): . friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() var = {..., 'friends': friends} def change_friends(request, operation, username): friend = User.objects.get(username=username) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('home:home') urls.py path('connect/<operation>/<username>/', views.change_friends, name='change_friends') models.py class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete=models.DO_NOTHING) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) html code <h2>friends</h2> {% for friend in friends %} <a href="{% url 'accounts:profile_username' username=user.username %}"> <h3>{{ friend.username }}</h3> </a> {% endfor %} -
Cannot create symbolic link in ngnix /site-enabled/?
I'm trying to deploy a django project using ngnix but i can't create symbolic link of my configuration file at /etc/ngnix/sites-available/webmash to /etc/sites/sites-enabled. I use following command:- sudo ln -s /etc/nginx/sites-available/webmash /etc/nginx/sites-enabled which produces following error:- ln: failed to create symbolic link '/etc/ngnix/sites-enabled': No such file or directory -
How to combine django model with function based view
I have a django view in which I wish to read a cookie urls.py: path('', views.home, name='home'), views.py: def home(request): context = {} url = 'home/home_page.html' cookies_allowed = request.COOKIES.get('cookies_allowed', '0') return render(request, url, context) models.py: class HomePage(Page): template = "home/home_page.html" banner_title = models.CharField(max_length=100, blank=False, null=True) But, of course, the render function does not contain any context data and I get a blank page. How do I get the data defined in the model into context? -
Modifying serializer but losing the ability to put/post
I need to modify my Django project which is acting as an api. I used this project in order to build it. Modified project is here on github. Here is what i have. I can delete, put and post datas without any trouble. Problem i have is i want datas instead of url, so i modified the project by adding to AppSerializer constants = ConstantsSerializer(many=True, read_only=True) regex = RegexSerializer(many=True, read_only=True) (code is below) to be as here. As you can see, i lose the ability to put/post/delete datas coming from some tables. I'm trying to read https://www.django-rest-framework.org/api-guide/relations/, but i don't understand how to do. May someone please help me on this ? Regards, Pierre Serializers.py from django.contrib.auth.models import User, Group from .models import Regex, App, Const, Constants from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] class RegexSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Regex fields = ['url', 'key', 'value', 'content', 'created_on', 'author'] class ConstSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Const fields = ['url','key', 'value'] class ConstantsSerializer(serializers.ModelSerializer): class Meta: model = Constants fields = ['url','key', 'value'] class AppSerializer(serializers.HyperlinkedModelSerializer): constants = ConstantsSerializer(many=True, read_only=True) regex = … -
Why is my event listener unbinding from my button after two clicks?
I've got an event listener on a like button that should stay bound to it after any amount of clicks but after the second time clicking, it unbinds its self. There is a script on the main html doc and one on the replacement doc (because the script doesn't see the replacement). I've tried passing the whole script tag to the html through context but that didn't work, tried passing just the path to the script tag but that didn't work, tried adding addEventListener() on success in the ajax functions but that didn't work either. Can anyone tell me why it unbinds its self? I'm new to JavaScript/JQuery so all of this is new to me and I don't understand how it unbinds its self. The code is fairly long so I apologize in advance handle_likes.js (snippet) $(".like-post-btn").on('click', function(){ console.log("Thing was clicked!"); // sanity check if ($(".like-post-btn").val() == "not-liked") { like_post(); } if ($(".like-post-btn").val() == "is-liked") { unlike_post(); } }); function unlike_post(){ console.log("Unlike post called...") // sanity check console.log("Test JQuery unlike post.."); console.log($("#post_id")); console.log($("#post_type")); $.ajax({ url: "posting/unlike_post/", data: { post_id : $("#post_id").val(), post_type : $("#post_type").val() }, success: function(data) { $('.like-stuff').html(data); }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! … -
Is it possible to get number of how many requests were received via throttling classes in django rest framework?
As title says, is it possible to get number of how many requests were received via throttling classes in django rest framework? For more information, for throttle classes I am using UserRateThrottle, for authentication classes I'm using TokenAuthentication, for permission classes I am using IsAuthenticated. I only have been able to get the limit number for example 1000/day. I did try to find the solution on google but I am out of luck! Thanks! -
Is there a way of getting the response.content for a post request in Django testing?
This article - https://www.dev2qa.com/how-to-use-django-test-client-to-test-views/ - suggests that we can access response.content to get the content of the response after sending a post request. However I've just created a dead simple project and app to test this but I just get an empty byte string. What am I missing? Models - class Note(models.Model): text = models.CharField(max_length=30) Views - class CreateNote(CreateView): model = Note fields = '__all__' success_url = reverse_lazy("index") def index(request): return HttpResponse("Hello!") Tests - class NoteTest(TestCase): def test_createNote(self): response = self.client.post('/notes/create', {'text': 'hello world!'}) print(response.content) # just returns b'' -
How to redirect to another url after detect face in django
The overall idea is that I want to redirect from a page to home page after detect face in Django framework. Tried to manipulate the return but failed to do so and no have any affect. This is views.py in django. import cv2 import threading from django.views.decorators import gzip from django.shortcuts import render, redirect, render_to_response, HttpResponse from django.contrib.auth import authenticate, login as _login, logout as _logout from django.http import JsonResponse,HttpResponseRedirect from django.http import StreamingHttpResponse def handler404(request): response = render_to_response('404.html', {}) response.status_code = 404 return response def home(request): if not request.user.is_authenticated: return redirect(login) return render(request, "home.html" ) class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0 + cv2.CAP_DSHOW) self.video.set(3, 640) # set video widht self.video.set(4, 320) # set video height # Define min window size to be recognized as a face minW = 0.2*self.video.get(3) minH = 0.2*self.video.get(4) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame minW = 0.2*self.video.get(3) minH = 0.2*self.video.get(4) face_cascade = cv2.CascadeClassifier('static/haarcascade_frontalface_default.xml') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale( gray, scaleFactor = 1.3, minNeighbors = 4, minSize = (int(minW), int(minH)), ) for (x,y,w,h) in faces: cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] if any(map(len, faces)): image=0 return image else: ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def … -
graphql how to get my only query and not an object kind
j'ai creer fichier graphql .gql dans lequel se trouve ma query const query = require("@/hello.gql"); by doing console.log (query) it gives me a kind object. Please do we do so that he only returns my request? Thank you in advance! -
Django Admin - when editing user his password is also updated
I am using custom User model and Django Admin - when I update user via the admin, it screws up the password and saves it in plain text instead of encrypted (I have to type the password in the form, the field is required). What should I do if I want to be able to edit the user without password at all? I read Django admin. Edit user and leave password unchanged but I do not understand the answer - I do not have any code for the admin in the views. models.py: class User(AbstractUser): class Meta: db_table = 'app_user' allow_emails = models.BooleanField(default=False) accept_privacy_policy = models.BooleanField(default=False) email = models.EmailField(unique=True) settings.py: AUTH_USER_MODEL = "app.User" admin.py class UserAdmin(admin.ModelAdmin): list_display = ["username", "email", "allow_emails", "accept_privacy_policy", "date_joined", "is_staff", "is_superuser"] -
django template just reloads when clicking a link pointing to another template
the template home in my django contains a url pointing to another page but when clicking this link , the home template just reloads here is the code for the urls.py, views.py and home.html this is urls.py from django.conf.urls import include, url from django.contrib import admin from pizza import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'',views.home,name='home'), url(r'order/',views.order,name='order'), ] this is views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'pizza/home.html') def order(request): return render(request,'pizza/order.html') this is home.html <h3> Nandias Garder </h3> <a href="{% url 'order' %}"> order a pizza</a> -
Django error stating model field not defined
So I am trying to create a django view where retrieval is done on the basis of past number of months for the current logged in user, as selected by him/her in the radio choices. But I am facing an error stating that one of my model fields 'timestamp' is not defined. Also, I am a bit confused as to how to print the retrieved model in the html. Given below are my files: html: {% if model %} <table> <thead> <tr> <th style = "padding: 20px;">Vendor ID</th> <th style = "padding: 20px;">Employee ID</th> <th style = "padding: 20px;">Debit</th> <th style = "padding: 20px;">Credit</th> <th style = "padding: 20px;">Time of transaction</th> </tr> </thead> <tbody> {% for i in model %} <tr> <td style="text-align: center;">{{ i.vendor_id }}</td> <td style="text-align: center;">{{ i.emp_id }}</td> <td style="text-align: center;">{{ i.debit }}</td> <td style="text-align: center;">{{ i.credit }}</td> <td style="text-align: center;">{{ i.timestamp }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <p>There are no active transactions!</p> {% endif %} Views.py if 'form2' in request.POST: d = {} date_id = request.POST["groupOfDefaultRadios1"] x = employee.objects.get(name = request.user) if date_id == 1: d = transaction.objects.filter(emp_id = x, timestamp = datetime.date.today-timestamp(days=30)) elif date_id == 2: d = transaction.objects.filter(emp_id = x, … -
Getting if a user is followed by logged in user, not working
I have a user following system that works well until I try to get info if I am following the user, but it just does not work. Here is a sample of the code. what is wrong-----> in the serializers.py of the user, I am trying to get a check if the user follows the current user he is checking. I tried to set it to give one of 3 responses. (Myself, not following, true or false). I am doing this in the user serializer so on the api can display some things based on the value. some things to note about how follow and unfollow works in this app------> the status plays a huge role here, there are three statuses, for now, followed, unfollowed, and blocked. When the user follows, the status is set to "followed" upon creation, when unfollowed, the user is not deleted but instead the status changes to "unfollowed", it was designed like this to save more data like time unfollowed and the rest. what happens when I run the code below-----> when I run the code, it recognizes myself when I view my profile and returns the appropriate message, but when I am viewing a … -
Django Rest Auth password reset link contains html codes
I am using Django REST-Auth for user registration. All works fine except for the fact that the password reset link contains "%20" and "%0A" html codes which yield the token not usable without manually adjusting it before POST. Sample link from the email received: http://127.0.0.1:8000/password-reset/confirm/MTY0MjM0MGMtNGEyMi00ZmY5LWE3YzgtNDdiOGM2M2ViYzIy/%20%0A%20%20%20%20%20%20%20%205d9-2e76cc7a3bc99cf6f1ed/ I've tried overriding the PasswordResetSerializer etc. but nothing so far has helped to resolve the issue. Package versions as follows. Django 3.0.2 django-rest-auth 0.9.5 djangorestframework 3.11.0 Anyone know where this is coming from and how to fix it? -
Django; Can't display on main page notes from admin page
I'm creating my first Django notes app and I'm trying to insert and display notes on the main page. Unfortunately I managed only how to insert them in data base, but I can't display them on the main page. Here is my views.py file: from django.shortcuts import render, render_to_response from django.template import RequestContext, loader from django.http import HttpResponse from .models import Note from .forms import NoteForm def home(request): notes = Note.objects template = loader.get_template('note.html') form = NoteForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() context = {'notes': notes, 'form': form} return render(request, 'note.html', context) And here is my html file: <link href="http://codepen.io/edbond88/pen/CcgvA.css" media="screen" rel="stylesheet" type="text/css"> <style> body {<br /> background: rgba(222,222,222,1);<br /> margin: 20px;<br /> }<br /> </style> <h1>Notes App</h1> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <td>&nbsp;</td> <input type="submit" value="Add note"> </form> I'm trying to make the app from this tutorial: https://pythonspot.com/django-tutorial-building-a-note-taking-app/ -
sum amount field in model using another model in django
i have three models : User, Campaign and Donation. Donation model has donation amount, donated by each user against each campaign. Campaign model class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # this is many to one relationship, on_deleting user, profile will also be deleted campaign_title = models.CharField(max_length=200, blank=True) Donation model class Donation(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) # this is many to one relationship, on_deleting user, user's donation details will be set to NULL campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING) donation_amount = models.IntegerField() views.py file def landing_page(request): # campaigns = Campaign.objects.all().order_by('-id') campaigns = Campaign.objects.all().order_by('-id') ////DO SOMETHING HERE TO SHOW TOTAL DONATION AGAINST EACH CAMPAIGN//// return render(request, 'core/landing_page.html',{'campaigns':campaigns}) Using the current views.py file, I'm able to display all the campaigns, how do i pass the total donation against each campaign to the html file? -
ModelChoiceField returns an object from a model but can't figure out how to then edit that object in database
I hope I can explain this as my brain is in a twist now. This is my form. It is deployed as a formset. Forms.py: class ReconciliationForm(forms.Form): transaction = forms.ModelChoiceField(queryset=Transaction.objects.filter(reconciled_type__isnull=True),required=True) choices_groupby = 'coa_sub_group', empty_label="Expense") store = forms.CharField(required=False) description = forms.CharField(required=False) ignore = forms.BooleanField(required=False) In my views.py I want to edit a field in the Transaction that the user selected in the form. When I look at whats inside the transaction field using logger.warning(form.fields['transaction']) I see there is an object: <django.forms.models.ModelChoiceField object at 0x050D9988>. So I try to edit the object, I get get an error saying the object has no Save() attribute. if formset.is_valid(): for form in formset: if form.cleaned_data['ignore'] == True: logger.warning(form.fields['transaction']) transaction = form.fields['transaction'] transaction.reconciled_type = 'i' transaction.save() messages.success(request, "Monzo transactions successfully added to ledger.")