Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model foreign key field is not available in migrations during tests
I have this model. class TransportOrder(SomeMixin, models.Model): order = models.ForeignKey( to="orders.Order", on_delete=models.PROTECT, related_name="transport_orders", help_text=_("Order which was used for creating"), null=True, blank=True, ) # Other fields have been removed for simplicity I have forward function in a migration. def forward(apps, schema_editor): TransportOrder = apps.get_model("transportorders", "TransportOrder") # There is no `order` field printed result. print(dir(TransportOrder)) However, this only happens while running my tests. Otherwise there is no problem. What can cause this issue? -
Django generate bootstrap tabs with for loop
I have a page in my web app with multiple tables, and rather than have them on separate pages or one long list, I want to use tabs and I need to be able to generate these tabs based on how many objects there are. I'm pretty certain it's just a problem with the template, but I'll include all the other files just in case. Here are the models relevant to the problem. class Exercises(models.Model): exercise = models.CharField(max_length=45) evolution = models.CharField(max_length=8) start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) logo = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=['exercise', 'evolution'], name='exercise_evolution_UNIQUE') ] def __str__(self): return f"Exercise: {self.exercise}\t Evolution: {self.evolution}" class Units(models.Model): uic = models.CharField(max_length=10) unit_name = models.CharField(unique=True, max_length=45) mcc = models.CharField(max_length=5, blank=True, null=True) ruc = models.CharField(max_length=10, blank=True, null=True) personnel = models.IntegerField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=['uic', 'mcc', 'ruc'], name='uic_mcc_ruc_UNIQUE') ] def __str__(self): return f"{self.unit_name}" def get_uic(self): return f'{self.uic}' class ExercisePersonnel(models.Model): exercise = models.ForeignKey('Exercises', models.CASCADE) unit = models.ForeignKey('Units', models.CASCADE) location = models.ForeignKey('Locations', models.RESTRICT) quantity = models.IntegerField() def __str__(self): return f'{self.unit}' class UnitEdl(models.Model): unit = models.ForeignKey('Units', models.CASCADE) equipment = models.ForeignKey('Equipment', models.CASCADE) quantity = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['unit', 'equipment'], name='unit_equipment_UNIQUE') I have functions that use … -
How to access a jwt token from a django rest framework to angular frontend
I have created a DRF api authenticated with jwt,the token is stored in a cookie.I can successfully access all the viewsets using the token with postman.It only becomes a problem when l want to pass the token to angular frontend for the same operations.I am using django rest framework backend and Angular 9 frontend.Also note that l am storing the token in a cookie. My views.py class LoginView(APIView): def post(self,request): #getting the inputs from frontend/postman email =request.data['email'] password =request.data['password'] user=User.objects.filter(email=email).first() #Authentication if user is None: raise AuthenticationFailed('User not found!') if user.password!=password : raise AuthenticationFailed("incorrect password") payload = { 'id':user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=10), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() #storing the token in a cookie response.set_cookie(key='jwt',value=token ,httponly=True) response.data = { 'jwt':token } return response class UserView(APIView): def get(self,request): token=request.COOKIES.get('jwt') if not token: raise AuthenticationFailed("unauthorised") try: payload =jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("session expired") user=User.objects.get(id=payload['id']) serializer=UserSerializer(user) return Response(serializer.data) class Update(APIView): def get_object(self,request): try: token=request.COOKIES.get('jwt') if not token: raise AuthenticationFailed("unauthorised") try: payload =jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("session expired") user=User.objects.get(id=payload['id']) return user except User.DoesNotExist: return Response("wakadhakwa",status=status.HTTP_204_NO_CONTENT) def get(self,request): obj=self.get_object(request) serializer=UserSerializer(obj) return Response(serializer.data) def put(self,request): obj=self.get_object(request) serializer=UserSerializer(obj,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response("corrupted data",status=status.HTTP_204_NO_CONTENT) def … -
Nginx "upstream" directive is not allowed here
I'm trying to set up a Django website with uwsgi and nginx. I created configuration file mysite.conf: # the upstream component nginx needs to connect to upstream django { server unix:///home/path/to/mysite/mysite.sock; } # configuration of the server server { listen 80; server_name mydomain.com www.mydomain.com; charset utf-8; # max upload size client_max_body_size 350M; # Django media and static files location /media { alias /home/path/to/mysite/media; } location /static { alias /home/path/to/mysite/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/path/to/mysite/uwsgi_params; } } And it gives this error: nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-enabled/mysite.conf:2 I don't why it happens. I followed this tutorial: https://tonyteaches.tech/django-nginx-uwsgi-tutorial/ -
How to display 2 message in my django website
I am creating a website that can display the hours worked of an employee and also show a graph of the employees past working hours. The graph on the y-axis could not show time value so I made an input that can convert integer to time. I want it to be displayed at the bottom while still showing the graph and hours worked. Here is a picture of my website displaying the hours worked, the graph and the convert input. . Here is after I convert integer to time. . Here is my code: def report(response): empName = employeeName.objects.all correct = True global cInUpdated global allDateUpdated global label if response.method == "POST": if 'byHour' in response.POST: n = response.POST.get("enterName") if employeeName.objects.filter(employee=n).exists(): emp = employeeName.objects.get(employee=n) time = emp.total_Hours_Worked messages.info(response, time + ' hours') f = Name.objects.filter(name=emp) allDate = [] cIn = [] today = datetime.today() datem = today.month for date in f: allDate.append(date.date) totalTime = (datetime.combine(date.date, date.timeOut)- datetime.combine(date.date, date.timeIn)).seconds/3600 cIn.append(totalTime) hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) cInUpdated = [] allDateUpdated = [] label = "Hours worked this month" for item in range(len(allDate)): if allDate[item].month == datem: cInUpdated.append(cIn[item]) … -
Dynamically create <script src from string in database using django
In my Django project, I am dynamically rendering cards populated with data from a database. This works as expected. In each card, I need to render a vue-audio-mixer control, but each instance of the mixer must have it's own configuration script. Firstly, I tried this: <script src="{{ movements.script_source }}" but this is wrong. Then, I tried the following code but it does not work either. Any help would be appreciated, thanks. <script> var url = "{{ movement.script_source }}"; var script = document.createElement("script"); script.src = url document.body.appendChild(script); </script> -
state value not change reactjs when axios get
When I used this code as an API in Python(Django) to return three characters from the username but unfortunately the value of the state does not change. Django code: class usertype(APIView): def get(self,request,format=None): try: user=User.objects.get(username=request.user) except: raise ValueError('error') if not user.is_superuser: data={ 'usertype':user.username[:3], } return Response(data) else: return redirect('login') Reactjs code: state={ usertype:'', } gettype() { api.get('/').then(res=>{ this.setState({usertype:res.data.usertype}); }); } showDash() { switch(this.state.usertype){ case "std": ///code break; case "thr": ///code break; default: ///code break; } } All imports are correct and there are no problems with the library installation. how can i fix this problem! -
How to display celery progress bar on UI in a way that it should display even after switching pages
I have created celery-progress bar in my django project like click on a button and the progress bar starts on UI and it works.After progress starts when i go to back page or next page & come back to progress-bar page, It doesn't display the bar anymore however the celery task is still running in the background. I want to show the progress baron UI even after switching pages until the task is done. Please suggest me to achieve it.Here is my code: views.py def approval_req_func(request): task = go_to_sleep.delay(3) data = {'status': 'Success', 'message': 'Approved successfully', 'task_id':task.task_id} return HttpResponse(json.dumps(data), content_type="application/json") tasks.py @app.task(bind=True) def go_to_sleep(self,duration): progress_recorder = ProgressRecorder(self) s = Contact.objects.all() for i,j in enumerate(s): time.sleep(duration) print(j) progress_recorder.set_progress(i+1, len(s),f'On Iteration {i}') return 'Done' Html & Scripts <button>Click to start Progress</button> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script> $(document).ready(function(){ $("button").click(function(event) { event.preventDefault() const valuesInArray = $(this).serializeArray() const body = {} valuesInArray.forEach(e => { body[e.name] = e.value }); $.ajax({ method: "GET", url: "{% url 'contact:approval_req_func' %}", data: body }).done(function (response) { $(function () { var progressUrl = "{% url 'celery_progress:task_status' 'task-id-stub' %}"; var progressUrll = progressUrl.replace('task-id-stub', response['task_id']); CeleryProgressBar.initProgressBar(progressUrll); }); }) .fail(function (response) { … -
Can we store files on the django framework?
I was wondering on how to store some files in the django framework, and how to access them for editing and updating them? I wanted to upload a few excel files and a few python scripts which automate the excel files. Everything is working fine locally for me, but just wanted to know on how to do it for webpage which can be accessed by anyone? Thanks -
Image is not uploading in Input Tag
I am building a BlogApp and I am new in django and HTML. I am trying to make a custom upload button using <input type="file" > BUT when i use {{ form }} then it is working BUT when i use <input type="file" name="file" > then it doesn't upload the Image. models.py class G(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) class GImage(models.Model): gimage = models.ForeignKey(G,related_name='imagess',on_delete=models.CASCADE) file = models.ImageField(upload_to='images') **My image instance name is file. views.py def new(request): GForm = modelformset_factory(GImage,fields=('file',),labels={'file':'Image'},extra=1,min_num=1) if request.method == 'POST': formset = GForm(request.POST,request.FILES,queryset=GImage.objects.none()) if formset.is_valid(): post_form = formset.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: if form: image = form['file'] photo = GImage(g=post_form,file=image) photo.save() return redirect('mains:all_stories') else: formset = GForm(queryset=GImage.objects.none()) context = {'formset':formset} return render(request, 'new.html',context) forms.py class GForm(forms.ModelForm): class Meta: model = GImage fields = ['file',] template.html When i try this :- <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> BUT When i try with input tag then it doesn't work. <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <input type="file" … -
django, django-exporter and gunicorn.give me error Read beyond file size detected
I have a django-rest webapp.I installed django-exporter to export metrics for my prometheus.I use gunicorn to run my webapp.But after working a while it throw this error: RuntimeError: Read beyond file size detected, /home/git/histogram_1000.db is corrupted. -
I'm stack in, Object x is not JSON serializable
I need a help please, i'm stack, i'm getting this error: Object of type CustomUser is not JSON serializable My code : def sharedContact(self, connectedUser): contactList = [] contacts = ContactCenter.objects.filter(contact_source=connectedUser) | ContactCenter.objects.filter(shared_with=connectedUser) #pprint(vars(contacts)) for contact in contacts: #pprint(vars(contact)) users = CustomUser.objects.filter(id=contact.contact_source_id) | CustomUser.objects.filter(id=contact.shared_with_id) for user in users: with schema_context(str(user.username)): tenants = Contact.objects.filter(id=contact.contact) for tenant_contact in tenants: contactList.append(tenant_contact) return contactList -
django radio choice can't be display
I working on a survey app where users with admin roles can log in to the admin dashboard to create surveys and provide the survey link to the surveyor to take the survey. I am having trouble displaying the questioner and choices on the surveyor page. I trying to display the survey question choices but the radio choice can't be displayed. The questions can be displayed but the radio choice cannot be display. Not sure what I did wrong. Previously I had my model setup like what I have posted here. But then I had trouble displaying all the questioners, so I get assistance from stack over and I've changed my model but now I can't display my radio choices. class Survey(models.Model): title = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now) archive = models.CharField(max_length=200, default='') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) class Meta: abstract = True class ChoiceQuestion(Question): choice = models.CharField(max_length=100) def __str__(self): return self.choice class TextQuestion(Question): textbox = models.CharField(max_length=100) def __str__(self): return self.textbox class CheckQuestion(Question): checkbox = models.CharField(max_length=100) def __str__(self): return self.checkbox <div class = "jumbotron container centerdv header-top"> <h2>{{survey.title}}</h2> </div> <div class="d-flex flex-column"> <form method = "post" action =#> <input type = "hidden" name … -
Can't access an item in a dictionary that does in fact exist
I have two buttons on my page, each one in its own separate form. One of the buttons, "deleteImage", works perfectly fine. The other button, "search", won't work. This is my response.POST when search is pressed. request.POST <QueryDict: {'csrfmiddlewaretoken': ['randomtoken1234'], 'search': ['food', '']}> request.POST.get("search") is failing to work for some reason, I tried printing it as well and nothing prints out. -
Difficulty in installing shuup
guys it's my first time installing the shuup and able to do the migrations but when tried the following command to initialize shuup python manage.py shuup_init it throws the below error: Traceback (most recent call last): File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'shuup_init' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\jmdee\tep\manage.py", line 21, in <module> main() File "C:\Users\jmdee\tep\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 211, in fetch_command settings.INSTALLED_APPS File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\jmdee\tep\tep\settings.py", line 15, in <module> django.setup() File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 66, in … -
How to do error handling for 401, 402, 403 in Django
Hi for my Django application I am trying to do error handling for all possible types of errors in which the Django documentation only shows how to deal with 404 and 500 errors by adding the following lines in the urls.py file as shown handler404 = 'store.views.handler404' handler500 = 'store.views.handler500' This ensures that the 404.html and 500.html templates are displayed to the user when such errors come up. But then for errors such as 401, 402, 403 can I similarly add?... handler401 = 'store.views.handler401' handler402 = 'store.views.handler402' handler403 = 'store.views.handler403' Even if this is available in Django, HOW CAN I TEST TO SEE IF IT WORKS. Any help is greatly appreciated. Thanks! -
Filtering doesn't work in conjunction with Search results Django
I have implemented a filter form in my web application. I have pagination tags implemented in the HTML, with the navigation buttons set up like: {% load pagination_tags %} {% block content%} <center> <h5> Search results for "{{search_query}}" </h5> </center> <br> <div class="col"> <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Filter</button> </form> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item {% if not prev_page_url %} disabled {% endif %}"> <a class="page-link" href="?{% url_replace request 'page' prev_page_url %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active" aria-current="page"> <a class="page-link" href="?{% url_replace request 'page' n %}">{{ n }} <span class="sr-only"></span> </a></li> {% elif n > page.number|add:-4 and n < page.number|add:4 %} <li class="page-item"> <a class="page-link" href="?{% url_replace request 'page' n %}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %} disabled {% endif %}"> <a class="page-link" href="?{% url_replace request 'page' next_page_url %}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> And the pagination_tags.py file looks like this: from django import template from urllib.parse import urlencode register = template.Library() @register.simple_tag def url_replace (request, field, value): dict_ = request.GET.copy() dict_[field] = value return dict_.urlencode() The pagination works … -
cant delete with keyword arguments '{'pk': ''}' from URL
I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button <a class="dropdown-item" href="{% url 'emsi:employee_delete' pk=employee.pk %}"> <i class="fa fa-trash text-danger fa-fw"></i>Delete</a> this is the urls.py from django.urls import path from . import views # Employee path('dashboard/employee/', views.Employee_All.as_view(), name='employee_all'), path('dashboard/employee/new/', views.Employee_New.as_view(), name='employee_new'), path('dashboard/employee/<int:pk>/view/', views.Employee_View.as_view(), name='employee_view'), path('dashboard/employee/<int:pk>/update/', views.Employee_Update.as_view(), name='employee_update'), path('dashboard/employee/<int:pk>/delete/', views.Employee_Delete.as_view(), name='employee_delete'), this the Views.py from django.shortcuts import render, redirect, resolve_url, reverse, get_object_or_404 from django.urls import reverse_lazy from django.contrib.auth import get_user_model from pip._vendor.requests import Response from .models import Employee, Department from django.contrib.auth.views import LoginView from django.contrib.auth import logout from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import FormView, CreateView, View, DetailView, TemplateView, ListView, UpdateView, DeleteView from .forms import RegistrationForm, LoginForm, EmployeeForm, DepartmentForm from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.utils import timezone from django.db.models import Q # Employee's Controller class Employee_New(LoginRequiredMixin, CreateView): model = Employee form_class = EmployeeForm template_name = 'emsi/employee/create.html' login_url = … -
Image is not saving in input tag
I am building a BlogApp and I am new in django and HTML. I am trying to make a custom upload button using <input type="file" > BUT when i use {{ form }} then it is working BUT when i use <input type="file" name="file" > then it doesn't upload the Image. models.py class G(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) class GImage(models.Model): gimage = models.ForeignKey(G,related_name='imagess',on_delete=models.CASCADE) file = models.ImageField(upload_to='images') **My image instance name is file. forms.py class GForm(forms.ModelForm): class Meta: model = GImage fields = ['file',] template.html When i try this :- <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> BUT When i try with input tag then it doesn't work. <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <input type="file" name="file" > {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> I have no idea why this is not saving. Any help would be much Appreciated. Thank You in Advance. -
Generate forms from serializer
I'm working with React in the front-end with Material-UI, and I would like to auto generate forms based on my serializer's schema. Usually, the way that CRUD works in the app is by listing the registers, and then give the option to add, edit, or remove registers. So, my idea would be to get the serializer's schema in the listing part of the CRUD and then use it to generate the forms later on. Is there anyway to do this? I'm thinking about maybe creating an npm package to help on it... Thanks -
How to display Django model's foreign key as its attribute in admin panel?
In Django Admin, my model CNAME has a foreign key to AuthUser, when I create a model instance, I must choose a User, but there display the AuthUser's Object number, how to display username in there? The model details: class CNAME(models.Model): name = models.CharField(max_length=64, unique=True, help_text=". eg:gat.google.com") desc = models.CharField(max_length=5120, null=True, blank=True, help_text="desc") desc_en = models.CharField(max_length=5120, null=True, blank=True, help_text="desc)") user = models.OneToOneField(unique=True, to=AuthUser, on_delete=models.DO_NOTHING, help_text="belong to user") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = "CNAME" verbose_name_plural = "CNAME" class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' In my admin.py I register it: admin.site.register(CNAME) class CNAMEAdmin(admin.ModelAdmin): list_display = ['name', 'desc', 'desc_en', 'user', 'ctime', 'uptime'] list_filter = [] search_fields = ['name', 'desc'] list_per_page = 10 -
How to POST a List of Objects to API in React JS/Django
So, I have a team (NY Yankees) and a list of players (players): 'yankees' ['babe ruth', 'lou gehrig', 'joe dimaggio', 'yogi berra', 'mickey mantle', 'derek jeter'] I have a form where I am sending POST request data, and it works perfectly fine, but I can only do it one at a time: function handleEnterButtonSubmitted(id) { const requestOptions = { method: "POST", headers: {"Content-Type": "application/json" }, body: JSON.stringify({ team: team, player: player, }), }; fetch('/api/player/', requestOptions) .then((response) => response.json()) .then((data) => console.log(data)); } My question is how do I take this already-working form, and turn it into an instance where I can submit various players, and they will all be associated to the "Team" object (foreign key in Django Models). How would the function "handleEnterButtonSubmitted" be different? My idea would be to use the following MaterialUI Component: <FormControl className={classes.formControl}> <InputLabel shrink htmlFor="select-multiple-native"> Native </InputLabel> <Select multiple native value={personName} onChange={handleChangeMultiple} inputProps={{ id: 'select-multiple-native', }} > {names.map((name) => ( <option key={name} value={name}> {name} </option> ))} </Select> </FormControl> This is the function: const handleChangeMultiple = (event) => { const { options } = event.target; const value = []; for (let i = 0, l = options.length; i < l; i += 1) { if … -
Using Django ORM for computed field
I have a scoreboard for a web app. Each user post is worth 10 points, and each user comment is worth 1 point. I want to sort by highest score first. So with raw SQL, it would be: select username, email, ( select 10 * count(*) from posts_post where accounts_customuser.id = posts_post.author_id ) + ( select count(*) from posts_comment where accounts_customuser.id = posts_comment.author_id ) total from accounts_customuser order by total desc, username; Of course, the idea with Django is to leverage the ORM and avoid raw SQL. I see there are aggregates, so it's close to something like this: queryset = get_user_model().objects.annotate(post_count=Count('posts'), comment_count=Count('comment')).order_by('-post_count', '-comment_count', 'username') However, that's not quite right because if I have a user with 1 post and 1 comment (11 points) and then one with 0 posts and 12 comments (12 points), they wouldn't be sorted right by the ORM with the above QuerySet. I tried leveraging F: # Note: CustomUser is what get_user_model() returns CustomUser.objects.annotate(post_count=Count('posts'), comment_count=Count('comment'), total=Sum(F('post_count') * 10 + F('comment_count')) ).order_by('-post_count', '-comment_count', 'username') However, that throws the following error: FieldError: Cannot compute Sum('<CombinedExpression: F(post_count) * Value(10) + F(comment_count)>'): '<CombinedExpression: F(post_count) * Value(10) + F(comment_count)>' is an aggregate I'm not sure where to go from here. … -
Concatenation of ObjectId and string in django template
I have a very simple question, on which i spent hours. Heres the deal: i insert a path to an image in mongodb, save said image in my static folder (under objectId.png) and pass the objectId to my template in order to display it. Heres some code, in views: return render(request,'resultat_simulation.html',{'truc':truc2}) truc2=str(truc.id), truc being the object inserted in the DB. It is passed to the template without issue. Now, the template: {% extends 'base.html' %} {% load static %} {% block body %} {{truc}} <img src="{% static 'C:\Users\smeca\Documents\projetfinal\stage\app\static\images\{{truc}}.png' %}"> {% endblock %} If instead of {{truc}}, i put the ObjectId of any image, it is rendered. I just want to append the string form of objectid to '.png' so i can loop through the images and display them all. I tried everything i found on the net to no avail. Thanks in advance. -
Generic relations serialization in django-rest-framework
could you help me please with the serialization of generic relation in Django rest framework. I need to get data for SWOT object including company and all comments for it. I have problems with retrieving comments which is a generic field. models.py: class SWOT(models.Model): name = models.CharField(max_length=500, default='') description = models.CharField(max_length=500, default='', blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) #Generic Relation for comments comments = GenericRelation(Comment) def __str__(self): return self.name class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(verbose_name="") created_date = models.DateTimeField(default=timezone.now) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() views.py: class SwotView(generics.ListAPIView): serializer_class = SwotSerializer def get_queryset(self): swot_id = self.kwargs['swot_id'] return SWOT.objects.filter(id=swot_id) serializers.py: class CommentRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, SWOT): serializer = SwotSerializer(value) else: raise Exception('Unexpected type of comment ', type(value)) return serializer.data class SwotSerializer(serializers.ModelSerializer): company = CompanySerializer() comments = CommentRelatedField(many=True, queryset=Comment.objects.all()) class Meta: model = SWOT fields = ('id','name', 'description','company','comments') I have tried to implement the code from the example in documentation but I tackle error. I don't know why the type of the object is Comment instead of SWOT. Could you tell me please what I can do to make this code work just like in documentation or propose another solution like regular relational fields as …