Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Preciso trazer as informações do banco de dados para o index.html
Preciso trazer as informações do banco de dados e rendereizar na pagina index.html apresenta o seguinte erro. (env) PS E:\crudpython> & e:/crudpython/env/Scripts/python.exe e:/crudpython/core/views.py Traceback (most recent call last): File "e:\crudpython\core\views.py", line 2, in from .models import Produto ImportError: attempted relative import with no known parent package (env) PS E:\crudpython> enter image description here -
How to filter by author in Django? Getting error: Field 'id' expected a number
I have a Django application that functions like a diary, where the homepage is an index list of all diary entries previously created. I am now trying to filter the index so that the user will only see the diary entries that they have created. Here is what I have done: Views.py from django.shortcuts import render from .models import DiaryEntry from django.views import generic from django.views.generic.edit import CreateView def index(request): """View function for MyDiary.""" author = DiaryEntry.author diary_entry = DiaryEntry.objects.filter(author=author).order_by('-created_on') context = { "diary_entry": diary_entry, } return render(request, 'diary_index.html', context=context) class EntryDetailView(generic.DetailView): model = DiaryEntry def get_data(self, **kwargs): context = super(EntryDetailView, self).get_data(**kwargs) return context class EntryCreate(CreateView): model = DiaryEntry fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Models.py from django.db import models from django.urls import reverse from django.conf import settings User = settings.AUTH_USER_MODEL class DiaryEntry(models.Model): title = models.CharField(max_length=255) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete = models.CASCADE ) def __str__(self): """String for representing the diary object.""" return self.title def get_absolute_url(self): """Returns the url to access a detail record for this user entry.""" return reverse('entry-detail', args=[str(self.id)]) HTML: {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>This is your diary!</h1> <hr> <h2>Here, … -
Unable to connect browser to any of my docker images
I downloaded cookiecutter django to start a new project the other day. I spun it up (along with postgres, redis, etc) inside docker containers. The configuration files should be fine because they were all generated by coockicutter. However, once I build and turn on the containers I am unable to see the "hello world" splash page when I connect to my localhost:8000. But there is something going wrong between the applications and the containers because I am able to connect to them via telnet and through docker exec -it commands etc. The only thing I can think of is some sort of permissions issue? So I gave all the files/directors 777 permissions to test that but that hasnt changed anything. logs % docker compose -f local.yml up [+] Running 8/0 ⠿ Container dashboard_local_docs Created 0.0s ⠿ Container dashboard_local_redis Created 0.0s ⠿ Container dashboard_local_mailhog Created 0.0s ⠿ Container dashboard_local_postgres Created 0.0s ⠿ Container dashboard_local_django Created 0.0s ⠿ Container dashboard_local_celeryworker Created 0.0s ⠿ Container dashboard_local_celerybeat Created 0.0s ⠿ Container dashboard_local_flower Created 0.0s Attaching to dashboard_local_celerybeat, dashboard_local_celeryworker, dashboard_local_django, dashboard_local_docs, dashboard_local_flower, dashboard_local_mailhog, dashboard_local_postgres, dashboard_local_redis dashboard_local_postgres | dashboard_local_postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization dashboard_local_postgres | dashboard_local_postgres | 2022-07-07 14:36:15.969 … -
Call a function in DetailView, views.py. which returns bool. Django, python
I am building an e-commerce website with django. There is a homepage which lists all items on website and when the user click on any of those items they will direct to details page which shows details about that item. Also on that detail page, I added a "wishlist" button so that users can add that item to their wishlist. My problem is, if the user does not have that item in their wishlist, I want to display "Add to wishlist" button to add that item to their wishlist when they clicked on it, otherwise I want to display "remove from wishlist" button to remove the item from their wishlist when they clicked on it. I have two separate function to add and remove items and they perfectly work but I want to display only one of the buttons "add" or "remove" by checking if that item exists in their wishlist or not. So my logic was writing a function checks if the user has that item in their wishlist or not in DetailView which displays the "detail" page in views.py and display only one of them but I couldn't. This is views.py class ItemDetailView(FormMixin, DetailView): model = Auction form_class … -
Django - TailwindCSS won't load some attributes
I'm having issues when it comes to using some attributes with Django and TailwindCSS. Let's take this table for example: <div class="relative overflow-x-auto shadow-md sm:rounded-lg"> <table class="w-full text-lg text-left text-gray-500 rounded-2xl mt-4 dark:text-gray-400"> <thead class="rounded-2xl text-lg text-white uppercase bg-[#68BA9E] dark:bg-gray-700 dark:text-gray-400"> <tr> <th scope="col" class="px-6 py-3"> Report title </th> <th scope="col" class="px-6 py-3"> Company </th> <th scope="col" class="px-6 py-3"> Brand (if any) </th> <th scope="col" class="px-6 py-3"> Go to report </th> </tr> </thead> <tbody> {% for report in reports %} <tr class="bg-white border-b text-center dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"> <th scope="row" class="h-19 px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap"> {{ report.title }} </th> <td class="px-6 py-4"> {{ report.company }} </td> <td class="px-6 py-4"> {% if report.brand %} {{ report.brand }} {% else %} - {% endif %} </td> <td class="px-6 py-4"> <a href="{% url 'tool:single-report' slug=report.slug %}">Access</a> </td> </tr> {% endfor %} </tbody> </table> </div> Gives the following: But when I try to change the bg-color from: <thead class="rounded-2xl text-lg text-white uppercase bg-[#68BA9E] dark:bg-gray-700 dark:text-gray-400"> To: <thead class="rounded-2xl text-lg text-white uppercase bg-red-700 dark:bg-gray-700 dark:text-gray-400"> The new color won't load. It gives: I don't understand why I'm getting nothing. In my configuration, following tasks are running: The server is running with python manage.py … -
How to use multiple models in django class based generic list view
Here, my code for models.py file, from django.db import models from config.g_model import TimeStampMixin # Create your models here. class Variant(TimeStampMixin): title = models.CharField(max_length=40, unique=True) description = models.TextField() active = models.BooleanField(default=True) class Product(TimeStampMixin): title = models.CharField(max_length=255) sku = models.SlugField(max_length=255, unique=True) description = models.TextField() class ProductImage(TimeStampMixin): product = models.ForeignKey(Product, on_delete=models.CASCADE) file_path = models.URLField() class ProductVariant(TimeStampMixin): variant_title = models.CharField(max_length=255) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ProductVariantPrice(TimeStampMixin): product_variant_one = models.ForeignKey(ProductVariant, on_delete=models.CASCADE, null=True, related_name='product_variant_one') product_variant_two = models.ForeignKey(ProductVariant, on_delete=models.CASCADE, null=True, related_name='product_variant_two') product_variant_three = models.ForeignKey(ProductVariant, on_delete=models.CASCADE,null=True, related_name='product_variant_three') price = models.FloatField() stock = models.FloatField() product = models.ForeignKey(Product, on_delete=models.CASCADE) now here I am using this class based list view, class ProductListView(generic.ListView): model = Product template_name = 'products/list.html' context_object_name = 'products' paginate_by = 2 def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) products = self.get_queryset() page = self.request.GET.get('page') paginator = Paginator(products, self.paginate_by) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context['products'] = products return context I want to use productimage,product variant and product variant price in my template,I don't know actually how to use multiple models on this view ,if anyoneone can suggesst me it will be helpful -
django website that add name of uer on greeting image , how to refuse None names and how refuse accsess to "/pic" page?
I'm trying to make a django website that take name of user and add it to greeting picture now I'm using return return FileResponse(i_mg) to show picture with name of user in another page that name pic.html but i found its doesn't useful because everyone can accesses to the page direct and the website will show name is None how can i use a unique URL for every user and refuse None name ? this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect from PIL import Image,ImageDraw , ImageFont from django.http import FileResponse,HttpResponse # Create your views here. def Home(request): return render(request , 'index.html') def Show(request): name_input = str(request.POST.get('user_name')) img = Image.open("C:\\Users\\kmm\\Desktop\\my_django_stuff\\Eid_G\\files\\covers\\mypic.png") d = ImageDraw.Draw(img) fnt = ImageFont.truetype('C:\\Users\\kmm\\Desktop\\fonts\\static\Cairo-Bold.ttf',40) message = name_input d.text((540,1020),message, font=fnt, fill=(237, 185, 117),anchor="ms") img.save('Images/'+name_input+'.png') save_in_model = Name(massenger_name=name_input,image=name_input+'.png') save_in_model.save() i_mg = open('Images/'+name_input+'.png','rb') if name_input is None: return redirect(Home) else: return FileResponse(i_mg) this my urls.py from django.contrib import admin from django.urls import path from Eid_Post import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',views.Home), path('pic',views.Show) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) this my index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> … -
Django Rest Framework: ordering lost when try to return get_queryset() in get method of modelviewset
in get_queryset I'm able to get the list of candidates in a order that i want but when i return it, then in the API response I'm seeing it in a different order serilizer.py class CandidateListSerializer(serializers.ModelSerializer): """ Candidate serializer """ job_skill_detail = serializers.SerializerMethodField(read_only=True) job_role_detail = serializers.SerializerMethodField(read_only=True) primary_skills_detail = serializers.SerializerMethodField(read_only=True) def get_job_skill_detail(self, obj): if obj.job_skill: return obj.job_skill.name def get_job_role_detail(self, obj): if obj.job_role: return obj.job_role.name def get_primary_skills_detail(self, obj): return obj.primary_skills.all().values( "id", "name", ) class Meta: model = Candidate fields = "__all__" my view.py get_queryset function in modelviewset api def get_queryset(self): if "Admin" in self.request.user.role or "Recruiter" in self.request.user.role: return self.queryset if "Client" in self.request.user.role: candidates_source_to_client = CandidateSubmission.objects.filter(company=self.request.user.company).values_list('candidate', flat=True) print(f"Candidates id from candidate submission model: {candidates_source_to_client}") candidates = self.queryset.filter( Q( band__in=CompanyBands.objects.filter( company=self.request.user.company ).values_list("band", flat=True) ) | Q(id__in=candidates_source_to_client) ) print(f"candidates from database with cliend company and company band: {candidates}") candidates_final = candidates.annotate( relevancy=Count(Case(When(id__in=candidates_source_to_client, then=1))) ).order_by("-relevancy") print(f"final candidates list: {candidates_final}") return candidates_final my print response from the final candidate list I'm getting final candidates list: <QuerySet [<Candidate: Amresh Giri>, <Candidate: Dishita Vishwakarma>, <Candidate: Rhaan Kumaad 2>, <Candidate: Raan Kaad>, <Candidate: Vigneshkumar Chinnadurai>, <Candidate: Rhan Kumad>, <Candidate: Apurva Dhakre>, <Candidate: Saiba Kumar>, <Candidate: Ramona>] This is the order that I want but am not able to … -
Changing style color via JavaScript isn't working
I have been trying to change the style color of an input field when a certain option is selected but it is not working. I have tried both onclick and oninput but to no avail. I suspect the issue lies with {{ type }} or == 'Buy'. function changeColor () { var transaction_type = document.getElementById('buysell'); var option_user_selection = transaction_type.options[ transaction_type.selectedIndex ].text; if (option_user_selection == 'Buy') { document.getElementById('costb').style.color = '#006400'; } else { document.getElementById('costb').style.color = '#DC143C'; } } <div class="transaction_type"> <p>Transaction Type:</p> <select style="font-size:16px" class="form-select" id='buysell' required> {% for type in form.transaction_type %} <option>{{ type }}</option> {% endfor %} </select> </div> forms.py transaction_choices = [ ('BUY', 'Buy'), ('SELL', 'Sell'), ] transaction_type = forms.CharField( max_length=4, widget=forms.Select( choices=transaction_choices, attrs={ 'class': 'form-select', 'name': 'transaction_type', 'id': 'floatingTransaction', 'oninput': 'changeColor();' }) ) cost_basis = forms.DecimalField( min_value = 0, widget = forms.NumberInput(attrs={ 'class': 'form-control', 'name': 'cost_basis', 'id': 'costb', }) ) -
Not able to Proxy Apache properly
I use a Django application. I want to access it via Apache. So, I've made DEBUG=False and tried to proxy ProxyPass "/" "http://localhost:8000/" So it routes to my application. Only problem is.. the static files don't load with this method. Therefore, I tried to put static folder in /var/www/html/static In console, this is where all the calls are going but they still don't load. This is my config file There must be something i'm missing or do not understand. Can someone please enlighten with some explanation! -
Django: there is no unique constraint matching given keys
I created an extension of the standard user model in models.py called Client. I added a manytomany relationship to it to indicate which clients are related to another: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) clients = models.ManyToManyField("self", blank=True) This works perfectly fine in my local dev environment where I use python manage.py runserver. However, when I try to run python manage.py migrate on our testing server using a postgresql database, I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "content_client" What am I missing here? -
Django Rest Framework upload_to doesn't work as desired
I'm passing callable for image field in my project like this def profile_picture_path(instance, filename): """Path for uploading profile pictures in media directory""" return f"user/profile_picture/{instance.pk}/{filename}" class User(AbstractUser): profile_picture = models.ImageField(_("profile picture"), upload_to=profile_picture_path, null=True, blank=True) When I add a user through the admin panel, the image gets a proper path: user/profile_picture/3/pfp.png. Problem comes when I send a post request to registrate: user/profile_picture/None/pfp.png # views.py @api_view(["POST"]) def register_view(request): """ Register View which takes only post method. """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # serializers.py class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): exclude = kwargs.pop("exclude", None) super().__init__(*args, **kwargs) if exclude is not None: for field_name in exclude: self.fields.pop(field_name) password = serializers.CharField(write_only=True) class Meta: model = User exclude = ["deleted", "deleted_by_cascade"] How can I fix this and get correct path for image uploads? -
using EmailMultiAlternatives in Django but it randomly stopped sending emails
I'm using Django and the email code is within a try except block that also creates a user. The code is creating the user, but when it comes to sending the welcome email, it's suddenly failing, and defaults to the except clause, which notifies the user that an account already exists with that email. After some debugging I realized that all of the code works right up until msg.send(), but this particular code hasn't been touched since February, when the website went live. I don't understand why it stopped working. in my settings.py: EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mandrillapp.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True in my views.py: htmly = get_template('main/new_account.html') d = {'name': data['first_name'], 'base': os.getenv('HOST_URL')} subject, from_email, to = 'New Account', os.getenv('EMAIL_HOST_USER'), email html_content = htmly.render(d) msg = EmailMultiAlternatives( subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") try: msg.send() except: print('message did not send') in my terminal: Conflict: /api/user/account/create -
i added & instead of | between Q objects but it does not work
Sometimes i will search for type and color only or name and year only, so Q should be able to compile request together for example if i write "url/search/?q=action&q=Blue" it returns only the last query which in this case is "Blue" views.py def search_result(request): query = request.GET.get('q') qs = Content.objects.distinct().search(query=query) query_string = request.GET.get('q') query_string = query_string.replace(';',',') page = request.GET.get('page', 1) pagination = Paginator(qs, CONTENTS_PER_PAGE) try: qs = pagination.page(page) except PageNotAnInteger: qs = pagination.page(CONTENTS_PER_PAGE) except EmptyPage: qs = pagination.page(pagination.num_pages) context = { 'SearchResults': qs, 'query': query_string, } return render(request, 'home/search_result.html', context) models.py class ContentQuerySet(models.QuerySet): def search(self, query=None): if query is None or query == "": return self.none() lookups = Q(genre__name__icontains=query) & Q(distributor__icontains=query) & Q(title__icontains=query) & Q(channels__name__icontains=query) & Q(year__icontains=query) return self.filter(lookups) class ContentManager(models.Manager): def get_queryset(self): return ContentQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) class ChannelQuerySet(models.QuerySet): def search(self, query=None): if query is None or query == "": return self.none() lookups = Q(name__icontains=query) return self.filter(lookups) class ChannelManager(models.Manager): def get_queryset(self): return ChannelQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) -
gmail is not sending from django web application
I have created a Python-Django web application. I tried to send an email to a user, but it is not working. How Can I solve it ? #SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_POSRT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER = 'fhcollege@gmail.com' EMAIL_HOST_PASSWORD = '' This from my settings.py file My views.py file is email=EmailMessage( 'PAYMENT SUCCESSFULL', 'welcome', settings.EMAIL_HOST_USER, ['fhcollege@google.com'] ) email.fail_silently = False email.send() How can I solve the issue ? The Error showing is TimeoutError at /payments/4 [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:9000/payments/4 Django Version: 4.0.2 Exception Type: TimeoutError -
i am not able to link pages in django my code is correct .What else i need to do?
in urls.py file my code is: from django.urls import path from . import views urlpatterns = [ path("<str:name>", views.index ,name="index"), ] in views.py file my code is: from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item # Create your views here. def index(response,name): ls=ToDoList.objects.get(name=name) return HttpResponse("<h1>%s</h1>" %ls.name) path also added in urls.py-mysite error showing page not found -
Remove inheritance from model retaining IDs
I have a two classes, one of which inherits from the other class Drink(models.Model): .... class Juice(Drink) .... Now, this was a mistake and I would like to remove the inheritance and have the Juice model to be a normal model Juice(models.Model). Yet, I would like to retain the sequence of IDs that are in the superclass. Due to the inheritance, the superclass has an auto ID field and the subclass has a pointer field (drink_ptr_id). What happens now when I just change the syntax is that django tries to add an auto ID field to the juice model and wants me to set a default value. The obvious problem is that I need the sequence of the supermodel to be copied into the auto ID field of the subclass model and I cannot just add a default value. A second problem - which is rather strange to me - is that the subclass already has an auto-incremented ID field, so there is a clash between the newly created field and the old id field. I tried to follow the advice given in this post: Remove model inheritance and keep id in newly created autofield, which is pretty much a … -
Why isn't Mypy inferring a 3rd-part library function's type?
Considering this code: class ExportView(IndexView): model_admin: Optional[ModelAdmin] = None def export_csv(self) -> HttpResponse | StreamingHttpResponse: fields = getattr(self.model_admin, "csv_export_fields", []) return render_to_csv_response(self.queryset.all().values(*fields)) I get the following error from Mypy on the return line: error: Returning Any from function declared to return "Union[HttpResponse, StreamingHttpResponse]" [no-any-return] render_to_csv_response is a method from django-queryset-csv, and Pyright correctly infer its return type as being a Union[HttpResponse, StreamingHttpResponse]. I thought that Mypy was not reading the 3rd-part library, as if running with --follow-imports=skip, but my pyproject.toml config has set silent, which behaves in the same way as normal [tool.mypy] plugins = ["mypy_django_plugin.main"] disallow_untyped_defs = true ignore_missing_imports = true follow_imports = 'silent' no_incremental = true warn_redundant_casts = true warn_unused_ignores = true warn_return_any = true warn_unreachable = true enable_error_code = 'ignore-without-code' show_error_codes = true Changing it to normal doesn't fix the issue either. Any idea how to get Mypy to find the proper type, like Pyright does out of the box? -
ImportError: cannot import name 'zoneinfo' from 'backports' (unknown location)
I am trying to deploy my Django model on an Apache2 server and it is running well on 'ip':8000. But when i am trying to run without 8000 port after completing all prerequisites i am getting this error [Thu Jul 07 10:18:36.178228 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module [Thu Jul 07 10:18:36.178240 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] return _bootstrap._gcd_import(name[level:], package, level) [Thu Jul 07 10:18:36.178247 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/root/novo-ai-api-main/backend/dj/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 20, in <module> [Thu Jul 07 10:18:36.178253 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] from django.db.backends.base.base import BaseDatabaseWrapper, timezone_constructor [Thu Jul 07 10:18:36.178260 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/root/novo-ai-api-main/backend/dj/lib/python3.8/site-packages/django/db/backends/base/base.py", line 12, in <module> [Thu Jul 07 10:18:36.178277 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] from backports import zoneinfo [Thu Jul 07 10:18:36.178308 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] ImportError: cannot import name 'zoneinfo' from 'backports' (unknown location) These are my all working files 000-default.conf <VirtualHost *:80> #ServerAdmin webmaster@localhost DocumentRoot /root/novo-ai-api-main ErrorLog /root/novo-ai-api-main/error.log CustomLog /root/novo-ai-api-main/access.log combine <Directory /root/novo-ai-api-main/backend/server/server> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /root/novo-ai-api-main/static <Directory /root/novo-ai-api-main/static> Require all granted </Directory> WSGIScriptAlias / /root/novo-ai-api-main/backend/server/server/wsgi.py WSGIDaemonProcess django_app python-path=/root/novo-ai-api-main/backend/server python-home=/root/novo-ai-api-main/backend/dj/ WSGIProcessGroup django_app … -
Struggling to display data I am trying to insert on webpage
I am currently doing CRUD with Products model and I am having a hard time displaying the data that I am trying to insert. model class Products(models.Model): categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) color = models.CharField(max_length=15) size = models.CharField(max_length=15) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) show and insert function def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) return render(request,'polls/product_insert.html') html page of insert and show respectively <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="1">9-6 WEAR</option> <option value="2">DESI SWAG</option> <option value="3">FUSION WEAR</option> <option value="">BRIDAL WEAR</option> </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <input type="text" name="sub_categories" placeholder="SUB_CATEGORIES"> </td> </tr> <tr> <td>Colors</td> <td> <input type="text" name="color" placeholder="Enter Colors"> </td> </tr> <tr> <td>Size</td> <td> <select class="form-select" aria-label="Default select example" name="size"> <option selected>Open this select menu</option> <option value="SM">SM</option> … -
Is there a signal/hook to know when a password reset has been triggered or if a password reset email has been sent in django allauth?
I'm trying to send emails via another service for password reset alone. Django only allows you to set one email provider, but I'm not sure how to delegate different emails to different email providers. Is this possible to do by listening to a signal like password_reset_sent or something similar? What I want to achieve is this: Default email sending: use client X if password reset email sending: use client Y Is this possible using django allauth? -
Django With Apache And mod_wsgi: Memory Leak?
My problem is that over time the memory usage (especially the virtual memory) increases until the system freezes. Last time the virtual memory of the "/usr/sbin/apache2 -k start" process has used over 8GB virtual memory. It was several days from the last apache2 restart. I have a virtual Machine with 1GB RAM and 15GB HDD where I have Ubuntu 22.04 installed with Apache/2.4.52 over apt with mod_wsgi, a python virtual environment where Django 4.0.5 is installed via pip. I do not run Django in daemon mode but in the "default" mode. I changed nothing in apache2.conf. My site-configuration looks like this: WSGIPythonHome /var/www/venv WSGIPythonPath /var/www/venv/fye_backend <VirtualHost *:80> ServerAdmin (my email) WSGIScriptAlias / /var/www/venv/fye_backend/fye/wsgi.py ErrorLog /var/www/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I server the files like this code (in views.py): def example(request): key = request.GET.get("key") some_info = some_model.objects.get(key) return HttpResponse(some_info) 1 Day current Virtual Memory usage 1 Day current RAM usage If more information is needed please let me know. Thanks! -
Django Rest Framework JWT authentication - user logged in after drop database
Like I mentioned in the title. I have a DjangoRestFramework application which uses JWT token authentication on the backend. The issue occurs when I log as user, and save the token in the cookies. Next, I drop the database, and create same user with same credential programatically on the backend. Finally when I open the browser, the user is still logged in, although technically the whole database was wiped out, and set up from scratch. Is this the expected behaviour for JWT or maybe there is a way to make sure, that those tokens expire when database is dropped ? Thanks -
Django: How to get value in one model from the other model?
It feels like a very simple question, but how to get value in one model from the other one in django? I have my models.py like this: class Patient(models.Model): id = models.AutoField(primary_key=True, verbose_name='Patient ID') class Salvage_Treatment(models.Model): id = models.AutoField(primary_key=True) id_patient = models.ForeignKey(Patient, on_delete=models.CASCADE) Salvage_treatment_end_date = models.DateField() class Survival_Parameters(models.Model): id = models.AutoField(primary_key=True) salv_treat = models.ForeignKey(Salvage_Treatment, on_delete=models.CASCADE) salvage_treatment_end_date = models.DateField() id_patient = models.ForeignKey('Patient', on_delete=models.CASCADE) Let's assume that I have a patient with id_patient = 2 and I fullfiled the Salvage_Treatment form for him with id=1 (id of this form) and some date in Salvage_treatment_end_date. Now I need to have this same date to be put automatically in Survival_Parameters.salvage_treatment_end_date. How can I do that? I don't want to choose which Salvage_Treatment form to get the data from - instead I ONLY want to select the patient's ID. -
get error message on already registerd email
i got a popup on this code for sucess when someone subs to newsletter, i cant figure out how to get an popup when there is an error when it dosent work due to email already in database. with a message that email is already registerd. The multiple email code i already got in my django code that handels the multiple email part. email = models.EmailField(max_length=255, unique=True) {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} <div id="delivery-banner" class="row text-center"> <div class="col bg-success text-white"> <h4 class="logo-font my-1">Sign up to Newsletter and get 5% discount</h4> </div> <div class="content-wrapper text-center bg-warning container-fluid" id="newsletter-wrapper"> <form v-on:submit.prevent="onSubmit"> <div class="card text-black bg-warning mb-3"> <div class="card-footer"> <div class="alert alert-success" role="alert" v-if="showSuccess"> You are Subscribed to our Newsletter! </div> <h2>Subscribe to our newsletter</h2> <div class="form-group"> <input type="email" class="" v-model="email" name="email" class="input" placeholder="e-mail address" required> </div> <div class="form-group"> <button class="btn btn-success ">Submit</button> </div> </div> <div class="social"> <a target="_blank" rel="noopener noreferrer" href="https://facebook.com/" class="btn btn-social-icon btn btn-primary btn-outline-facebook "><i class="fa fa-facebook"></i></a> <a target="_blank" rel="noopener noreferrer" href="https://youtube.com/" class="btn btn-social-icon btn btn-danger btn-outline-youtube"><i class="fa fa-youtube"></i></a> <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/" class="btn btn-social-icon btn btn-info btn-outline-twitter"><i class="fa fa-twitter"></i></a> <a target="_blank" rel="noopener noreferrer" …