Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set the id of an HTML element with Django variable?
Right now, I'm displaying a bunch of elements using data from a Python dictionary, which looks something like {"id", "content", "id2": "content2"}. I'm then passing that to an HTML template through Django, and running a for loop to create an element for every item in the dictionary. The problem is, I'm going to add other front-end features via javascript, that require each element created to have a unique id in HTML, which I want to be set to the key of the python dictionary (So the first element has id of 'id', second element has an id of 'id2'...) So, how do I set the id of the element to be the Django variable? I know it isn't the for loop's problem, since I can print out the id variable just fine. Python code objects = {"A1": "xxx", "B2": "yyy", "C3": "zzz"} return render(request, "website/index.html", { "objects": objects }) index.html {% for object, specs in objects.items %} <div class="status"> Chunk of irrelevant code here </div> {% endfor %} I want each div with class status to also have an id of "A1" or "B2" and so on, but I don't know how to assign this -
Permission denied: 'd:/upload/'
Error Page PermissionError at /insert [Errno 13] Permission denied: 'd:/upload/' Request Method: POST Request URL: http://localhost/insert Django Version: 2.1 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'd:/upload/' Exception Location: C:\Users\cocoa\PycharmProjects\myweb2\board\views.py in insert, line 25 Python Executable: C:\python study\myweb2\Scripts\python.exe Python Version: 3.8.5 insert part from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect UPLOAD_DIR = 'd:/upload/' @csrf_exempt def insert(request): frame='' fsize=0 if 'file' in request.FILES: file=request.FILES['file'] fname=file._name with open('%s%s' % (UPLOAD_DIR, frame), 'wb') as fp: for chunk in file.chuncks(): fp.write(chunk) fsize=os.path.getsize(UPLOAD_DIR + fname) row = Board(writer=request.POST['writer'], title=request.POST['title'],content=request.POST['content'], filename=fname, filesize=fsize) row.save() return redirect('/') Perhaps django has no authority to access the 'upload' folder. Changed from security in upload folder to all permissions. Should this problem be solved in sql? Help me.... -
"Cannot resolve keyword 'created' into field" on new DRF list view
I made a new list view in my Django REST Framework app: class ColumnView(ListCreateAPIView): queryset = Column.objects.all() serializer_class = ColumnSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) When I try to access it, I get the following error: FieldError at /my/new/endpoint Cannot resolve keyword 'created' into field. Choices are: _order, fields, from, my, model There's no created field anywhere in sight - not in the ColumnSerializer, not in the Column Django model, nowhere. The stacktrace is really opaque, too - my app doesn't appear anywhere in it. What's going on? -
Connecting AWS RDS MySQL instance to Django application
So I have created a Django backend application and have just put on the finishing touches. Now I would like to make my app use an MySQL instance I have created with my AWS account. I have entered all the credentials into my setting.py file but I get a strange error. I'm not sure what I'm doing wrong as there is almost no documentation of how connect it and it is my first time doing it. Here is the error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on {AWS ENDPOINT} -
Validating Sum of InlineFormSet against Total in ParentModel
Let's assume I have a main model called Bill. There I have a field total_amount and a many-to-many relationship to the UserModel through an intermediate model, where the share of the total bill per User can be recorded. See the following snippets. Finally, the sum of the share of the totall bill per User's shall equal the total_amount. I like to validate within the form, inlineform (or model) that the sum of the amounts in the Model BillDebitor equals the total_amount of the Bill Model. If anyhow possible this shall be evaluated within the form itself and raise a ValidationError if the amounts are not equal. Can somebody assist in how to solve this? I tried throgh custom clean methods, but for some reason neighter the parent form nor the inline formsets are available in the respective forms. models.py class Bill(modles.Model): total_amount = models.Decimalfield() debtor = models.ManyToManyField(settings.AUTH_USER_MODEL, through='BillDebtor') class BillDebtor(models.Model): bill = models.ForeignKey(Bill) debtor = models.ForeignKey(settings.AUTH_USER_MODEL) amount = models.Decimalfield() forms.py class BaseBillForm(models.ModelForm): class Meta: model = Bill fields = ['total_amount'] class DebtorForm(models.ModelForm): class Meta: model = BillDebtor fields = ['debtor', 'amount'] class DebtorFormSet(models.BaseInlineFormSet): pass DebtorInlineFormSet = inlineformset_factory(Bill, BillDebtor, form=BaseBillForm, formset=DebtorFormSet, extra=2) view.py class SplitBillView(CreateView): model = Bill from_class = BaseBillForm … -
Python DJANGO 3.0 issue with passing arguments to @register.simple_tag
I have the following tree: apps templatetags pyos.py templates index.html In pyos.py I have the following code: import os from django import template register = template.Library() @register.simple_tag def listdir(path): d = os.listdir return d(path) def test(): pass Then in index.html, inside templates I have the following already working: {%extends 'principal.html'%} <div> {%load pyos%} {%listdir 'C:/'%} </div> I need to pass some static path as argument, is there any way to do something like that? <div> {%load pyos%} {%load static%} {%listdir {%static 'img/image.png'%}%} </div> -
Django: Annotate table with field across a M2M mapping to another table
I want to get competition.name from a list of submissions. In my setup, competitions and teams share a M2M relationship (with an associated competition-team object. Each competition-team pair can submit any number of submissions. I now have a dashboard page which I am trying to create a table of all submissions by the team accompanied by the respective competition's name. The output should look like: | Submission Name | Submission Date etc. | Competition Name | | Sub01 | 2020-12-30 2000 | Competition01 | I have trouble retrieving the competition name from the submissions. Here are my models: class Competition(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) class CompetitionTeam(models.Model): competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id') team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id') class CompetitionSubmission(models.Model): competitionteam_id = models.ForeignKey(CompetitionTeam, on_delete=models.CASCADE, db_column='competitionteam_id') I wish to annotate a set of submissions with their respective competition names. I tried with: submissions.annotate(competition_name=Subquery(Competition.objects.filter(id=Subquery(CompetitionTeam.objects.get(id=OuterRef('competitionteam_id')).competition_id)).values('name'))) "ValueError: This queryset contains a reference to an outer query and may only be used in a subquery." I also tested with the following command: CompetitionSubmission.objects.prefetch_related('competitionteam_id__competition_id') It runs but the command seems to do nothing. I will update this post with other methods I try. Thank you. -
GET API with Django code working in Postman but not in React JS
The GET API works in Postman with the correct JSON response, but doesn't work in React when I try to show the JSON response on the webpage. I also don't know how to handle this CORS error: from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I tried many ways, but I ended up getting some sort of error every time so for now, I just used a temporary solution, which is a Chrome extension, to get rid of this error for now, but I have to solve it eventually. Here is my code in views.py: class get_events_1st_alg(APIView): def get(self, request, format=None): import pandas as pd import numpy as np import psycopg2 import sqlalchemy from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics import pairwise_distances import requests from sqlalchemy import create_engine engine = create_engine('postgresql://postgres:postgres@localhost/postgres') # pd.read_sql_query('''SELECT * FROM arts_user_interaction LIMIT 5;''', engine) events = pd.read_sql_query('''SELECT * FROM arts_event;''', engine) Ratings = pd.read_sql_query('''SELECT * FROM arts_user_interaction;''', engine) Mean = Ratings.groupby(by="User_ID", as_index = False)['User Rating'].mean() Rating_avg = pd.merge(Ratings, Mean, on = "User_ID") Rating_avg['adg_rating']=Rating_avg['User Rating_x']-Rating_avg['User Rating_y'] check = pd.pivot_table(Rating_avg,values='User Rating_x',index='User_ID',columns='Event_ID') final = pd.pivot_table(Rating_avg,values='adg_rating',index='User_ID',columns='Event_ID') final_event = final.fillna(final.mean(axis=0)) final_user = final.apply(lambda row: row.fillna(row.mean()), axis=1) cosine = cosine_similarity(final_event) np.fill_diagonal(cosine, 0 … -
Why do you test a model's field label name and when do you use the label name?
This article recommends testing your model's fields label name. Why would you test a field's label name when it is already set by Django? When in your code do you use the label name for a field? -
How to build control panel for kivy application in django?
Hi i want to build admin panel in Django for my kivy application. I am using: Python 3.7 Pycharm Kivy Mongodb -
Why does 'Git add *' leave some files unstaged?
I initialized a new git repo in my Django project. All files( including the files in subdirectories and pipfile) are staged when I run git add * except the .__atomic-writegxd2tirf file. Why is this one excluded? -
HttpResponse - how to get the values from context (Django)
I have a function defined like this in my views.py: def homePageView(request): (some code here...) return render(request, 'index.html' {'mytuple': mytuple}) The function itself is working perfectly, however I need the mytuple value to be accessible from another function. So, my other function looks something like this: def value_checker(request): value_check = homePageView(request.POST.get(['mytuple'], False)) return render(request,'dynamic.html', {'value_check': value_check}) Unfortunately is not working and I'm getting an error: TypeError at /value unhashable type: 'list' I've looked at the Django documentation of HttpResponse but honestly I can't seem to figure out how to access this tuple. What am I doing incorrectly here? -
Django - how to delete objects in the database?
So, I'm having problems deleting objects in django project's database. I have a model in my models.py file that looks like this. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) I want to be able to delete information in this model. In my project, I have this model's information displayed in a table that looks like this table/html My goal is to click the "drop" button and have that line of info deleted. I've been following some tutorials and advice on making a delete function for my views.py and I can't get it to work. It seems pretty simple but I'm not sure where I'm going wrong. Here's my views.py and urls.py def delete_player(request, id): player = Myteam.objects.get(id=id) #print(player.id) player.delete() return redirect('index') path('delete_player/<int:id>', views.delete_player, name="delete_player") here's my html... <form action="" method="POST"> {% csrf_token %} <table style="border: 1px solid black;"> <tr> <td style="border: 1px solid black;">QB</td> … -
[Django Beginner]: Proper way to import a model from another app when using forms?
I have a model, inventory.Location. This is in the inventory app. I'm creating a form in another app and make reference to inventory.Location. Specifically, I'm populating a choice field with all Locations (with minor criteria). This works well until I attempt to make any migrations, at which point Django throws an error: django.db.utils.OperationalError: no such column: inventory_location.contact contact is just a field, removing contact just causes the same error to occur only with another field. It seems Django doesn't like creating an instance for LocationForm as it ties back to the inventory.Location model. If I comment out the contents of 'LocationForm' and re-run the migration attempt it works perfectly fine. Removing any previous migrations and/or re-building the DB from scratch doesn't seem to have any influence, it's specifically the LocationForm class contents. Is there a best practice way I should be handling this? Everything works; I just have to comment out the contents of LocationForm, run migrations, then uncomment. I'm clearly approaching this the wrong way. from django import forms from inventory.models import Location def get_locations(): location_list = [] locations = Location.objects.all() for location in locations: if location.primary_ip: site_list.append( (location.name, location.name) ) return location_list class LocationForm(forms.Form): location = forms.ChoiceField( widget=forms.Select(), … -
Not requiring Authentication Credentials in Authenticated Views Django Rest Framework
I have some views with IsAuthenticated Decorator. When I try to access those views with postman without the Token it's not giving me an error. But it should give me an error by saying authentication credentials are not provided. What is the reason for that. @permission_classes((IsAuthenticated,)) @api_view(['POST']) def CreateSubject(request,pk): author = TeacherProfile.objects.get(user_id=pk) serializer = SubjectSerializer(data=request.data) if serializer.is_valid(): serializer.save(author=author) return Response(serializer.data) From this view, I can create a subject but it should require the user token to be inside headers. But as I guess decorator is not working. Im using a custom user model class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12,null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # def has_perm(self, perm, obj=None): # return self.is_admin def has_module_perms(self, app_label): return True -
Ignore filter in Django None value
Is there anybody know how can I ignore filtering when the value is none just like the sample below. municipality = request.POST.get('municipality) if request.POST.get(municipality) else None bene = Person.objects.filter(province=province, municipality=municipality) If the municipality value is none the filtering should ignore municipality in bene query and it should only filter the province, just I need help this time thanks -
django new posts made are going on the bottom when they should go up top
I am currently building an app that allows users to post comments on a web page. Every time someone makes a new comment it goes to the very bottom. How do you make all new comments made appear up top? -
Django rest framework serializer require all or none
Is there a way to make a list of fields be an all or none required? Maybe something like this where if any of fields 'A' to 'D' is included in data all of them should be required but if none of them is included in data it should be fine: class BookSerializer(serializers.ModelSerializer): fieldA = serializers.CharField() fieldB = serializers.CharField() fieldC = serializers.CharField() fieldD = serializers.CharField() # other fields class Meta: require_together = ( ('fieldA', 'fieldB', 'fieldC', 'fieldD'), ) -
Django + Apache, Saving uploaded files on different storage server
I have a application server where I have configured my Apache and Django which will host my application. This is running fine. Now the requirement is to serve the uploaded files directly to different storage server or you can say on a remote server. And after uploading my application should able to retrieve them also from the remote server. My application is on x.x.x.50 My storage is x.x.x.60 How can i do that with minimal changes in my application server. I have tried changing MEDIA ROOT path in Apache but I don't know how exactly i should do that to work it smoothly. -
Django: Trying to create a Meeting Room API with Reservations
So I got these tasks: Creating meeting room Get meeting room reservations and the possibility to filter by employee Create reservation (Reservation has title, from and to dates, employees) First of all I have created a meeting room, this is the model: class MeetingRooms(models.Model): public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) creator = models.ForeignKey(Employees, on_delete=models.CASCADE) reservations = models.ManyToManyField(MeetingRoomsReservations, blank=True) secret_key = models.CharField(max_length=128, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "MeetingRooms" def __str__(self): return str(self.id) So as the task says I need to create some kind of reservations, so basically I was thinking that I could create reservations object and make it ManyToManyField, so it could serve many reservations for different users, imagine the meeting could have like 10 people. Then I have created MeetingRoomsReservations model to handle all the reservations: class MeetingRoomsReservations(models.Model): statusTypes = [ (0, "Valid"), (1, "Cancelled") ] receiver = models.ForeignKey(Employees, on_delete=models.CASCADE) meeting_room = models.ForeignKey('MeetingRooms', on_delete=models.CASCADE, default=None) title = models.CharField(max_length=150, blank=False, null=False) status = models.IntegerField(choices=statusTypes, null=False, blank=False, default=0) date_from = models.DateTimeField() date_to = models.DateTimeField() class Meta: db_table = "MeetingRoomsReservations" def __str__(self): return str(self.id) As far as I understand the logic, the MeetingRoomsReservations will handle all the reservations that were registered for the MeetingRoom. MeetingRoom > … -
Condition inside objects filter Django
Im been wondering if it is possible to put condition inside query just like this sample = Person.objects.filter(province=province, municipality=municipality, if barangay!=None: then barangay ="value") Im been having a problem same with this link but I don't know how I can ignore empty value in query. Is there any expert can help me please -
Changing Value of an Attribute in a Model when a post takes place
I have made a blog where a user can like or unlike, so everything is working fine now but I have tried to add a Like Model to view more details related to each like that takes place by which user and when. In the Like Model I have added a value for each model and choices are Like and 'Unlike' I have tried in the views to use get_or_create but it cause an error TypeError: Field 'id' expected a number but got <built-in function id>. and I tried to add the value incase a like and unlike is made it returned AttributeError: 'str' object has no attribute 'save' I am going to show the view with my trials commented First here is the post model: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the like model: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) liked = False current_likes … -
Django tests stopped running
My Django tests have randomly stopped running and I cannot figure out why. The error that I'm getting is: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I found this question and I've run the command: export DJANGO_SETTINGS_MODULE=mysite.settings (with my relevant settings) and it didn't solve the issue. I've also tried adding this to the top of my tests file but it didn't do anything: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") Here is the full print out of the error I'm getting: /Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/bin/python /Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py Traceback (most recent call last): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py", line 90, in <module> from repcdocs.tasks import print_slack_users File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/repcdocs/tasks.py", line 10, in <module> from django.contrib.auth.models import User File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before … -
Django Multiple Choice Quiz - conditionally change background using python / html
New to django, python, and html here. I'm creating a MULTIPLE CHOICE QUIZ and want the background to conditionally change based on the user's selected answer. I'm trying to use the "IF" function through html. Stylesheet using classes via CSS are working just fine. I made several print calls just to see if my python logic was working and it does (see code below). I think it's something i'm doing wrong from the html side. Side note - all questions and answers are saved in Django database. So for example: The correct answer to question 1 is "Apple". If the user selected "Apple", the webpage should result "Correct! Good job.". For any other answer selected, should result "Wrong!! The correct answer is Apple." My problem for many many many days/hours is that as of now every choice I select results in "Wrong, you are Incorrect" as the resulted background. Even when the correct answer is chosen by the user. Thanks in advance for all of your help! Please see code below. views.py def vote(request, question_id, *args, **kwargs): question = get_object_or_404(Question, pk=question_id) ### temporarily PRINTED call from database to see if python logic works, It works. ID 1 prints out "Apple". … -
Service backend failed to build
Getting the following error while trying to build docker image: ERROR: Service 'backend' failed to build : The command '/bin/sh -c apk add — update — no-cache postgresql-client' returned a non-zero code: 3 How can I resolve this?