Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
data:image/png;base64 not work but I don't know what to replace it with
def get_image(): buffer=BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) graph=base64.b64encode(buffer.getvalue()).decode() buffer.close() return graph def chart_select_views(request): graph=None error_message=None; df=None; if purpd.shape[0]>0: ... df['date']=df['date'].apply(lambda x:x.strftime('%d-%m-%Y')) df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum') if chart_type!='': .. graph=get_simple_plot(chart_type,x=df2['date'],y=df2['total_price'],data=df) else: error_message='selecte date'; else: error_message='no data'; context={ 'error_message':error_message, 'graph': graph, } return render(request, 'Product/index.html',context) <img src="data:image/png;base64, {{graph|safe}}"> the image is not displayed I tried with another format. I want to display the data in png format of the data that comes from my database of course in this part I do not want to use js even if it is very easy -
Grey box rendered in place of icon on Google Maps
I'm using the Google Maps API in my Django project to display the current users location and this is my first time using maps. The map loads fine, but there's a grey box in place of where the map marker should be(Just over the Au in Australia): // Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } window.initMap = initMap; I've customized the icon to display a different image and only the size of the grey box changed, there are no errors in the console. Any help would be appreciated! -
is there a way to provide custom names for my drf-yasg endpoints?
i am implementing an API using django-rest-framework and using drf-yasg to document and name my endpoints every post method ends with create i tried searching through the documentation and i cant find a way to do it -
How do I remove or change the 'Unknown' option from the dropdown of a BooleanField filter created using django_filters?
In my models.py, there's a BooleanField named cash: class Realization(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None) cash=models.BooleanField(default=False) amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0) And I'm using this model as a ForeignKey in another model IPDReport: class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True) approvedpackage=models.ForeignKey(ApprovedPackage, on_delete=CASCADE, blank=True, null=True) ctscan=models.ForeignKey(CTScan, on_delete=CASCADE, blank=True, null=True) radiations=models.ForeignKey(Radiations, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True) I wanted to create a filter for the IPDReport data, including Realization's cash field, so I used this way: class IpdFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Name') ctscan__rt_number=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='RT Number') package__patient_type__patient_type=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Type of Patient') realization__amount_received__gt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received') realization__amount_received__lt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte') from_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_bd', 'class':'form-control'}), field_name='realization__billing_month', label='From - Date of Billing ', lookup_expr='gte') to_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_bd', 'class':'form-control'}), field_name='realization__billing_month', label='To - Date of Billing ', lookup_expr='lte') class Meta: model=IpdReport fields={ 'realization__cash':['exact'] } Now on the IPDReport page in my app, the field renders like below: In the dropdown, the default option shows as Unknown. Is there any way I can change or remove that completely? Also, how can I add an HTML class attribute … -
Integrity error thrown even when parent model has values
I am getting this integrity error ORA-02091: transaction rolled back ORA-02291: integrity constraint (SYSTEM.MAIN_PAIN_ARTIST_ID_4D007402_F) violated - parent key not found even when parent model contain the values passed to foreign keys in the child table here are my models class Artist(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) name = models.CharField(max_length=200) country = models.CharField(max_length=200) year_of_birth = models.PositiveSmallIntegerField() year_of_death = models.PositiveSmallIntegerField(null=True) def __str__(self) -> str: return self.name class Owner(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) name = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=10) def __str__(self) -> str: return self.name class Painting(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) title = models.CharField(max_length=200) theme = models.CharField(max_length=200) rent = models.FloatField() owner_id = models.ForeignKey(Owner , on_delete=models.CASCADE , null= False , blank = False) artist_id = models.ForeignKey(Artist , on_delete=models.CASCADE , null=False ,blank = False) def __str__(self) -> str: return self.title Here is my views.py file def create_painting(response): if response.method == "POST": painting_form = createNewPainting(response.POST) if painting_form.is_valid(): i = painting_form.cleaned_data["id"] ttl = painting_form.cleaned_data["title"] thm = painting_form.cleaned_data["theme"] rent = painting_form.cleaned_data["rent"] own_id= int(painting_form.cleaned_data["owner_id"]) art_id= int(painting_form.cleaned_data["artist_id"]) answers = Painting.objects.filter(id=i) if not answers: with connection.cursor() as cursor: try: r = cursor.execute( f"INSERT INTO main_painting VALUES ({i} ,'{ttl}' , '{thm}' , {rent} , {own_id} , {art_id});") return HttpResponseRedirect("paintings/%s" %i) except … -
How to update a global variable from a function in Python?
I want to update an empty string value which is declared globally. I want to update that variable from inside a function. Following id the code: import jwt import os from dotenv import load_dotenv load_dotenv() from rest_framework.exceptions import APIException jwtPrivateKey = (os.environ.get('SECRET_KEY')) # VARIABLE DECALRED HERE token_value = "" def authenticate(auth_header_value): try: if auth_header_value is not None: if len(auth_header_value.split(" ", 1)) == 2: authmeth, auth = auth_header_value.split( " ", 1) if authmeth.lower() != "bearer" and authmeth.lower() != "basic": return TokenNotBearer() # WANT TO UPDATE THE VALUE OF token_value HERE token_value= jwt.decode( jwt=auth, key=jwtPrivateKey, algorithms=['HS256', ]) return TokenVerified() else: return TokenNotBearer() else: return TokenNotProvided() except (TokenExpiredOrInvalid, jwt.DecodeError): return TokenExpiredOrInvalid() # when token is expired or invalid class TokenExpiredOrInvalid(APIException): status_code = 403 default_detail = "Invalid/Expired token" default_code = "forbidden" # when token is not provided class TokenNotProvided(APIException): status_code = 401 default_detail = "Access denied. Authorization token must be provided" default_code = "unauthorized" # when the token is not provided in the bearer class TokenNotBearer(APIException): status_code = 401 default_detail = "Access denied. Authorization token must be Bearer [token]" default_code = "token not bearer" # when the token is valid class TokenVerified(): status_code = 200 default_detail = "Token verified Successfully" default_code = "verified" # … -
Slow loading Django Admin change/add
The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime, Loading Time Models: class Alert(BaseModelCompleteUserTimestamps): type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type") device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device") device_event = models.ForeignKey("dm_detection.VIDSDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="device_event") anpr_event = models.ForeignKey("dm_detection.VSDSDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event") ecb_event = models.ForeignKey("dm_detection.ECBDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event") hr_only = models.IntegerField(null=True, blank=True) # acknowledged is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged") acknowledged_at = models.DateTimeField(blank=True, null=True) acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True, related_name="alert_acknowledged_by") # resolved is_resolved = models.BooleanField(default=False, verbose_name="Resolved") resolved_at = models.DateTimeField(blank=True, null=True) resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True, status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1) Admin.py @admin.register(Alert) class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin): form = AlertEditForm fields = ('type', 'device', 'device_event', 'status', 'hr_only', 'is_acknowledged', 'acknowledged_at', 'acknowledged_by', 'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event', 'created_at', 'updated_at', 'OD_vehicle_number' ) Forms.py class AlertEditForm(forms.ModelForm): status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True)) device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all()) anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all()) acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all()) resolved_by = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Alert fields = '__all__' -
Django button not submit when i have onclick
I have a button and i want to when this button is clicked this submit my form and they open a popup with onclick but when i have the onclick the form is doesn't submitted. I have tried to delete onclick and the form perfectly work but when i readd is same ): <div class="container-login-form-btn"> <input onclick="openPopup(event)" class="login-form-btn" type="submit" value="Submit"/> </div> <div class="popup" id="popup"> <h1 type="submit">OTP Verification</h1> <p>Code has been send</p> <div class="otp-card-inputs"> {{ otp }} </div> <p>Didn't get the otp <a href="#">Resend</a> </p> <input class= "verify-otp-btn" type="submit" value="Submit"/> </div> function openPopup(event){ popup.classList.add("open-popup"); event.preventDefault(); } .popup { width: 900px; background: #ffffff; border-radius: 20px; position: absolute; top: 0; left: 50%; transform: translate(-50%, -50%) scale(0.1); text-align: center; padding: 0 30px 30px; color: #333; visibility: hidden; transition: transform 0.4s, top 0.4s; z-index: 2; font-family: 'Poppins', sans-serif; box-shadow: 0 10px 40px -20px black; } .open-popup { visibility: visible; top: 50%; transform: translate(-50%, -50%) scale(1); } Thanks you in advance I'm trying to show the popup and to submit the form. -
How to ensure that a custom field may be used when creating an instance but is not included when updating?
I have a serializer for a User model with custom fields password_1 and password_2 configured with write_only = True so they are not displayed with GET but required with POST when creating a new model, which is perfectly fine. My problem is the PUT method, because when I want to update a model the fields are still required. How can I configure the serializer or the view to make these two fields optional with PUT ? I test my code with the browsable API and the PATCH method, although supported, isn't proposed when updating a model. This is what I've tried: first I updated the put method of the view by adding partial_update, but I couldn't get the expected result, probably because they are custom fields. views.py @permission_classes([IsAuthenticated]) class ManagerDetailsView(RetrieveUpdateAPIView): serializer_class = ManagerSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) obj = get_manager(pk) return obj def get_permissions(self): if self.request.method == 'PUT': self.permission_classes = [HasChangeManagerObjectPermission | HasTeamLeadPermission] return super(self.__class__, self).get_permissions() def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) Then I undo the previous try and modified the validate method of the serializer by setting kwargs["partial"] to True but it has no effect. serializers.py class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 … -
Can't get NGINX to read socket created by GUNICORN via SUPERVISORD (permission error)
I'm trying to run Django on AWS/Ubuntu using NGINX/Gunicorn (via supervisord) My Nginx logs keeps throwing a permission error when trying to access app.sock. "app.sock" is created by gunicorn, and gunicorn is run by supervisord, and supervisord is a nightmare. ps aux | grep nginx root 63435 0.0 0.1 55200 1692 ? Ss 10:56 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 63436 0.0 0.5 55848 5424 ? S 10:56 0:00 nginx: worker process As we can see www-data is the user associated with nginx. ls -lh ~/www/app.sock srwxrwxrwx 1 root root 0 Dec 27 11:20 /home/ubuntu/www/app.sock And app.sock is owned by "root", hence the permission error I'm getting. And here is my supervisord config file [program:gunicorn] directory=/home/ubuntu/www command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/www/app.sock matched.wsgi:application user=www-data autostart=true autorestart=true stderr_logfile=/logs/gunicorn.err.log stdout_logfile=/logs/gunicorn.out.log In my config file, I've attempted to tell supervisor to run my gunicorn command AS www-data, but its still creating app.sock as root. It seems like the "user" parameter does not do anything at all. The only solution I see to this ridiculous problem is to run Nginx as root, which I know is a bad idea. I've searched almost every discussion on the web and I cannot … -
Keeping information from model Django
I have a project and when users logged in they have to choose a company and unit after that when user is working how can keep the company_id and unit_id? Because user have to be only adding data that company_id and unit_id I tried keeping ids from url with int:company_id/sint:unit_id but it can't work -
csv file stored in Django members directory loaded as directory instead of csv file
I am working in a Django app in a directory myworld. In this directory, I have a members directory with a templates directory with an html file myfirst.html. In the html file, I have this code: <script src="https://d3js.org/d3.v7.min.js"></script> <script> const loadData = () => { return d3.csv("/members/employees").then((data) => { for (var i = 0; i < data.length; i++) { console.log(data[i].Name); console.log(data[i].Age); } } ) }; loadData(); </script> And the contents of employees.csv is: Name, Age John, 30 Jane, 32 (I'm following an example here). However instead of getting the output that they get on that link, namely: John 30 Jane 32 I only get many lines of Undefined. On the django side, the terminal says: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 27, 2022 - 11:14:57 Django version 4.1.2, using settings 'myworld.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. HTTP GET /members/ 200 [0.16, 127.0.0.1:51510] HTTP GET /static/myfirst.css 200 [0.01, 127.0.0.1:51510] HTTP GET /static/myfirst.jss 200 [0.00, 127.0.0.1:51510] HTTP GET /members/employees 301 [0.00, 127.0.0.1:51510] HTTP GET /members/employees/ 200 [0.00, 127.0.0.1:51510] I tried seeing if the data was even loaded from the file correctly, but something … -
Why my validation is not working in django-rest serializer?
Appointment is being registered although I am providing before time in start time for appointment. models.py class Appointment(models.Model): status = models.CharField( choices=APPOINMENT_STATUSES, max_length=20, default=SCHEDULED, help_text="", ) full_name = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_TYPE, max_length=10, default=MALE) email = models.EmailField() phone_no = models.CharField(max_length=10, validators=[validate_phone_no]) start = models.DateTimeField(max_length=50, help_text="Appointment start Date & Time") end = models.DateTimeField(max_length=50, help_text="Appointment End Date & Time") doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT, blank=True, null=True) message = models.TextField() def __str__(self): return self.full_name serializers.py class AppointmentCreateSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = '__all__' def create(self, validated_data): return super().create(validated_data) def validate(self, attrs): # check appointment start and end time if attrs["start"] < timezone.now(): raise serializers.ValidationError("Appointment date cannot be in the past") if attrs["start"] >= attrs["end"]: raise serializers.ValidationError( f"Appointment end date/time should be after than start/date time." ) return super().validate(attrs) Description: This is my appointment model and serializer for that. Why my validation is not working. I want, the user wont be able to create appointment if the start date and time is before current date and time. ----------------> But Appointment is getting registered, if User is entering today date but before time . What's Wrong with this? and What can be better solution for this problem? -
i want to change 'add cart' button to 'plus' ,'value', and 'minus' when click on "add cart" in shopping cart
$(".cart").click(function () { var idstr = this.id.toString(); console.log(idstr); if (cart[idstr] != undefined) { console.log("exist"); qty = cart[idstr][0] + 1; console.log(qty); console.log(cart[idstr][0]); } else { qty = 1; price = document.getElementById("price" + idstr).innerHTML; image = document.getElementById("img" + idstr).src; aname = document.getElementById("name" + idstr).innerHTML; console.log("not"); cart[idstr] = [qty, aname, image, price]; } console.log(cart); updateCart(cart); localStorage.setItem("cart", JSON.stringify(cart)); }); function updateCart(cart) { for (var item in cart) { document.getElementById("div" + item).innerHTML = "<button id='minus" + item + "' class='btn btn-primary minus'>-</button> <span id='val" + item + "''>" + cart[item][0] + "</span> <button id='plus" + item + "' class ='btn btn-primary plus'>+</button>"; } } this happened when i try i am expecting this when i clicked on add cart button it didnt change to my expected buttons its means my function updateCart not working -
Django - How to store country name?
I am using a proxy model in django: from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.IntegerField() name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 if Country.objects.filter(name=self.name).exists(): pass else: super().save(*args, **kwargs) class State(customer_location): country_name = models.CharField(max_length=100) class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() try: country_obj = Country.objects.get(name=self.country_name) #error here self.parent_id = country_obj.id except Country.DoesNotExist: self.parent_id = 777 #FIX THIS PARENT ID super().save(*args, **kwargs) Now as you can see i have declared country_name inside state proxy model so that i can get the id of country stored in the database. Basically i want to set state parent_id = country id and i am not able to do it. I am very close i guess but stuck at last step i guess so? Can someone please help? The error i get is: django.core.management.base.SystemCheckError: ?[31;1mSystemCheckError: System check identified some issues: … -
Ajax Request to ApiView endpoint raises forbidden http error
I have been trying to to an AJAX Request to an ApiView endpoint. $.ajax({ url: '{% url 'edit_custom_user_additional_info' %}', method: "patch", data: $form.serialize(), header: { "X-CSRFToken": "{{ csrf_token }}" }, success: function (data) { alert("Dati aggiuntivi salvati con successo"); }, error: function (data) { console.log("Errore durante il salvataggio dei dati aggiuntivi"); }, }); I have also added the {% csrf_token %} to the form but I still get Forbidden error. I have also tried to add the CSRF Exempt but still the error. How can I fix that? -
Deploying Django app to Elastic Beanstalk Docker platform
Im'm trying to deploy a django app to single docker container platform on EB version Docker running on 64bit Amazon Linux 2/3.5.2. This is what I've done so far: Created Dockerfile and compose, pushed the image to ECR, Created Dockerrun.aws.json and it looks like this: { "AWSEBDockerrunVersion": "1", "Image": { "Name": "URI to the ECR repository", "Update": "true" }, "Ports": [ { "ContainerPort": 8000, "HostPort": 8000 } ] } Created sample app in Elastic Beanstalk. Uploaded the Dockerrun.aws.json file as the source code Now the EB url is taking to a "This site can't be reached" page but in the logs I can't find the specific error instead I see a message stating that deployment has succeeded Also when I run eb locally like this eb local run --port 8080, eb local open, it's working just fine. Let me know if there's anything else I need to share. -
optmizing queries in django
Here I have four models Category, Products, ProductOffer and CategoryOffer. The CategoryOffer is Foreignkey to Category and ProductOffer is Foreignkey to Products. And while a product have an offer and the category having the product also have an offer. I'll compare both offers and shows whichever is higher. So far everything is working but when I looked on to how much queries is getting executed. It's a lot. It's shown below: (0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default (0.016) SELECT "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_products" INNER JOIN "inventory_category" ON ("inventory_products"."category_id" = "inventory_category"."id") WHERE "inventory_products"."is_available"; args=(); alias=default (0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default (0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default (0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM … -
django: Page not found (404)
project/urls.py from django.contrib import admin from django.urls import path, include from django.http import HttpResponse urlpatterns = [ path("admin/", admin.site.urls), path("", include('todo.urls')), ] setting.py TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] todo/ulrs.py from django.urls import path from . import views urlpatterns = [ path("login", views.home), ] todo/views.py from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, 'index.html') I don't know why it is not showing my page... I have created django project called taskly. And in that project I have only 1 app called todo. I have referred templates folder as well as you can see above. In that template folder there is only 1 page index.html -
Django 'User' object has no attribute 'profile'
Good day to all of you we are facing a problem when I create a user profile with signals when I enter the register section 'str' object has no attribute 'get' my View: from django.shortcuts import render,redirect from .forms import LoginForm,RegisterForm from django.contrib.auth import authenticate,login,logout from django .contrib.auth.models import User # Create your views here. def Login_view(request): form=LoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) login(request,user) return redirect('index') return render(request,'accounts/login.html',{'form':form}) def Register_view(request): form=RegisterForm(request.POST or None) if form.is_valid(): user=form.save(commit=False) password=form.cleaned_data.get('password1') user.set_password(password) user.save() new_user=authenticate(username=user.username,password=password) login(request,new_user) return redirect('index') return render(request,'accounts/register.html',{'form':form}) def logout_view(request): logout(request) return redirect('index') My Signals from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import UserProfile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() My Model: class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) username=models.CharField(verbose_name='Kullanıcı Adı',max_length=40) name=models.CharField(verbose_name='ad',max_length=40) surname=models.CharField(verbose_name='Soyad',max_length=40) bio=models.TextField() avatar=models.ImageField(null=True,blank=True) I used the signals part for the user profile, but I'm making a mistake somewhere, I need to solve it -
having issues with my django project on vscode
i tried running my project and its showing this error message ModuleNotFoundError: No module named 'models' i kept models in my settings.py in my installed apps but still did not work -
cannot import name 'InvalidAlgorithmError' from 'jwt'
I am trying to implement djangorestframework-simplejwt in djanog project. when I try to post username and password show error. include this following line. from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] asgiref==3.5.2 Django==4.0 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 mysqlclient==2.1.1 PyJWT==2.6.0 pytz==2022.6 sqlparse==0.4.3 tzdata==2022.6 -
i use append in for loop of local storage ,i want to display item in a new line every time loop finished
for(item in cart){ let name =cart[item][1]; let qty =cart[item][0]; let image =cart[item][2]; let price=cart[item][3]; mystr=` <td class="product-thumbnail"><a href="shop-details.html"><image src="${image}" alt="product"> </a></td> <td class="product-name">${name}</td> <td class="product-price"><span class="amount">${price}</span></td> <td class="product-quantity"> <button id='plus" + item + "' class ='btn btn-primary plus'>+</button> <span id="quantity" >${qty}</span> <button id='minus" + item +"' class='btn btn-primary minus'>-</button> </td> <td class="product-subtotal"><span class="amount"></span></td> <td class="product-remove"><a href="#"><i class="fa fa-times"></i></a></td> ` console.log(mystr); $('#items').append(mystr) } i want to display every item in new line not all items in same line i expect this -
Django Soak Testing Bulk Request at once
I want to test whether Django can handle heavy load requests at once continuously. How to conduct this scenario? using tests?. Eg: 300 Read requests 300 Write requests within 1 sec. You can take any basic ORM query like User.objects.get(id=`some id) for 1 request and take this as 300 different read requests. Same for write requests as well but change any field of your choice. Later check if that works for at-least 10 sec. You can think of this scenario as multiple concurrent users using the Django app. -
Annotate value to a many to many field in django
I have a model: class A(models.Model): ... users = models.ManyToManyField(User) ... I want to annotate some data to users of an instance of model A. I was doing something like this: a=A.objects.filter(id=2).first() a.users.all().annotate(games_played='some condition here') but this statement is returning a queryset of User model. Is it possible to annotate data to a many to many field of an instance and still have an object of model A so that I can do this; a.users.all()[0].games_played