Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - SImple left join between 2 tables
I have been searching for LEFT JOIN of Django on Stackoverflow, however, most of solution are just too complicated. My models: class Voucher(models.Model): code = models.CharField(unique=True, max_length=255) delivery_type = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True, null=True) start_at = models.DateTimeField() end_at = models.DateTimeField() discount_type = models.CharField(max_length=255) discount_amount = models.FloatField(blank=True, null=True) class VoucherCustomer(models.Model): voucher_code = models.OneToOneField(Voucher, models.DO_NOTHING, db_column='voucher_code', primary_key=True) customer_id = models.IntegerField() times_used = models.BigIntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) This is what I tried: from django.db.models.sql.datastructures import Join #I thought this one is like from VoucherCustomer left join Voucher on VoucherCustomer.voucher_code = Voucher.code j=Join(VoucherCustomer, 'voucher_code', Voucher,"LEFT JOIN" ,'code', True) j.objects.filter(voucher_code ='SAIGONS247').values('code', 'delivery_type', 'description', 'times_used').values However, I got this result in the end: AttributeError: 'str' object has no attribute 'get_joining_columns' -
How do I move a local Postgres database to Heroku to make it public? After that how do I connect to the Heroku Postgres database from Django?
I am currently running a Django application on my local Postgres database. However, I would like to make it remote so that other group members can also read from the database. So how would I migrate my local Postgres database to a Heroku Postgres database? After that, how would I change settings.py in Django to connect to the Heroku Postgres remote database? Thank you! -
For Loop for Django Ajax Form Submission
Hi I have a for loop which creates multiple modal popups and its corresponding form inside the modal pop up. I am submitting the form via Ajax method so as to not have the page refresh. However i am facing the problem that if i have multiple forms only the first form gets submitted correctly. The subsequent forms will submit the first form's value. Can anyone help me i have been trying to solve this for a long time. Currently i have put my javascript in the for loop after the end form tag between{% for form,post in zipped %} and {% endfor %}. My thinking was that when the value {{post.pk}} changes i will listen in on a different form because i have used a unique form id formy{{post.pk}} as the selector in the javascript. However it is not working. My script is: <script> $('#formy{{post.pk}}').on("submit" , function(e){ e.preventDefault(); $.ajax({ type:"POST", data:{ tag:$('#tag').val(), author:$('#author').val(), file_name:$("#file_name").val(), file_path:$("#file_path").val(), unique_id:$("#key").val(), csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val(), }, success:function(){ alert("UPDATED!!!!"); } }); }); </script> My html code is : {% for form, post in zipped %} <tr> <td><img src={{post.file_path}} style="width: 300px;"></td> <td>{{post.tag}} {{post.pk}}</td> <td><button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal{{post.pk}}"> Edit Tag </button></td> <form id="formy{{post.pk}}"> {% csrf_token %} <div … -
Can we use multiple serializers for a single django post API?
I have implemented an API which accepts a set of inputs from serializers and validates them. I have to differentiate the set of inputs based on category which is included in the context of URL. currently I am validating the fields and making them mandatory based on the category. I want to know if we have multiple sets of serializers to differentiate them based on the category. -
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