Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-invitations Transporting data from one model to another model when user signs up
I am using django-invitations and django-allauth and it works quite nicely to invite users to sign up for the website. However, I also assign a team to the users upon invitation. So if user A is on team 1, then when they invite people, those people get assigned to the Invitation model with team 1 as their team assignment. However, when they click on the actual signup link and sign up for the website, I can't seem to pass the team assignment with their signup. Here is the view that I wrote to invite multiple users via a form: @login_required def invite_multi_premium(request): # Get users that are in the company's user database as well as users that have been invited taskly_users = TasklyUser.objects.filter(team=request.user.team) Invitations = get_invitation_model() # I'm afraid this is going to get all invited users, not just those that belong to the company invited_users = Invitations.objects.filter() if request.method == 'POST': form = InviteMultipleEmailsForm(request.POST) print(request.POST) invitees2 = request.POST['emails'] invitees = invitees2.split(', ') for invitee in invitees: Invitation = get_invitation_model() try: invite = Invitation.create(invitee, inviter=request.user, team=str(request.user.team)) invite.send_invitation(request) except IntegrityError as e: print(type(e)) print(dir(e)) return render(request, 'invitations/forms/_invite_multi.html', { # 'message': e.args, # 'company_users' : company_users, # 'invited_users' : invited_users, "form":form }) … -
Why Django is not able to find my ModelName
NameError: name 'student' is not defined This is my Model.py from django.db import models from datetime import date # Create your models here. class Category(models.Model): title = models.CharField(max_length=255, unique=True) class Book(models.Model): title = models.CharField(max_length=255, unique=False) categories = models.ManyToManyField(Category) cover = models.TextField(max_length=100000, blank=True, null=True) author = models.CharField(max_length=255, unique=False) description = models.TextField(max_length=25000, blank=True, null=True) available = models.IntegerField(default=0) class Student(models.Model): student_id = models.CharField(max_length=255, unique=True) firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) department = models.CharField(max_length=255) section = models.CharField(max_length=10) year = models.CharField(max_length=10) class Borrow(models.Model): book = models.ManyToManyField(Book) student = models.ManyToManyField(Student) qty = models.IntegerField(default=0) date = models.DateField(default=date.today) status = models.CharField(max_length=25) I am simply trying to update the data stored in my model named Student And Here is my views.py where all the methods exists from library.models import Book, Category, Student, Borrow from django.shortcuts import render, redirect from django.http import HttpResponse def student_edit(request): studentid = request.GET['sid']; first_name = request.GET['firstname']; last_name = request.GET['lastname']; depart = request.GET['department']; sectn = request.GET['section']; yr = request.GET['year']; print(studentid); print(first_name); print(last_name); print(depart); print(sectn); print(yr); student.objects.filter(student_id=studentid).update(firstname=first_name, lastname=last_name,department=depart,section=sectn,year=yr) Here at last I am getting the error where I am trying to filter my objects of my model Help me to solve this issue I have very less time to solve this Again and Again I am getting … -
How to upload desktop videos on django backend using Ckeditor?
I use Ckeditor and ckeditor uploader on django backend, but there is no any video uploading features. I refer to documentation process of ckeditor . I found html5 video attachment plugin , but it didnt work in my case. Someone could explain me detail way of implementing html5 video in ckeditor step by step . -
Query on Django model to get only one response?
My get endpoint is this: def get(self, request, name, rollno): """Display latest infomation""" schema = models.CredentialOffer.objects.filter(name= name, rollno= rollno) serializer = serializers.CredentialOfferSerializer(schema, many=True) #serializer = self.serializer_class() return Response(serializer.data) Myurl path("records/<str:name>/<str:rollno>", views.TestApiView.as_view()), so it is displaying data with name and roll no i passed. ex: http://127.0.0.1:7000/api/records/lucky/1234 { "id": 1, "name": "lucky", "rollno": "1234", "comment": "test1", "responseStatus": "SUCCESS" }, { "id": 2, "name": "lucky", "rollno": "1234", "comment": "test2", "responseStatus": "SUCCESS" } If their are multiple records, how do i modify view.py to display only one record(record having highest id among them) where id is auto generated field of model -
How to customize django Admin form template
I am new to django world and I want to create Admin model form like as shown below. Cartype Model has - Name - Image - Base Price Add on Model - Name Cartype-Addon Model - Cartype_Id - AddOn_Id - Price -
Running Django Project with apache server windows
How to host django with apache server xampp.I dont want to run project on 127.0.0.1:8000/ instead i want to run it on localhost.I am not being able to download .so file of mod_wsgi. Help us to find it. -
TypeError at /perloandata perloan() missing 1 required positional argument: 'request'
Request Method: GET Request URL: http://127.0.0.1:8000/perloandata?first_name=q&sex01=f&aadhar_no=q&pan_no=q&relation=SAVING+ACCOUNT&amt=10000&noyear=1&address=q&pin=1&city=q&state=Andhra+Pradesh&mob_no=q&email_id=q%40erh.vvv Django Version: 3.0.6 Exception Type: TypeError Exception Value: perloan() missing 1 required positional argument: 'request' 2. models.py from django.db import models # Create your models here. class perloan(models.Model): username = models.AutoField(primary_key=True,blank=True) firstname= models.CharField(max_length=250,blank=True,null=True) secondname= models.CharField(max_length=250,blank=True,null=True) sex = models.CharField(max_length=250,blank=True,null=True) Aadharno = models.CharField(max_length=250,blank=True,null=True) pan = models.CharField(max_length=250,blank=True,null=True) address = models.CharField(max_length=250,blank=True,null=True) pin = models.CharField(max_length=250,blank=True,null=True) city = models.CharField(max_length=250,blank=True,null=True) state = models.CharField(max_length=250,blank=True,null=True) mobileno = models.CharField(max_length=250,blank=True,null=True) emailid = models.CharField(max_length=250,blank=True,null=True) views.py from django.shortcuts import render,redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.core import serializers from .models import perloan Create your views here. def index(request): return render(request,'main01.html') def eduloan(request): return render(request,'eduloan.html') def loansecurity(request): return render(request,'loansecurity.html') def perloan(request): return render(request,'perloan.html') def veichlel(request): return render(request,'veichlel.html') def home(request): return render(request,'home.html') def perloandata(request): username = request.POST.get('name') firstname = request.POST.get('firstname') secondname = request.POST.get('secondname') sex = request.POST.get('sex02') Aadharno = request.POST.get('Aadharno') pan = request.POST.get('pan') address = request.POST.get('address') pin = request.POST.get('pin') city = request.POST.get('city') state = request.POST.get('state') mobileno = request.POST.get('mobileno') emailno = request.POST.get('emailno') data = perloan() #data.name = username data.firstname = firstname data.secondname = secondname date.Aadharno = Aadharno #sdate.pin = pin data.sex = sex data.address = address data.pin = pin data.state = state data.mobileno = mobileno data.emailid = emailid data.save() return redirect('home') urls.py from django.urls import path … -
Django, passing entire object instance when validating through Model validators custom function
I've created a custom validation function for my model in Django as following: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, default=None ) company_name = models.CharField(validators=[validate_url],max_length=50, null=False, blank=False) ... My validate_url function converts the company_name into an url and checks if the same generated url already exist in any profiles. def validate_url(value): url = value.replace(' ', '-') url = url.lower() try: u = Profile.objects.get(url=url) raise ValidationError( 'The company name already exist' ) except Profile.DoesNotExist: pass This seems to work fine when new profiles are created and saved to the database. However when I'm just editing another fields of an existing profile (through admin), it raises me the validation error from the validate_url because it sees himself as already existent value. I would want to pass the user of that instance and check if that user is equal to u.user from u = Profile.objects.get(url=url) and if they are equal it should not raise the error. The problems is that I cannot simply do that: validators=[validate_url(self.user)] Because it gives me the error that self is not defined. How can I pass the user object instance when validating before saving the profile? -
E commerce cart logic - Django
why my code showing error. '''' <script type="text/javascript"> console.log('This is working'); if(localStorage.getItem('cart')==null){ var cart = {}; } else{ cart = JSON.parse(localStorage.getItem('cart')); } $(document).on('click', '.atc', function(){ console.log("the add to cart button is clicked"); var item_id = this.id.toString(); console.log(item_id); if(cart[item_id] != undefined){ cart[item_id] = cart[item_id] + 1; } else{ cart[item_id] = 1; } console.log(cart); localStorage.setItem('cart', JSON.stringify(cart)); document.getElementById("cart").innerHTML = "cart("+ Object.keys(cart).length +")"; }); DisplayCart(cart); function DisplayCart(cart){ var cartString =""; cartString += "<h5>This is your cart</h5>"; var cartIndex = 1; for(var x in cart){ cartString += cartIndex; cartString += document.getElementById("nm"+x).innerHTML + "Qty:" + cart[x]; cartIndex += 1; } $('[data-toggle="popover"]').popover(); document.getElementById("cart").setAttribute('data-content',cartString); } '''' it showing following error in browser console. Uncaught TypeError: Cannot read property 'innerHTML' of null at DisplayCart ((index):192) at (index):185 -
AWS S3 Responds with HTTP 400
I am writing a piece of code that uploads something to AWS S3 asynchronously. In doing so, I have been following this tutorial. Everything seems to be fine; however, when it comes to the actual upload, I get an HTTP 400 back from AWS. <Error><Code>InvalidRequest</Code><Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message><RequestId>E1CB0551A45B4B3D</RequestId><HostId>H8xQkyTimhnb+Z3cIKKB1EvCwDp+Ka+Rt+JR4YISR2hrj7Qmmb2BLHc0UXpoC+Gz1n7wwt8aYkg=</HostId></Error> The initial hunch was that this had something to do with with the signature version, so I explicitly set AWS_S3_SIGNATURE_VERSION = "s3v4" in settings.py of the Django project for Boto3 and Django-Storages to use. This didn't help. Hence, it seems that there is something wrong with the way the policy is formed before it is sent to AWS. Is this correct? What goes wrong here? P.S. There are a couple of other people in the commends of the tutorial who report the same issue and are unable to resolve it. models.py class FileItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null = True, on_delete = models.SET_NULL) name = models.CharField(max_length=120, null=True, blank=True) path = models.TextField(blank=True, null=True) size = models.BigIntegerField(default=0) file_type = models.CharField(max_length=120, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) uploaded = models.BooleanField(default=False) active = models.BooleanField(default=True) @property def title(self): return str(self.name) urls.py urlpatterns = [ path('uploader/', TemplateView.as_view(template_name='celery_test/test-uploader.html'), name='upload-home'), … -
One by one task using django, celery and redis
I use django, celery and redis to launch task asynchronously. # tasks.py @shared_task def my_task(): # Do stuff of task 1 return True # Somewhere in test1.py my_task.delay() # Few milli seconds later in test2.py my_task.delay() With that configuration, my_task is launched 2 times on 2 different files. So they are executed on different threads almost at the same time. I need these 2 tasks to be executed one by one. If my_task #1 is executing and another my_task #2 is launched, I need my_task #2 to wait for the #1 to end before executing. I don't want to use only one thread passing argument to celery celery worker --concurrency=1 Config of celery in my settings.py is basic : # settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' I found many resources who talks about that subject but I don't really understand how to achieve my goal https://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html#ensuring-a-task-is-only-executed-one-at-a-time Running "unique" tasks with celery http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html -
GenericForeignKey filtering in django
When filtering on a "GenericForeignKey" I get following error: django.core.exceptions.FieldError: Field 'owner' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I already checked this topic, and tried it: django: how do I query based on GenericForeignKey's fields? This is my code: model: class Pool(models.Model): pool = models.ForeignKey( Pool, on_delete=models.CASCADE, related_name="pools" ) owner_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) owner_id = models.PositiveIntegerField() owner = GenericForeignKey("owner_type", "owner_id") View: pools = Pool.objects.filter( owner_id=parent_supplier.id, owner_type=ContentType.objects.get_for_model(parent_supplier).id, ) but that doesn't work, what am I doing wrong? Doing literally the same as in the so-topic? -
Issue with Django 3 and jupyter
I am trying to to use jupyter note with django3 but I am getting this error, can anyone help me this. I m stuck on this part. -
Django] My registration form doesn't work
I'm coming to you because I have a problem with my form. Let me explain, when I enter the information in the inputs and I click on the button, it does absolutely nothing, without any error message. This is views.py: from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from .models import Movies from .forms import CreateUserForm from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.conf import settings from django.contrib.auth.decorators import login_required # Create your views here. def home(request): context = { 'movies': Movies.objects.all() } return render(request, 'list/home.html', context) @login_required(login_url='login-page') def add(request): return render(request, 'list/add.html', {'title': 'Add Movies'}) def signup(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('list-home') else: form = CreateUserForm() return render(request, 'list/sign.html', {'form': form}) This is forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={"placeholder": "Your pseudo:"})) first_name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={"placeholder": ">Your first name:"})) last_name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={"placeholder": "Your last name:"})) email = forms.EmailField( max_length=50, required=True, widget=forms.TextInput(attrs={"placeholder": "Your email:"})) password = forms.CharField(max_length=50, required=True, widget=forms.PasswordInput(attrs={"placeholder": "Your password:"})) password2 = forms.CharField(max_length=50, required=True, widget=forms.PasswordInput(attrs={"placeholder": "Confirm your password:"})) class Meta: model = User fields = ('username', 'first_name', … -
Fixtures are not meant to be called directly
I'm using Django 3.0.5, pytest 5.4.1 and pytest-django 3.9.0. I want to create a fixture that returns a User object to use in my tests. Here is my conftest.py import pytest from django.contrib.auth import get_user_model @pytest.fixture def create_user(db): return get_user_model().objects.create_user('user@gmail.com', 'password') Here is my api_students_tests.py import pytest from rest_framework.test import APITestCase, APIClient class StudentViewTests(APITestCase): user = None @pytest.fixture(scope="session") def setUp(self, create_user): self.user = create_user def test_create_student(self): assert self.user.email == 'user@gmail.com' # other stuff ... I keep getting the following error Fixture "setUp" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters. I read and read again this previous question but I cannot find out a solution. Furthermore, in that question the fixture wasn't returning nothing, while in my case it should return an object (don't know if it can make any difference) -
In django how can i apply query like this:-
This type of query is applied in sql update myModel set name="new name", age=24 where id==2 How can I apply this type of query in Django -
Change float format in django, decimal separate by ( , ) and thousands by (.)
I'm trying to change the format of the money representation in my django system. I use float to represent it. An actually a price look like this $1,500.30 and now I want to look like this $1.500,30 Here is the price in my model public_price = models.FloatField ( verbose_name=_('Precio'), blank=True, null=True, default=0.0 ) Please help, any idea will be excellent. -
Accidently deleted Profiles and Stubs4 from Django and unable to run manage.py
I wanted to clear the database because I messed in putting correct parameters to update_or_create and create functions of django.For that I deleted the database from pgadmin4 in postgres and deleted all__pycache__, stubs.v4 and the Profiles folder in my django project because I wanted to again feed data into the database. My goal is to upload a .csv file and fill data row by row (create/update) to database. Now these errors neither let me create superuser not let me do run manage.py PS C:\Users\Dell\Desktop\github\DjantoSoft> python manage.py runserver c:\python37\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory PS C:\Users\Dell\Desktop\github\DjantoSoft> django-admin createsuperuser No Django settings specified. Unknown command: 'createsuperuser' -
500 (Internal Server Error) when fetching from Django Rest API default router (to create object)
I am trying to make Django and React to work together, and although I have a basic knowledge of Django (I can develop a site), I am just starting to learn React. My project structure is based on this video which is loosely based on this blog in turn. My API works perfectly fine, I can create, retrieve, update, and delete objects without problems. Also, on my frontend, I have managed to correctly display a list of the items from my database, by fetching the related API Url. Just to make it clear, here is the main 'backend' urls.py: from rest_framework import routers from .views import AssessmentViewSet router = routers.DefaultRouter() router.register('api/assessments', AssessmentViewSet, 'assessments') urlpatterns = router.urls Now, from what I see on my API webpage, objects are created and retrieved on the same Url, and namely http://127.0.0.1:8000/api/assessments/, as you can see from this screenshot. The only difference, I guess, is that when I want to create an object, all I have to do ist to specify inside the fetch function, that I am making a POST request. This is done in my CreateAssessmentForm.jsx file: import React, { Component } from "react"; class CreateAssessmentForm extends Component { state = { loading: … -
heroku message "Attachment names not available. Please specify one."
Trying to deploy Django/Postgres application (Windows 10 OS) to Heroku, running the command $ heroku addons:create heroku-postgresql:hobby-dev I get the message: Creating heroku-postgresql:hobby-dev on motorhome... ! ! Attachment names not available. Please specify one. My static files settings: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE='whitenoise.storage.CompressedManifestStaticFilesStorage' Could you please give a hint of what the reason for this problem can be? -
Can you make this site on django? [closed]
So I wan to start learning django, and i have some questions. For example, can you make site like this in django: https://csgorun.org/ . Or if you can, is it worths it? Or maybe for this sites i need to take up js, php e.t.c Because I know python and django is easier for me. Thanks -
Accessing object attributes when rendering a formset
I hope I can manage to explain myself. I'm using modelformset_factory to edit a set of objects. In the example below I want to edit the start date and enrollment status for a bunch of candidates on a course. The formset uses a Queryset that I've provided it with. I'm trying to figure out how to render the candidates name in the HTML template. Currently I'm sending both the formset and queryset to the template, create two loops and binding them together using {% if forloop.counter == forloop.parentloop.counter %}. This works ok except when two people try using the form at the same time, so the queryset changes before one of the users can submit, and that causes the formsets to fall out of alignment with the queryset. The code below is just a simplified example, the code may have errors in it, it's just as an example of what I'm trying to do. models.py class Candidate(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT, null=False, blank=False) first_name = models.CharField(max_length=255, null=True, blank=True) lastname_name = models.CharField(max_length=255, null=True, blank=True) is_enrolled = models.BooleanField(null=True, blank=True, default=0) start_date = models.DateField(blank=False, null=False) views.py course = get_object_or_404(Container, id=course_id) CandidatesFormSet = modelformset_factory(Candidate, fields=('is_enrolled', 'start_date')) formset = CandidatesFormSet(queryset=Candidate.objects.all()) template.html {% for form in … -
Multiple users click the button of django web app at the same time
I wanted to know, in Django if there are multiple users clicking the Button of web-app at the same time, so will it create a conflict? For example. There is a "next sample" button to pull the sample data from database, so if multiple users at the same time click the next sample button, will there will be any conflicts(like two users got the same sample data set?). I have researched about it but could not get the clear answer, however i believe that Django application creates the individual sessions for the request and it wont overlap the requests. -
Saving data into database using Django channels
I'm having issue with saving of data from websocket via django channels. Whenever channels receive a player's data, it will add the data into the queue list and once the queue list is filled, it will then create a room for the players and send back to the players to tell them which room to connect to. But the issue here is that the process will be stuck at the model creation part and doesn't proceed from there. I have tried googling around but I can't seems to find anything that would help me for this issue. Here's the code: consumers.py class GameLobbyConsumer(AsyncWebsocketConsumer): room_name = "" room_group_name = "" queue_list = [] player_list = [] async def connect(self): # Connecting to matchmaking lobby try: await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() except Exception as e: print(e) async def disconnect(self, code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data=None, bytes_data=None): player_info_json = json.loads(text_data) player_info_dict = dict(player_info_json) key_verification_list = ["player_id", "name"] if list(player_info_dict.keys()) != key_verification_list: await self.close() response_data: dict = await self.check_queue_list(player_data=player_info_json) if not response_data["status"]: room_size = response_data["queue_size"] await self.channel_layer.group_send( self.room_group_name, { "type": "notification", "message": f"Still looking for match, {room_size}/4 players currently" } ) else: players = response_data["players"] room_id = response_data["room_id"] … -
Django Reduce Page SQL Queries (Code Optimization)
I have 2 pages that are getting slower and slower one of which is totally unusable when there are more than 10 objects or so involved. I know what the issue is after using the django-debug-toolbar package. ListView page: 23971.48 ms (182 queries including 180 similar and 178 duplicates ) I'm fairly new to making optimized database queries and so far everything just works. However, as I said before if I have more than 10 objects (in this case documented trades) things start crashing. I believe a big solution would be to calculate these stats and then save them as fields. Is that the right approach, not at all, or just scratching the surface? models.py (you can tell there are a lot more functions that call many more functions) class Trade(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ... # P/L Value = Sum of all buys * ( Entry Cost Per Unit (CPU) - Exit Cost Per Unit (CPU) ) def get_profit_loss_value_or_None(self): if self.get_exit_cpu() > 0: if self.type == 'Long': result = self.get_entries().aggregate( get_profit_loss_value=Sum('amount', output_field=models.FloatField() ) * (self.get_exit_cpu() - self.get_entry_cpu()))['get_profit_loss_value'] return 0 if result is None else result elif self.type == 'Short': result = self.get_entries().aggregate( get_profit_loss_value=Sum('amount', output_field=models.FloatField() ) * -1 * …