Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count elements in Django
I am learning Django. I have a question about counting elements from tables. class Opinion(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) users = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) books = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) rate = models.IntegerField() description = models.TextField() def __str__(self): return self.user_id.username + ' ' + self.book_id.title My table Opinion is in relationship with built-in table User. I am wondering how can I count how many opinions each user has added? I would like to show information about users and the amount of opinions they have added on my website. Thanks for the help. -
I am trying check if user is authenticated navigate to dashboard . There is no error in console and network. How can I fix this?
I am developing a authentication system using Django, DRF and Djoser in backend and React, reduxtool kit in front end. Every thing works perfectly fine exept mapStatToProps which provide isAuthenticated const mapStateToProps = (state) => ({ isAuthenticated: state.auth?.isAuthenticated, } doesn't work when I use it as if (isAuthenticated) { return <Navigate to="/dashboard" />; } to redirect page to dashboard in login.jsx. I don't why. Please help me to fix this bug. redux state in redux devtool shows { rootReducer: { auth: { access: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYyMjAwMTM4LCJqdGkiOiJjMjY1OGE5YjM2MTg0NjMxYTRhOTNlYzNiNjZmNDc1MSIsInVzZXJfaWQiOjR9.rpBooY2zuHQE7ttl8DFjR3XSam3B6f55ZYMF_jQeyJc', refresh: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY2MjI4MjkzOCwianRpIjoiODM2ZTA1OGVmMTU4NDUxN2I5ZDViNWExMGU1YThkZmMiLCJ1c2VyX2lkIjo0fQ.MzEIvO6vmEhJZ2v3_TZCC4k3gBaKEVeES4OzAaq9DBI', isAuthenticated: true, user: { email: 'ripyschool@gmail.com', id: 4, username: 'ripyschool' } } } } #my loginpage import React, { useState } from "react"; import { Link, Navigate } from "react-router-dom"; import { connect } from "react-redux"; import { login } from "../actions/auth"; import axios from "axios"; import style from "../assets/styles/Login.module.css"; import { FaGoogle } from "react-icons/fa"; import { FaGithub } from "react-icons/fa"; import FormLayout from "../hocs/FormLayout"; const Login = ({ login, isAuthenticated }) => { const [formData, setFormData] = useState({ username: "", password: "", }); const { username, password } = formData; const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = (e) => { e.preventDefault(); login(username, password); }; const continueWithGoogle … -
Django Pycharm Process finished with exit code -1
Recently when i run Django project server on 0.0.0.0 port 8000 (I should run on 0.0.0.0 instead of 127.0.0.1) randomly in some requests return this error and kill the process(completely random). Process finished with exit code -1 And after reload, on first request give save error I use window 10 and Pycharm v 2021.2.2 it seems it's bug of Pycharm. Because there is no problem when deploy on the server -
AttributeError: 'WSGIRequest' object has no attribute 'get' I got this error earlier and I didn't find my answer here
I am going through a django course and I got this error earlier but the tutor doesn't !!! what should I do ??? this is my code below views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Project from .forms import ProjectForm def projects(request): objs = Project.objects.all() context = {"projects": objs} return render(request, 'projects/project.html', context) def dynamic(request, text): obj = Project.objects.get(id=text) return render(request, 'projects/single-project.html', {'obj': obj}) def createproject(request): form = ProjectForm() context = {'form': form} return render(request, 'projectform.html', context) models.py from django.db import models import uuid class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(null=True, blank=True, max_length=2000) source_link = models.CharField(null=True, blank=True, max_length=2000) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) tag = models.ManyToManyField('Tag', blank=True) total_vote = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return self.title class Review(models.Model): VOTE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.value class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name forms.py from django.forms import ModelForm … -
GiltLab CI/CD Django tests failing
I want to run some tests on Gitlab with CI/CD with a Django project. The tests on my local pc work fine, my job test pipeline is always failing with those tests. I get a SyntaxError. Here the script failure I get in the pipeline when the tests failed : Running with gitlab-runner 15.3.0~beta.42.gdb7789ca (db7789ca) on blue-3.shared.runners-manager.gitlab.com/default zxwgkjAP Preparing the "docker+machine" executor 00:06 Using Docker executor with image ruby:2.5 ... Pulling docker image ruby:2.5 ... Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... Preparing environment 00:01 Running on runner-zxwgkjap-project-39068925-concurrent-0 via runner-zxwgkjap-shared-1662191947-427cb239... Getting source from Git repository 00:02 $ eval "$CI_PRE_CLONE_SCRIPT" Fetching changes with git depth set to 20... Initialized empty Git repository in /builds/XXX/Deploy_django_application_to_server/.git/ Created fresh repository. Checking out 51c8456f as master... Skipping Git submodules setup Executing "step_script" stage of the job script 00:01 Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... $ echo "Running unit tests..." Running unit tests... $ python manage.py test app_users.tests.CustomUserTests File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax Cleaning up project directory and file based variables 00:00 ERROR: Job failed: exit code 1 *the script of my .gitlab-ci.yml is : stages: # List of stages for jobs, and … -
How to integrate scikit-ExSTraCS with my Django application
I'd like to use https://github.com/UrbsLab/scikit-ExSTraCS's features in my application, but I've discovered that it lacks REST interfaces. This is okay because I can easily create Django REST APIs for scikit-ExSTraCS' classes, but I'm hoping someone here has some experience with this or knows of a package that already handles it. -
Enviroments variables and migrations not working in django
I have following problem. I, starting app with structure like this: In env_vasr.sh I want to keep all the credentials etc. I source this file and variables are in env. However, when I run django-admin migrate, I get the following problem: Can anyone tell me what is the problem please. ├── eMenue │ ├── eMenue │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-310.pyc │ │ │ └── settings.cpython-310.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── eMenueApp │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ └── manage.py ├── env_vars.sh ├── global_settings.json ├── requirements.txt This the output from the django-admin migrate command: With hardcoded values it worked fine. However, I created ne project after to add env variables from file. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/michal/devel/eMenue/venv/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/base.py", line 415, in … -
saving value in session but not able to retreive in future api calls
I am not much ware about how django sessions works and how does it communicate with frontend technologies like vue.js I have a project setup in django from backend and vue.js for frontend request.session['session_user_id'] = serializer.entity.owner.id using this code I am saving the user_id in session and trying to retrieve the this session user_id in future API calls but I am getting None request.session['session_user_id'] giving None Can anyone help me or explain in doing this in a correct way or finding a better approach ? -
Django keeps logging me out from dev server when changing my codebase
In my Django app I have a lot of if request.user.is_authenticated logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again. Is there any way to stay logged in when in Debug = True (or other) mode? # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "False") == "True" # Add s.th. here to keep me logged in? -
django-taggit similar_objects(): how to specify a model in the queryset
I use django-taggit on my site across several applications. The package uses a generic foreign key (by default), which allows it to work with many models, which is very convenient when working with tags and displaying different objects filtered by certain tags. But this default behaviour doesn't satisfy me when I try to find similar objects for example: # news/views.py class NewsDetailView(TagMixin, FormMixin, DetailView): model = News ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) related_items = self.object.tags.similar_objects()[:4] context['related_items'] = related_items return context In this case, I want to select similar news, but instead I get similar objects of all types, including articles or shop goods. Please tell me how can I specify my model in this command: related_items = self.object.tags.similar_objects()[:4] I want it to be News only. -
How to display an image from an external API as part of a response in Django
I have an external API that returns images and it requires a private key in order to access it. The content type it returns is 'image/jpeg'. I am creating an API with the Django Rest Framework that uses this API. I also have a model with some basic char entries, and I want to return both those model entries as well as the image in a response, with the goal of making AJAX calls to it in JS and displaying both the data and the image in HTML. I'm not exactly sure if I need to use Django forms? or if I can just make a call to the API in a plain js file hosted in my project? the latter would be ideal if I am able to send the image as part of the response... but ofcourse I don't want to expose the API key, which is part of the URL I am making a request to to get the image. I just want to essentially download the image and send it as a response. This is the current code I have been testing out: @api_view(['GET']) def random_image(request): response = requests.get('api url with secret key') if request.method == … -
Django migration error when using queryset in a Modelform
I use a queryset in a modelform instance to populate choices. However, when I now want to run the initial project db migration it returns django.db.utils.ProgrammingError: relation "core_category" does not exist LINE 1: ..._category"."name", "core_category"."fa_icon" FROM "core_cate... I tried to use a try - except block to work-around this but it didn't change the situation. So how to overcome this? As of course the categories table will be empty when migrating initially. class PollerForm(ModelForm): """ A form to create new Pollers """ # Get categories as choices, use try except # for initial migrations if no categories are available yet try: CHOICES = Category.objects.all() except (OperationalError, ProgrammingError) as e: CHOICES = [] # User instance will be passed in the view class Meta: model = Poller exclude = ('created_by',) category = forms.Select(choices=CHOICES) -
Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found
When I am using the get_url function in the SubCategroy model it gives an error like this. NoReverseMatch at /products/category/fiction/ Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\^category/\(\?P(?P<category_slug>[-a-zA-Z0-9_]+)\[\-\\W\]\+\)/\(\?P(?P<sub_category_slug>[-a-zA-Z0-9_]+)\[\-\\w\]\+\)/\$\Z'] there are no errors when I am not using {{sub_category.get_url }} in my HTML. but I want to use the URLs of each sub-category in the HTML. what did I do wrong? the way I used sub-categories maybe not be a good idea. if there are any good suggestions please add to your answer. also, I want to use language as also another categorizing criterion. is there a better or alternate way to implement this? My html {% if category_links %} {% for category in category_links %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="" data-bs-toggle="dropdown">{{ category.category_name }}</a> <ul class="dropdown-menu list-unstyled category-list "> {% if sub_category_links %} {% for sub_category in sub_category_links %} {% if sub_category.category_id == category.pk %} <li><a class="dropdown-item" href="{{ sub_category.get_url }}"> {{ sub_category.subcategory_name }} </a></li> {% endif %} {% endfor %} {% endif %} <li><a class="dropdown-item" href="{{ category.get_url }}"> View All </a></li> </ul> </li> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.products, name="products"), path('category/<slug:category_slug>/', views.products, name='products-by-category'), path('category/<slug:category_slug>/<slug:sub_category_slug>/', views.products, name='products-by-sub-category'), path('language/<slug:language_slug>/', views.products_by_language, … -
Django form success messages on an HTML page with multiple forms
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted. How can I tie the success message to the submitted form on my HTML page? forms.py from dataclasses import field, fields from logging import PlaceHolder from socket import fromshare from django import forms from .models import ServiceRequest, Contact, Newsletter class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','phone','message'] class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ['name','email'] views.py from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render from django.views.generic import TemplateView from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm from django.http import HttpResponseRedirect from django.contrib import messages from django.urls import reverse def Contact(request): contact_form = ContactForm(request.POST or None) newsletter_form = NewsletterForm(request.POST or None) if request.method == 'POST' and contact_form.is_valid(): contact_form.save() messages.success(request, "Thanks for contacting us!") return HttpResponseRedirect(request.path_info) elif request.method == 'POST' and newsletter_form.is_valid(): newsletter_form.save() messages.success(request, "Thanks for joining our newsletter!") return HttpResponseRedirect(request.path_info) context = { "contact_form":contact_form, "newsletter_form":newsletter_form, } return render(request, "main/contact.html", context) contact.html {% extends "blog/base.html" %} … -
Django allauth Microsoft SSO
I'm having trouble configuring my SSO options for my Django project that I'm working on. I'm hoping to make it so that only those users in my organization are able to sign into the application but I keep getting the following error: AADSTS50194: Application 'Azure: Application (client) ID'(DjangoAppSSO) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant. I have gone in and populated the admin console with my Client ID being the same as above from the Azure account. I also created a Client Secret with my Value and Secret ID and put those in the admin console as well. I populated the Value as the "Key" in admin and Secret ID as the "Secret Key". All the required imports are done for settings.py and I believe the issue is in what I am giving the SOCIALACCOUNT_PROVIDERS possibly. settings.py: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'APP': { 'tenant': 'organization', 'client_id': 'Azure: Application (client) ID', } } } Just for clarification sake, anywhere it says "Azure: Application (client) ID" is the actual value from there, I just don't want … -
I can't open my dashboard page in login Buttton? Why?
enter image description here I can't open my dashboard page in login button, I don't understand where is my fault. Please someone help me -
Why do we use underscore "_" in this python function using django?
_, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) So here is a function that returns a list of names. I am trying to understand how this function works but I don't understand what that underscore at the beginning is doing there. Thank you! -
Django signals weak=False
If I use Debug=false, the django signals stop working and I have to use week=false. I can't figure out why the default is week=true. I just figured out that it has something to do with the garbage collector. From the fact that I use week=false, does the garbage collector not run? Will the memory fill up with garbage over time and start a memory leak? Example use: @receiver(post_save, sender=sender, weak=False) def define_status(sender, instance, created, **kwargs): ..... -
django terminate adding any input to the database from the form
In an auction web. I'm trying to terminate adding any input (bids, comments and add to watchlist) by any user to the database if the owner of the product press on 'close ' button so I tried to implement this pseudo code: in views.py function listing: t = 1 if == 1: if owner clicks on the close button: ... t = 2 if the user adds a comment: ... if the user adds a bid: ... if user clicks on add to watchlist button: ... else: return message ('Auction has ended') I have implemented this code and the listing page accepted entries and inputs after the owner of the listing clicked on the 'close' button. I also tried to change the value of t to a boolean value ( t = True, if t == True, if user clicked: return t = False) but it didn't work. so what is the problem. def entry(request, name): enter = listing.objects.get(title = name) f= bids.objects.filter(product_id = enter) x = 0 z = "" last = None ended = None like = "k" l = 0 if request.method == 'POST' and request.POST.get("bid"): biddd = int(request.POST['bid']) user = request.user if biddd > x: bids.objects.create(bid= … -
I have a problem the form works but it does not send me the emails could you help me It is my first publication,
I have a problem the form works but it does not send me the emails could you help me It is my first publication, I honestly have no idea what it could be [CODE SETTINGS] EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST_USER='xxxxx@gmail.com' EMAIL_HOST_PASSWORD='xxxxxxxxxxxxxxxxx'** [** CODE VIEWS **] from django.shortcuts import render, redirect from .forms import FormularioContacto from django.conf import settings from django.core.mail import EmailMessage # Create your views here. def contacto(request): form=FormularioContacto() if request.method == "POST": form=FormularioContacto(data=request.POST) if form.is_valid(): nombre=request.POST.get("nombre") email=request.POST.get("email") contenido=request.POST.get("contenido") email= EmailMessage(f"Alguien quiere contactarse desde la WEB,El Usuario: {nombre} con el email: {email} por el asunto: {contenido}","",["torresfdev@gmail.com"],reply_to=[email]) email.send() try: return redirect("/contacto/?Enviadoconexito") except: return redirect ("/contacto/?NO_se_pudo_enviar") return render (request,"contactoapp/contacto.html", {"form":form}) -
how to create file txt and download using html in django
i have encrypt text and i want to create file txt which contains encrypt text and can be download the file via html. the encrypt file was in the function variable, how to get the result encrypt? and i don't know how to create file txt from another variable function. please help me with it. here's my encrypt code: def encrypt(key, pt): plaintext = read_file(pt) if isinstance(plaintext, str): pt= plaintext.encode("utf-8") print(pt) if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" print(key) assert len(key) == key_bytes # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(pt) print(ciphertext) return (iv, ciphertext) #what i want to keep in new file is ciphertext and here's how i called that func: def homepage(request): form = AudioForm() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() plaintext = Audio_store.objects.all().values_list('password').last() key = Audio_store.objects.all().values_list('key').last() pt = plaintext[0] ky = key[0] print(pt) print(ky) context={'form':form, … -
Django redirect another view from another app form
contact/views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') # return redirect('success') return redirect('PostList') #another view from another app return render(request, "contact.html", {'form': form}) # def successView(request): # return HttpResponse('Success! Thank you for your message.') contact/urls.py from django.contrib import admin from django.urls import path from .views import contactView urlpatterns = [ path('contact/', contactView, name='contact'), # path('success/', successView, name='success'), ] blog/views.py from django.views import generic from .models import Post, PostImage # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books # context['image_list'] = PostImage.objects.all() # context['image_list'] = self.get_object().postimage_set.all() context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug')) return context blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] I need the following in the SIMPLEST … -
How to filter liked posts by User? (Django)
I'm trying to list all posts that are liked by userself. This is what i'm trying to code (likeapp/models.py) class LikeRecord(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='like_record') article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='like_record') class Meta: unique_together = ('user', 'article') (likeapp/views.py) @transaction.atomic def db_transaction(user, article): article.like += 1 article.save() # like_count = LikeRecord.objects.filter(article=article).count() if LikeRecord.objects.filter(user=user, article=article).exists(): raise ValidationError('Like already exists') else: LikeRecord(user=user, article=article).save() @method_decorator(login_required, 'get') class LikeArticleView(RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('articleapp:detail', kwargs={'pk': kwargs['pk']}) def get(self, *args, **kwargs): user = self.request.user article = get_object_or_404(Article, pk=kwargs['pk']) try: db_transaction(user, article) messages.add_message(self.request, messages.SUCCESS, '좋아요가 반영되었습니다') except ValidationError: messages.add_message(self.request, messages.ERROR, '좋아요는 한번만 가능합니다.') return HttpResponseRedirect(reverse('articleapp:detail', kwargs={'pk': kwargs['pk']})) return super(LikeArticleView, self).get(self.request, *args, **kwargs) (articleapp/models.py) class Article(models.Model): writer = models.ForeignKey(User, on_delete = models.SET_NULL, related_name = 'article', null = True) project = models.ForeignKey(Project, on_delete = models.SET_NULL, related_name = 'article', null = True) title = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to='article/', null=False) content = models.TextField(null=True) price = models.IntegerField(default=0) amount = models.CharField(max_length=200, null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) (articleapp/views.py) class ArticleLikeListView(ListView): model = Article context_object_name = 'article_like_list' template_name = 'articleapp/likelist.html' def get_queryset(self): user = self.request.user queryset = LikeRecord.objects.filter() return queryset I'm trying to use filter() function to distinct liked posts by userself. How can I fix this code? Thank You! -
Get informations for each x seconds
I would like to know if there is a way to check every x seconds a value in a database table in django, and if it is the desired value, the user is redirected to another page. what i tried: I tried to use a form and it posts every 3 seconds and as soon as it makes the post it would check the table (model), but the page doesn't even load, because of sleep (it's worth mentioning that I tried SetTimeout and SetInterval) def wait(request, slug): form = MatchForm() if request.method == 'POST': roomName = Match.objects.get(roomname = slug) if (int(roomName.num_players) > 1): return redirect(f'../play/{slug}') return render (request, 'chess/waiting_room.html', {'slug':slug, 'form':form}) waiting_room.html - javascript function sleep(milliseconds) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); } subm_form() function subm_form(){ var form = $("#form") form.submit(); sleep(3000) subm_form() }; -
Use django formset for only a few specific fields
I am relatively new to django (about 3 months using it) and ran into the following problem at work. I have a model with several fields, and they asked me that of those fields, 4 specifically should be able to dynamically add another register, that is, if i register something in one of those fields, there should be the option to do it again indefinitely. I understand that this can be achieved using formset but all the examples I find are using all the fields of the model and not just a few. Any ideas on what I can do? this is the model class Mercancia(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE id = models.AutoField(primary_key=True) factura = models.ForeignKey("Factura", on_delete=models.CASCADE) desc_mercancia = models.CharField(max_length=256, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'La descripción de la mercancia no acepta caracteres especiales.')]) comercio = models.ForeignKey("ClaveComercio", on_delete=models.CASCADE) tipo_moneda = models.ForeignKey("Moneda", on_delete=models.CASCADE) cantidad_comerc = models.DecimalField(max_digits=30, decimal_places=0) valor_unitario = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total_dolares = models.DecimalField(max_digits=20, decimal_places=4, validators=[MinValueValidator(0)]) marca = models.CharField(blank = True, max_length=35, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) modelo = models.CharField(blank = True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) submodelo = models.CharField(blank=True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El submodelo solo permite valores alfanuméricos.')]) numero_serie = models.CharField(blank = True, max_length=25, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', …