Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'd like to modify the JavaScript code to meet the conditions [closed]
I am a student who is learning web programming. It's just that I added functionality to the program, so it's not saved in DB. Above is saved, but features have not been added, below is added, but not saved to DB. I think it's because of Select. If you correct the code below, we will adopt it right away. I'd like to supplement this content so desperately. I'm looking for an expert who can solve this code that hasn't been solved after two weeks of hanging on. Thank you for reading the long question. Existing code stored in DB: <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="value_code" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="value_code" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> </div> Code not saved : <style> * {padding: 0; margin: … -
(DJANGO) Storing Multiple data from html forms to the database
I am create a quiz app and i have some value for every radio Option, and i want to store the question,option user have selected and the optionvalue. Below is the model for Questions where i have stored the Question from where i need to fetch the questions to show to the user. models.py class modelStrategy(models.Model): domainStrategy = models.CharField( max_length=20, default="Strategy", blank=True) dateStrategy = models.DateField(auto_now_add=True) priorityStrategy = models.IntegerField() questionsToAddStrategy = models.CharField(max_length=256) questionType = models.CharField(max_length = 20,choices=QUESTION_CHOICE,null=True, blank=True) question_text = models.CharField(max_length=200,null=True, blank=True) OptionsOneStrategy = models.CharField(max_length=120, null=True, blank=True) OptionsOneValueStrategy = models.IntegerField(null=True, blank=True) OptionsTwoStrategy = models.CharField(max_length=120, null=True, blank=True) OptionsTwoValueStrategy = models.IntegerField( null=True, blank=True) OptionsThreeStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsThreeValueStrategy = models.IntegerField(null=True, blank=True) OptionsFourStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsFourValueStrategy = models.IntegerField(null=True, blank=True) OptionsFiveStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsFiveValueStrategy = models.IntegerField(null=True, blank=True) OptionsSixStrategy = models.CharField( max_length=120, null=True, blank=True) OptionsSixValueStrategy = models.IntegerField(null=True, blank=True) here is the views.py file def chnageQuesStra(request): if request.method == "POST": saveans = modelAnswer() saveans.questionsToAddStrategy = request.POST.get("Question") saveans.OptionsStrategy = request.POST.get('option') questionsToAddStrategy = request.POST.get("Question") saveans.save() mod = modelStrategy.objects.all() paginator = Paginator(mod,1) try: page = int(request.GET.get('page','1')) except: page =1 try: questions = paginator.page(page) except(EmptyPage,InvalidPage): questions = paginator.page(paginator.num_pages) context = { "mod":mod, "questions":questions, } return render(request,'Questions.html',context=context) here is the html code were i … -
How to fix: ProgrammingErrorsAlreadyExists'django_content_type'
When I run the server it gives this message on console: "You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them." When I try to run python manage.py migrate. It shows this message at the bottom: "[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There is already an object named 'django_content_type' in the database." -
Unable to add values at features in django admin panel
I am new in Django and now I am working with manipulation of database in django admin panel. While playing with features I am unable to add values in features. There is no key and after saving it leaves empty object. I am using django 2.2.5. Click for the image Here are my codes models.py from django.db import models class Feature(models.Model): name: models.CharField(max_length=20) age: models.IntegerField(max_length=3) sex: models.CharField(max_length=5) point: models.CharField(max_length=5) partner_name: models.CharField(max_length=20) relation: models.CharField(max_length=20) partner_age: models.IntegerField(max_length=3) partner_sex: models.CharField(max_length=5) partner_point: models.CharField(max_length=5) description: models.CharField(max_length=500) partner_img: models.CharField(max_length=100) admin.py from django.contrib import admin from .models import Feature # Register your models here. admin.site.register(Feature) urls.py import myapp from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path("", include("myapp.urls")) ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] -
getting multiple countdown timers from querysets using django models and javascript
I really don't know how to push on with this, the idea is an investment platform where the user can have multiple investments and each investment has a due date enter image description here this image shows that when I try to query the countdown timer it just shows for the first query set and it picks the new query added to the model query set <script> let timer = new Date({{amt.timer|date:'U'}}*1000) time = new Date(timer).getTime() newbox = document.getElementById('box') var interval = setInterval(() => { const now = new Date().getTime() const diff = time - now console.log(` this is testing diff ${diff}`) console.log(` this is testing ooo ${time}`) console.log(` this is testing now ${now}`) const d = Math.floor(diff / (1000 * 60 * 60 * 24) ) const h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const s = Math.floor((diff % (1000 * 60)) / 1000); newbox.innerHTML = `${d} days ${h} hours ${m} minutes ${s} seconds` if (diff < 0) { clearInterval(interval) } {#console.log(time)#} {#console.log(diff)#} {#console.log('hello')#} }, 1000) </script> this code is in the forloop. thanks, I … -
Get Django Custom user model listed under admin app `Authentication and Authorization`
Note my question is similar to this one, however that answer recommend not calling the customised user model User, whereas the official docs and this issue do. I created a custom User model in an app called plug: plug/models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): """ Requirements: - Must be defined in models.py, due to the way settings.AUTH_USER_MODEL is defined - Must not be called 'User', or else can't list it in same table """ is_hamster = models.BooleanField(default=False) is_superhero = models.BooleanField(default=False) is_pogo_stick = models.BooleanField(default=False) class Meta: # app_label = 'auth' # <-- This doesnt work db_table = 'auth_user' settings.py file set accordingly: AUTH_USER_MODEL = 'plug.User' plug/admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model @admin.register(get_user_model()) class UserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'is_hamste', 'is_superhero', 'is_pogo_stick') list_display_links = list_display fieldsets = UserAdmin.fieldsets + ( ('Leasing User Role', {'fields': ('is_hamste', 'is_superhero', 'is_pogo_stick')}), ) All is good except in the admin interface the custom user is listed under the heading Plug instead of under Authentication and Authorization (where Users used to be listed, along with Groups). I tried setting app_label = 'auth' in the meta of the custom user model, however then it fails … -
Store data just for a single session in Django?
I am currently creating a website with Django and I came across the following question: I want to store data, the user enters (a string (e.g. a name or his age)), BUT it must be "deleted" when the same user enters the website again after closing it so is should only be saved for the current session. So I read about cookies but they actually DO store the data of a session to be used again in the next. So does anyone know a way to store data for a single session in Django? Thanks in advance -
How to i get session value userid in adddomainwiseprojects - django(using inline formset method)
Here i have attached views.py where add_projectdomain fields are added by importing models, here how can i get the loginid i.e. session key(userid) (as i have got in company_details view by using reuest.session.get method) in Add_domainwise projects form and save it. views.py from django.shortcuts import render,HttpResponse,redirect from .models import Add_domainwise_projects, Company_details, Country_master, State_master, City_master, Domain_master, Company_testimonials from .models import tbNewUser from django.contrib import messages from .forms import Add_domainwise_projectsForm from django.forms import inlineformset_factory, HiddenInput def logout(request): try: del request.session['userid'] except: return render(request, 'indexpage.html') return render(request, 'indexpage.html') def loginpage(request): if request.method == 'POST': try: Userdetails = tbNewUser.objects.get( userid=request.POST['userid'], password=request.POST['password']) print("Username=", Userdetails) request.session['userid'] = Userdetails.userid return render(request, 'indexpage.html') except tbNewUser.DoesNotExist as e: messages.success(request, 'Login ID or Password is Invalid..!') return render(request, 'Login.html') def Userreg(request): if request.method == 'POST': username = request.POST["username"] userid = request.POST['userid'] password = request.POST['password'] Alternatemail = request.POST['Alternatemail'] phone = request.POST['phone'] tbNewUser(username=username, userid=userid, password=password, Alternatemail=Alternatemail, phone=phone).save() messages.success(request, 'The userid' + request.POST['userid']+" is registered successfully") return render(request, 'Registration.html') else: return render(request, 'Registration.html') print("not saved") def indexpage(request): companies=Company_details.objects.all() context={'companies':companies} return render(request, 'indexpage.html',context) def add_country(request): if request.method == "POST": countryname = request.POST.get("countryname") Country_master.objects.create( countryname=countryname ) return render(request, "add_country.html", {"msg": 'Country- '+request.POST['countryname'] + 'Added!' }) else: return render(request, "add_country.html") def add_state(request): if request.method == "POST": … -
Django slow inner join on a table with more than 10 million records
I am trying to count the number of visitor_pages for a specific dealer in a certain amount of time. I would share the raw sql query that I have obtained from django debug toolbar. SELECT COUNT(*) AS `__count` FROM `visitor_page` INNER JOIN `dealer_visitors` ON (`visitor_page`.`dealer_visitor_id` = `dealer_visitors`.`id`) WHERE (`visitor_page`.`date_time` BETWEEN '2021-02-01 05:51:00' AND '2021-03-21 05:50:00' AND `dealer_visitors`.`dealer_id` = 15) The issue is that I have more than 13 million records in the visitor_pages table and about 1.5 million records in the dealer_visitor table. I am thinking of using a materialized view but before attempting that, I would really appreciate suggestions on how I could improve this query. -
mock or override values in apps.py (Django) for testing
Typically I'd set a value in settings.py and then use @override_settings in tests to override it. Is there any similar mechanism that exists for overriding settings in apps.py when using app_config? For instance # apps.py class MyConfig(AppConfig): SOME_VAR = "SOME_VAR" # some .py file from django.apps import apps apps.get_app_config('some_app').SOME_VAR # some test.py # How to change the value that apps.get_app_config('some_app').SOME_VAR returns? It's strange this isn't covered in the docs as it feels this would be a common use case or maybe I'm missing something? Thanks, -
pagination does not work for numbers in between and also for reverse in django
I am filtering my data, and also applying paginator, I have found some solution and I used it but it is working only for the next button and not for previous and button numbers in between i.e. for {{i}} (Django, python) this is template_tag file myapp_extra.py from django import template register = template.Library() @register.simple_tag def my_url(value, field_name, urlencode=None): url = '?{}={}'.format(field_name, value) if urlencode: querystring = urlencode.split('&') filterd_querystring = filter(lambda p: p.split('=')[0]!=field_name, querystring) encoded_querystring = '&'.join(filterd_querystring) url = '{}&{}'.format(url, encoded_querystring) return url in my html {% load myapp_extra %} <other code> <nav> <ul class="pagination rounded-separated justify-content-center" style="float: right; margin-top: 1%;"> {% if employees_attendance_list.has_previous %} <li class="page-item"><a class="page-link" href="{% my_url employees_attendance_list.previous_page_number 'page' request.GET.urlencode }"><i class="mdi mdi-chevron-left"></i></a></li> {% else %} <li class="disabled"></li> {% endif %} {% for i in employees_attendance_list.paginator.page_range %} {% if employees_attendance_list.number == i %} <li class="page-item active"><a class="page-link" >{{ i }}</a></li> {% else %} <li class="page-item"><a class="page-link" href="{% my_url i 'page' request.GET.urlencode}">{{ i }}</a></li> {% endif %} {% endfor %} {% if employees_attendance_list.has_next %} <li class="page-item"><a class="page-link" href="{% my_url employees_attendance_list.next_page_number 'page' request.GET.urlencode %}"><i class="mdi mdi-chevron-right"></i></a></li> {% else %} <li class="disabled"></li> {% endif %} </ul> </nav> in views page = request.GET.get('page', 1) paginator = Paginator(employees_attendance, settings.PAGE_LIMIT) try: employees_attendance_list = paginator.page(page) … -
Django testing how to make a request as logged in user?
In Django tests, I want to log in and make a request. Here the code def test_something(self): self.client.login(email=EMAIL, password=PASSWORD) response = self.client.get(reverse_lazy("my_releases")) self.assertEqual(response, 200) But the code doesn't work and returns AttributeError: 'AnonymousUser' object has no attribute 'profile' How to make request in test as logged in user? -
File deletion when cloning a model that contains an ImageField
When I save() a model that contains an ImageField, the post_save signal of the model base deletes the file that was previously associated with the ImageField which is fair enough because the file has changed to a new value. However, if I've cloned the model, i.e. loaded an object from the db, set it's pk to None, set it's ImageField to a new value and then done a save(), I don't want it to delete the original file because it's still in use by the object that was cloned. item = Item.objects.get(id=kwargs['pk']) item.pk = None item.thumbnail = <new image> item.save() #<--causes the original Item's thumbnail file to be deleted This feels like its such a normal procedure that there should be a pattern for doing it without overriding signals but I'm damned if I can see it. Can anyone point me in the right direction please. -
Is It possible to listen to Rest API Endpoint using django channels?
Goal is to send the serialized data of the created object of POST Method! Request will come from Android/IOS app built with Flutter/Dart I am trying to use Django Channels Rest Framework. But I am not sure if it is gonna work or not! -
Angular app keeps saying message does not exist
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the point marked 'this point' in the code. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MessageResponse, Channel } from 'stream-chat'; import { StreamService } from '../stream.service'; import { StateService } from '../state.service'; declare const feather: any; @Component({ selector: 'app-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.scss'], }) export class ChatComponent implements OnInit { constructor( public streamService: StreamService, private stateService: StateService, private router: Router ) {} messages: MessageResponse[] = []; message = ''; channel!: Channel; async sendMessage() { if (this.message) { try { await this.channel.sendMessage({ text: this.message, }); this.message = ''; } catch (err) { console.log(err); } } } getClasses(userId: string): { outgoing: boolean; incoming: boolean } { const userIdMatches = userId === this.streamService.currentUser.messages.id; (this point) return { outgoing: userIdMatches, incoming: !userIdMatches, }; } } -
how to show success message on keyclock page in django?
{% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{message.tags}}" {% endif %}> <i class="bi bi-exclamation-triangle-fill"></i> {{ message }} </li> {% endfor %} </ul> {% endif %} I want to show this message on keycloak page. it's server is different from our Django project now how can show success message displaying on keyclock page The view returns success and error message response = requests.post(reset_url, data=payload, headers=headers) if response.status_code == 200 and response.json()["statuscode"] == "E_SUCC": messages.success(request,"You should receive an email with further instructions") else: messages.error(request,"Email not found.") -
Running Unit testing in Django
I'm running a unit test in Django but keep getting an error File "C:****\views.py", line 21, in post s = str(points['string_points']) KeyError: 'string_points' Command Used: python manage.py test The structure of my test code looks as follows: class TestViews(TestSetUp): def test_getClosestPoints_with_no_data(self): res = self.client.post(self.calculateClosestDistance_url) import pdb # python debugger pdb.set_trace() self.assertEqual(res.status_code, 400) class TestSetUp(APITestCase): def setUp(self): self.getClosestDistance_url = reverse('getClosestDistance') self.calculateClosestDistance_url = reverse('calcClosestDistance') points = { "string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)" } return super().setUp() def tearDown(self): return super().tearDown() Structure of my views file is as follows: class closestDistanceValue(APIView): def get(self, request): points = Points.objects.all() serializer = PointsSerializer(points, many=True) return Response(serializer.data) def post(self, request, format=None): points=request.data # user input s = str(points['string_points']) closestPoint = getClosestDistance(s) data = { 'point': s, 'closestPoint': closestPoint } serializer = PointsSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) JSON Body for POST request. Keyed in as user input { "string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)" } What I'm I missing? -
Call manager of select_related field
I have the following example: class Profile(models.Model): ... class Person(models.Model): profile = models.ForeignKey(Profile, ...) I have complex Model manager for Profile class and I built a view to list a big amount of Person. I try to compute everything in database so I would like to call the Profile Manager from Person QuerySet. To do that, I need to do something like: Person.objects.filter(...).select_related('profile', queryset=Profile.objects.with_computed_revenue().all()) And then I should be able to get person.profile.computed_revenue retrieved from SQL, with the function "with_computed_revenue" being a function of the ProfileManager that annotate computed_revenue. The final goal is to add in person queryset : .values('profile__computed_revenue') It seems possible with Prefetch for prefetch_related, but I cannot find an equivalent with select_related. -
Nested table rows
I'm working on a project that is still in its early stages using Django and Jquery. I would wish to create a nested table in that team leaders have people assigned to them. So far I have been able to display team leaders but not able to display employees associated with them. Views.py class SupervisorEmployee(View): def get(self,request,firstname,lastname,*args,**kwargs): supervisor_name=get_object_or_404(Supervisor,firstname=firstname, lastname=lastname) filtered_team_leaders=TeamLeaders.objects.filter(supervisor=supervisor_name.pk) context={ 'firstname':firstname, 'lastname':lastname, 'filtered_team_leaders':filtered_team_leaders, } return render(request,'supervisors/employees.html',context) class EmployeeResponseView(View): def post(self,request): first_value = request.POST.get('first_value') first_value=first_value.strip() second_value = request.POST.get('second_value') second_value=second_value.strip() team_leader_query=get_object_or_404(TeamLeaders,fname=first_value,lname=second_value) employee_query=Employees.objects.filter(team_leader=team_leader_query.pk) data=serializers.serialize('json',employee_query) return HttpResponse(data,content_type='application/json') template.html <thead class="bg-secondary text-white"> <th>ID</th> <th>firstname</th> <th>lastname</th> <th>Role</th> <th>Joining</th> <th>age</th> <th>remuneration</th> </thead> <tbody> {% for team_leaders in filtered_team_leaders %} <tr id="emb" class="bg-light"> <input id="first" type="hidden" value="{{ team_leaders.fname|safe }}"> <input id="second" type="hidden" value="{{team_leaders.lname|safe }} "> <td>{{ team_leaders.id }}</td> <td>{{ team_leaders.fname }}</td> <td>{{ team_leaders.lname }}</td> <td><span class="badge bg-danger">{{ team_leaders.role }}</span></td> <td>{{ team_leaders.joining }}</td> <td>{{ team_leaders.age }}</td> <td>{{ team_leaders.remuneration }} / day</td> </tr> employee data goes here {% endfor %} </tbody> </table> template associated with jquery to add employee data below supervisor var first_value=$.trim($('#first').val()); if(second_value != '' && first_value != '') { $.ajax({ url:'{% url "employee_response" %}', method:'POST', data:{'first_value':first_value,'second_value':second_value}, success:function(data) { Response data from database should be embedded below each team leader }, error:function() { alert('Error fetching employees'); } … -
Cannot create a server with run.py for e-commerce website
This is one of my first times using this website so please feel free to ask for clarification underneath if I haven't worded this well! So, im creating an e-commerce website for a project however I have an error where my form code is displaying on my website instead of actually working (if that makes sense!) I asked for help previously and was told I needed to run my server with run.py to get to the local host. However when I try running run.py I have this error: Traceback (most recent call last): File "run.py", line 1, in from shop import app File "/Users/darby/Desktop/CM1102-WA-master copy/Coursework_3/shop/init.py", line 4, in from shop import routes File "/Users/darby/Desktop/CM1102-WA-master copy/Coursework_3/shop/routes.py", line 3, in from others.py import app, db ModuleNotFoundError: No module named 'others' The files it references in question are as follows: run.py from shop import app if __name__ == "__main__": app.run(debug=True) init.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from shop import routes app = Flask(__name__, static_folder="static") db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) routes.py from flask import Flask, render_template, flash, redirect, url_for, session, request, logging, session from flask_login import login_user, current_user, logout_user, login_required from others import app, db … -
Django, Foreign key not getting filled with session data
im trying to fill my foreignkey with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: class JobCreate(CreateView): model = Job form = JobCreateForm() form_class = JobCreateForm context = {} success_url = reverse_lazy('jobsview') def POST(self,request): if(request.method == 'POST'): form = JobCreateForm(request.POST) if(form.is_valid): job = form.save(commit=False) job.employer = request.user job.save() context = {} return render(request, 'jobs/jobs.html',context) else: context = {} return render(request, 'jobs/job_form.html',context) Model: class Job(models.Model): employer = models.ForeignKey(User, related_name='employer', on_delete=CASCADE,blank=True) employees = models.ManyToManyField(User, related_name='employees2user',null=True,blank=True) title = models.CharField(max_length=200,) description = models.CharField(max_length=200,null=True,blank=True) category_id = models.ManyToManyField(Category,blank=True) skill_id = models.ManyToManyField(Skill,blank=True) approved = models.BooleanField(default=False) # img = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): # Default value return self.title -
use model's value to create a Django form
I have a model which is as follows: class BloodTestType(models.Model): type = models.CharField(max_length=200) def __str__(self): return str(self.type) class BloodParameters(models.Model): type = models.ForeignKey(BloodTestType, on_delete=models.CASCADE) parameter = models.CharField(max_length=200) minimum_value = models.FloatField() maximum_value = models.FloatField() unit = models.CharField(max_length=200) required = models.BooleanField(default=True) GENDER_CHOICES = [ ('B', 'Both'), ('M', 'Male'), ('F', 'Female'), ] gender = models.CharField(max_length = 100,choices = GENDER_CHOICES,default = 'B') def __str__(self): return str(self.type) + ' ' + str(self.parameter) Consider BloodParameters model has 3 parameters with type = '1' I want to create a Django form containing these 3 parameters as input fields but the form loads up as blank. I'm trying something on these lines in my forms file : class BloodReportCBCIronForm(forms.Form): cbc_iron_parameters = BloodParameters.objects.filter(type = 1) print('asd') print(cbc_iron_parameters.__dict__) for each in cbc_iron_parameters: each.parameter = forms.CharField(label = each.parameter,max_length = 80,required = True,) -
Django- Ajax returning wrong data
I'm building a webcomic using Django framework. The problem that I have now is to display chapters from different issues with AJAX. Let's say we have issue#1 and issue#2, when user clicks on issue#1 cover, it displays chapters of issue#1. I have managed to make it partially work, but it always displays issue#2 chapters, even if I click issue#1. excpected behaviour: how it is now: issue list html {% csrf_token %} <script> const csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value; </script> <div class="container mt-3 mb-3"> {% if issue_pl %} <div class="center-issues"> {% for issue in issue_pl %} <img src="{{ issue.cover.url }}" class="issue-thumbnail" alt="{{ issue.title }}" title="{{ issue.title }}" onclick="aload();" /> <script> function aload() { var xhr = new XMLHttpRequest(); xhr.open("POST", "{% url 'chapter_pl' issue.slug %}"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.onload = function () { document.getElementById("container").innerHTML = this.response; }; xhr.send(); } </script> {% endfor %} </div> {% endif %} <div id="container"></div> </div> views.py def ChapterListPL(request, slug): chapter_pl = ChapterPL.objects.filter(issue__slug=slug, status=1).order_by('number').all() context = { 'chapter_pl': chapter_pl, } return render(request, 'comics/chapters_pl.html', context) urls.py path('comics/<slug>/chapters', views.ChapterListPL, name='chapter_pl'), -
Using multiple connection vs single connections in sql python
I am using pymysql to connect to sql like this: con=pymysql.connect(...) cur=con.cursor() Well I am using flask web framework for some use. I defined the connection object as a single time and pass it to other function for use like this: @app.route('/') def index(): cur.execute(...) con.commit() #other stuffs My questions is that whether it is a good way or this: @app.route('/') def index(): con=pymysql.connect(...) cur=con.cursor() cur.execute(...) con.commit() #other stuffs What should I choose using a single connection or multiple one for every function. I don't want to make it crash if two requests are made at the same it and make it synchronised too. What's actually a good way? Thanks! -
alueError: Cannot assign value-field-must-be-a-object-instance
I get the following error ValueError: Cannot assign "(<UserProfile: testUser>, True)": "Comments.profileInfo" must be a "UserProfile" instance. What I am doing is unit testing : def create_user_profile(user): profile = UserProfile.objects.update_or_create(gender = 'F', defaults={ 'user': user}) return profile def create_comment(profile, cat): comment, __ = Comments.objects.update_or_create( defaults= {'profileInfo' : profile, 'category' : cat} ) return comment class CommentsFeature(TestCase): def setUp(self): self.user = create_user("testUser", "testPassword") login = self.client.login(username='testUser', password='testPassword') self.profile = create_user_profile(self.user) self.comment = create_comment(self.profile, self.cat) Model Code: class Comments(models.Model): profileInfo = models.ForeignKey(UserProfile, on_delete=models.CASCADE) class UserProfile(models.Model): GENDER_CHOICES = ( ('F', 'Female'), ('M', 'Male'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) dob = models.DateField(blank=True, null=True) facebook = models.BooleanField(default = False) # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User, on_delete=models.CASCADE) website = models.URLField(default = "", blank = True) picture = models.ImageField(upload_to='profile_images', default="", blank = True) def __str__(self): return self.user.username The error is coming from the set up function only. My test cases are returning this error Traceback (most recent call last): File "C:\Users\nikhi\Workspace_backup\Rango_Project\rango\tests.py", line 187, in setUp self.comment = create_comment(self.profile, self.cat) File "C:\Users\nikhi\Workspace_backup\Rango_Project\rango\tests.py", line 53, in create_comment 'category' : cat}