Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to cache QuerySet in Django
I am starting with my web application in Django. I tried to do some optimilization and loaak at queries and loading time. I did some refactor with select_related or prefetch_related, but I get stacked. I have some structured ratings according to object which is assigned to. I need on every level in structure (Employee, Team, Company..) do some calculations with ratings data. I have created class method in every model and filtered relevant ratings according to object which it belongs to. def get_ratings(self): employee_projects = EmployeeManagement.objects.filter(employee=self) feedbacks = Feedback.objects.filter(rate_for__in=employee_projects) ratings = Rating.objects.filter(feedback__in=feedbacks) return ratings I use data from this method in many place as input for calculations as property in model. But problem is that every time I call this method, query is created into DB. I think I would need some kind of cache, but when I tried to decorate as property, exception was thrown : 'QuerySet' object is not callable. Next issue I have is connected with number of instances of same object. Every instance has unique values and place in structure and returned ratings is different, but is not posible with large amount of instances doing query for each of that. So when I have 10 instances … -
Django Issue on Docker
I am running the Django rest framework and it is running fine but > when It goes to docker then I see this issue. Is anyone knows how to resolve the issue? I am searching on the internet but did not find any solution, anyone who encounters the same issue? Attaching to jdx_web_1 web_1 | Watching for file changes with StatReloader web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception web_1 | raise _exception[1] web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute web_1 | autoreload.check_errors(django.setup)() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate web_1 | app_config.import_models() web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models web_1 | self.models_module = import_module(models_module_name) web_1 | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module web_1 | … -
Ucenik matching query does not exist
I have a problem in views.py: def profil(request, pk): context = { 'profesor': Profesor.objects.get(id=pk), 'ucenik': Ucenik.objects.get(id=pk), } return render(request, 'profil.html', context) when i go to page i got this error: Ucenik matching query does not exist. my url.py: path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('profil/<str:pk>/', views.profil, name='profil'), if i delete: 'ucenik': Ucenik.objects.get(id=pk) then work, but on my profil.html page i need to display details Prfesor model and Ucenik model, i need both of them in def profil -
hey can anyone help me with this i am new to django,how can i get the user details using the token authentication when the message is created
Authenticate the user using token authentication. (NOT JWT Token) There's a quota of 10 messages per hour per user. After a successful message creation, return the message object (JSON) in the response. Example: { "id": 102, "message": "Lorem ipsum", "created_at": "created time in UTC", "updated_at": "last updated time in UTC", "created_by": { "id": 3, "username": "testuser", "email": "test@mail.com", ... } } In case of any error, return the error message. -
Need help saving a base64 image to django image field
i am working on a django project which returns a base64 encoded image and i want to save the image to the django image field.however i am missing something and would appreciate any help. Here is the model: class Catalogue(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True) description = models.CharField(max_length=255, blank=True) image_link = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True, null=True, default=None) def save(self, *args, **kwargs): self.name = self.products.name self.description = self.products.description super(Catalogue, self).save(*args, **kwargs) def __str__(self): return str(self.products) in views.py which i am getting the image from an api cat_name = [] for e in Catalogue.objects.all(): cat_name.append(e.name) print(cat_name) for prod_id in cat_name: print(prod_id) image_url = f"API URL HERE" b64 = requests.get(image_url, headers=headers).json() b64_img_code = b64['data'] Catalogue.image = base64_to_image(b64_img_code) Catalogue.save() messages.success(request, "Product Added") return redirect('home') This is the utils file that am decoding the passed base64 string: def base64_to_image(base64_string): return ContentFile(base64.b64decode(base64_string), name=uuid4().hex + ".png") Thanks again in advance -
Django Celery Periodic task is not running on mentioned crontab
I am using the below packages. celery==5.1.2 Django==3.1 I have 2 periodic celery tasks, in which I want the first task to run every 15 mins and the second to run every 20 mins. But the problem is that the first task is running on time, while the second is not running. Although I'm getting a message on console: Scheduler: Sending due task <task_name> (<task_name>) But the logs inside that function are not coming on the console. Please find the following files, celery.py from celery import Celery, Task app = Celery('settings') ... class PeriodicTask(Task): @classmethod def on_bound(cls, app): app.conf.beat_schedule[cls.name] = { "schedule": cls.run_every, "task": cls.name, "args": cls.args if hasattr(cls, "args") else (), "kwargs": cls.kwargs if hasattr(cls, "kwargs") else {}, "options": cls.options if hasattr(cls, "options") else {} } tasks.py from celery.schedules import crontab from settings.celery import app, PeriodicTask ... @app.task( base=PeriodicTask, run_every=crontab(minute='*/15'), name='task1', options={'queue': 'queue_name'} ) def task1(): logger.info("task1 called") @app.task( base=PeriodicTask, run_every=crontab(minute='*/20'), name='task2' ) def task2(): logger.info("task2 called") Please help me to find the bug here. Thanks! -
python.exe: No module named django-admin Vscode Error
(venv) PS D:\Project> python -m django-admin startproject home . D:\Project\venv\Scripts\python.exe: No module named django-admin I have no clue what I am doing wrong. I am pretty new to this. Vscode doesn't show python in the status bar. I have already set the interpreter. Every video on Youtube shows how to create the project directly. Google gave me no results on this question. -
Django local variable 'cart' referenced before assignment
i am trying to add a product to the cart and then redirect to the 'cart' page/url but when i select the button to add to cart, i get this error UnboundLocalError at /cart/add_cart/3/ local variable 'cart' referenced before assignment this is the function to get cart id : def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart this is the function to add a product to cart and redirect to the cart page: def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #use cart_idin session to get cart except Cart.DoesNotExist: cart = cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') -
How to upload file to Django rest framework API using Axios and react hook form?
I have created an API using Django Rest Framework. It has an image uploading option. But I can not upload the file. I am using Axios for API calls and react hook form for form handling. I am posting the code below for better understanding. Django: Model: class BlogModel(models.Model): user = models.ForeignKey(user_model.User, on_delete=models.CASCADE, related_name="user_blog") blogtitle = models.CharField(max_length=250) blogcontent = models.TextField() blogimg = models.ImageField(upload_to="blog_image", blank=True) slug = models.SlugField(max_length=250, unique=True) tags = models.ManyToManyField(BlogTagsModel, related_name='blog_tags', blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) edit_date = models.DateTimeField(auto_now=True) Serializer class BlogSerializer(serializers.ModelSerializer): class Meta: model = blog_model.BlogModel fields = '__all__' extra_kwargs = { 'user': {'read_only': True}, 'slug': {'read_only': True}, } View class BlogPostView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = blog_ser.BlogSerializer queryset = blog_model.BlogModel.objects.all() def perform_create(self, serializer): rand_num = random.randint(99, 222) blog_slug_str = f"{serializer.validated_data.get('blogtitle')}{rand_num}" sample_string_bytes = blog_slug_str.encode("ascii") base64_bytes = base64.b64encode(sample_string_bytes) slug = base64_bytes.decode("ascii") serializer.save(user=self.request.user, slug=slug) React: Form JSX <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit(onSubmit)}> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="title" > Title </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="title" type="text" {...register('title', { required: true })} /> {errors.title && <p className="text-red-500 text-xs italic">Title is required</p>} </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="image" > Image </label> <input … -
Django html display from model
I need on my html page to display data from Profesor and Ucenik model: ime, prezime, jmbg. {{profesor.ime}} {{profesor.prezime}} {{ucenik.ime}} {{ucenik.prezime}} {{ucenik.jmbg}} my profile page id dynamic, need to display profesor data or if ucenik to display ucenik data what i need to add on my views.py models.py class Profesor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) class Ucenik(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) jmbg = models.IntegerField(null=True) urls.py path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('posetioc/', views.posetioc, name='posetioc'), path('profil/<str:pk>/', views.profil, name='profil'), ] views.py def profesor(request): return render(request, 'pocetna_profesor.html') def ucenik(request): return render(request, 'pocetna_ucenik.html') def profil(request, pk): return render(request, 'profil.html') HTML: {% extends 'base.html' %} <title>profesor</title> {% block content %} <body> {% include 'navbar.html' %} <h1>Ime:</h1> {{profesor.ime}} </body> {% endblock %} -
django appending form inside form with javascript called submit button
i have multiple form inside my template and i want to appending form div with add button like this <div id="Partform" class="card-body"> <div id="netformdiv" class="netformdiv"> <div style="display: flex;flex-direction: row" id="netwindow"> {{ formnetpriod.activity|as_crispy_field }} {{ formnetpriod.material|as_crispy_field }} {{ formnetpriod.days|as_crispy_field }} </div> </div> <div id="btnnetwindow"> <button style="width: 50px;height: 50px" onclick="addnetwindow()" class="btn btn-success">+</button> <button style="width: 50px;height: 50px" onclick="removenetwindow()" class="btn btn-danger">-</button> </div> </div> the javascript in my template for add or minuse form field is like this: <script> function addnetwindow(){ var form = document.getElementById("netwindow") var formBody = document.getElementById("netformdiv") var formcpy = form.cloneNode(true); formBody.append(formcpy); } function removenetwindow(){ let form = document.querySelectorAll("#netwindow") form[form.length-1].remove(); } </script> and the template view like this :enter image description here if i click on add button the div copied and when click minuse button the div remove last form but my problem is when i clicked on add or minuse button the submit button called and my page refreshed lost the appended form i think this is for django form to refresh the form data but how can i fix the problem. thank you -
Page not loading even after 200 status
I'm trying to redirect to the invoice page but nothing changes except the refresh this is the url.py urlpatterns = [ path('', User_login_view, name='login'), path('home/', HomePageView.as_view(), name='home'), path("nglm/", NGLMView.as_view() , name="nglm"), """ other urls for the sidebar""" path("createinvoice/", NGLINVAPI.as_view(), name="createinvoice"), path("nglinvoice/", NGLInvoiceTV.as_view(), name="nglinvoice") ] After login I go to "nglm" page where I input the customer details and click the submit button which calls the api "createinvoice". the class is shown below class NGLINVAPI(APIView): def post(self,request): if 'nglinv' == request.POST['formtype'] : data = { 'name': request.data['cname'], 'civilid': request.data['civilid'], 'ph':request.data['ph'], 'disc':request.data['disc'], 'bookno':request.data['Bookno'], 'tga':request.data['LAmount'], } p,ccreated = update_customerdb(data=data) l = update_gldb(data=data) data['cid'] = p.id iq,i = update_inventory(data=data,gl=l) lici = update_LICI(cid=p,lid=l,data=data) ninv = update_invoice(licid=lici,lid=l,cid=p,data=data,il = iq,items = i) invid = ninv.id NGLItemModel.objects.all().delete() base_url = '/nglinvoice/' query_string = urlencode({'pk': ninv.pk}) url = '{}?{}'.format(base_url, query_string) return redirect(url) return HttpResponseRedirect('home') this should have redirected me to invoice page "nglinvoice". the view is show below class NGLInvoiceTV(TemplateView): template_name = "pages/nglinvoice.html" def get(self, request): p = request.GET['pk'] inv = get_object_or_404(InvoiceModel, pk=p) context = {} context['segment'] = 'api' context['pagename'] = 'New GL API' context['object'] = inv return render(request,self.template_name , context) I have no issues up to this point. the problem is it doesn't show the page "nglinvoice.html", it just … -
Django - getting dropdown values
currently i am new to django and working with forms in django. i didn't know how to get the values from the dropdown and print it in python terminal ? Can anyone konw, How to get the dropdown values in Django and print it ? -
IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id
I have 2 models one for Question and one for Answer when i submitted answer form its throws me an error like this: IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id but when i added blank=True and null=True i can sumitted the form but i need to go to the admin and select the qustion i want the answer to be able to appear and that is not what i want. please how can i solve this error ? my models class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return str(self.user) the views def viewQuestion(request, pk): question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) the viewQuestion template: <div class="container"> <div … -
Tips to host an online MySQL server usable with Django
I want to make a Django website, with MySQL as the database. I have two of my friends working with me in different places for the development phase. The problem is, which online resources to use for the development time for the least/free cost' ? I have been thinking to use GitHub to store the website, but can't find any good MySQL free servers online (for the development period). Can someone suggest me? -
Django form input value for current image
My html form's image part: {% for photo in date.photo_set.all %} <div class="photo-wrapper-{{ forloop.counter }}"> <input type="file" name="current-photo-{{ forloop.counter }}" value="{{ photo }} accept="image/*""> </div> {% endfor %} Okay so this is a part of my form in Django. In form I show all current photos of model. When I submit the form I want to get that current photos in self.request.POST.keys(). But their key's values are empty like so: 'current-photo-1: [''], current-photo-2: ['']. As I understand the issue is in value attribute of <input> tag in my html form. It doesn't store any object-like stuff (image). How to make it actually store current photo. Hope you got it. If any questions, don't hesitate. Thanks! Note. I am pretty sure this information is enough for you to answer this question. -
Getting user credentials by email
I'm making a small solution to restore user credentials. I decided to try to do it with my algorithm. I request the user's mail and compare it with the database of postal addresses. If the mail exists, I want to send the user his credentials (login and password). I have already done the acceptance and verification of mail, as well as configured the sending of emails to postal addresses. But how to get access to credentials with only mail and the fact that the user is not logged in, I do not understand. I know that maybe my solution based on security is not very good, but there was interest and I really want to understand how to do it. It may be possible to make a quick login and get data from there, or it can do without it? As a result, I have to send the used as a message to views.py this data. views.py def recovery(request): if request.user.is_authenticated: return redirect("/accounts/exit/") else: if request.method == 'POST': email_form = UserRecoveryForm(request.POST) if email_form.is_valid(): email = email_form.cleaned_data['email'] try: send_mail("Восстановление учетных данных.", "message", "from@gmail.com", [email], fail_silently=False) except BadHeaderError: return HttpResponse('Ошибка в теме письма.') return render(request, 'registration/recovery_done.html') else: email_form = UserRecoveryForm() return render(request, … -
Django - How do I write a queryset that's equivalent to this SQL query? - Manging duplicates with Counting and FIRST_VALUE
I have Model "A" that both relates to another model and acts as a public face to the actual data (Model "B"), users can modify the contents of A but not of B. For every B there can be many As, and they have a one to many relation. When I display this model anytime there's two or more A's related to the B I see "duplicate" records with (almost always) the same data, a bad experience. I want to return a queryset of A items that relate to the B items, and when there's more than one roll them up to the first entered item. I also want to count the related model B items and return that count to give me an indication of how much duplication is available. I wrote the following analogous SQL query which counts the related items and uses first_value to find the first A created partitioned by B. SELECT * FROM ( SELECT COUNT(*) OVER (PARTITION BY b_id) as count_related_items, FIRST_VALUE(id) OVER (PARTITION BY b_id order by created_time ASC) as first_filter, * FROM A ) AS A1 WHERE A1.first_filter = A1.id; -
Sending data to external api url django rest_framework [Errno 2] No such file or directory
#My views file class CreateImageInfo(APIView): parser_classes = [MultiPartParser, FormParser] serializer_class = PostCreateUpload def post(self, request, *args, **kwargs): headers = {'Authorization': 'Bearer ' + c} url = 'https://api.logmeal.es/v2/image/recognition/type/{model_version}' file = PostCreateUpload(data=request.FILES) if file.is_valid(): file.save() image = file.data['image'] resp = requests.post( url, files={'image': open(image, 'r')}, headers=headers) return Response(resp.data, status=status.HTTP_201_CREATED) #Serializer File class PostCreateUpload(serializers.ModelSerializer): class Meta(): model = Identified fields = ('timestamp', 'image') #My Models file- class Identified(models.Model): # name = models.CharField(max_length=30) image = models.ImageField(upload_to='media', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.timestamp ** current error coe displaying is "FileNotFoundError: [Errno 2] No such file or directory: '/images/media/art.onlin_281031686_1095087414692746_398359933098246564_n.jpg'"** -
Django: how to add slug to url tag in django?
i want to add a slug to url in using django, i have tried different slugs but there is something i am missing. <a href="{% url 'tutorials:tutorial' t.tutorial_category.slug t.tutorial_topic_category.slug t.topic.slug t.slug %}">{{t.title}}</a> this is my views.py def tutorial(request, main_category_slug, topic_category_slug, tutorial_slug): tutorial_topic_category = TutorialTopicCategory.objects.get(slug=topic_category_slug) topic = Topic.objects.filter(tutorial_topic_category=tutorial_topic_category) tutorial = Topic.objects.get(slug=tutorial_slug) context = { 'topic':topic, 'tutorial':tutorial, } return render(request, 'tutorials/tutorial.html', context) urls.py path("<slug:main_category_slug>/<slug:topic_category_slug>/<slug:tutorial_slug>", views.tutorial, name='tutorial') -
Using Regex Validators
How can I use Regex Validators in my Django project? (Current using Django 1.11) forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') To be more specific in 'full_name' , 'company' and 'note' fields I just want to allow digits and letters. In 'email' field want to allow digits , letters, "-" , "_" , "." and "@" characters. And in 'phone_number' field want to digits and "+" , "#" , "()" characters. -
Display media files with Django
I learn Django and I have a problem with display img in settings I add: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "moje_media") and in url.py I add static urlpatterns = [ //routing ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Problem is that img is uploading correctly but I have a problem with display that. For example - in my template I have img tag: <img src="{{MEDIA_URL}}{{film.plakat}}"> But it doesn't display that. I inspect img that and src contain "/media/plakaty/test.jpg". I go to Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ filmy/ login/ [name='login'] logout/ [name='logout'] ^media/(?P<path>.*)$ The current path, media/plakaty/test.jpg, matched the last one. What is wrong? -
return multiple images and their corresponding id in django
I want to send multiple images and their corresponding id from django to react.js. I tried to return dictionary of images with id as key in this format: {id1:image1, id2:image2} but i only recieved this in react.js {id1, id2} and there is no media images in recieved dictionary. How can return multiple images and thier corresponding id in django? -
how to create choices field from Enum Types Django
Enum class # waiting the customer ( not paid ) Waiting = "Waiting" # Waiting to the next ship Pending = "Pending" # on the way Shiping = "Shiping" # Done Done = "Shipped" Order Model How can I make Choices field from the Previous Class class Order(models.Model): customer = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) amount = models.PositiveIntegerField() status = models...! -
A better solution for the increasing number game?
I am remaking the question I made here based on the feedback given to me. If there is still something unclear in my question please let me know. Explanation for the game: Increasing number game where the user has to guess before the number is going to stop increasing. This is purely a random chance and is done by clicking on a button by the user. Number is calculated on the server side after each game. Number will be increasing by 0.01 starting from 1.00 until the number calculated on the server side. Solution I have come up with: Running a background process using apischeduler. Executing the number increasing function every 0.1 seconds which adds 0.01 to the current state of number and sends the state result to frontend using Django Channels. I am pulling and updating the state using database queries. When the end result (number) is reached, new number will be calculated and there will be a timer running before new game begins. That all this seems odd considering I am calling a function in the background every 0.1 seconds forever. I can not figure out how to complete the task differently though. Is there a better solution/more …