Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create tree table efficiently MPTT
I need to implement a table of different products inside a dashboard in a hierarchial structure / tree. I'd need to do that in the most efficient way, as currently the page takes for ever to load. The tree has 3-4 dimensions in total. I'm using django-mptt for creating the queries on the backend. Which template tags of django-mptt should I use and how should I combine it with HTML in order to create the rows inside the table? Example would be great. -
I created an API in DRF in which i can create coupon code in admin panel, can anyone guide me how i can redeem using script
I created an simple Django rest framework api where i create Coupon in admin panel now i want to validate/redeem that coupon using simple python script or javascript or HTML but i don't know how, Please anyone can help? Here is my models.py File : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code Here is my views.py file from django.shortcuts import render from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer Here is my serializer.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Please if possible help, Thank you. -
Graphql query error handling like mutation error
we can easily catch validation error from graphql mutations but if we need to raise some exception from query resolver what would be the standard way. for example: some_value = some_model.objects.get(id=1) if not some_value: raise ValidationError(field: "Error message") -
dj-rest-auth api endpoints urls page not found
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # drf, rest_auth, allauth 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', # apps 'board_subject_restful', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } SITE_ID = 1 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('board_subject_restful.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] When attempting to connect to rest-auth/ url, the following error occurs. api-auth/, rest-auth/registration/, all rest-auth Api endpoints urls The same error also occurred. *dj-rest-auth is the same situation enter image description here -
Django demand login in url
I have a Django page with content that changes depending on whether the user is authenticated or not (more content when the user is authenticated) Is there a way to provide an URL to this page, but login the user first if he's not logged in, and do nothing if the user is already logged in? There is the https://www.example.com/login/?next=/mypage/ syntax, but this will ask for a login even if the user is already logged in. Any way to achieve this easily? -
'at=error code=H10' WHILE DEPLOYING TO HEROKU
So i have a project that i am trying to deploy to heroku and i keep getting the above error, let me share my code and if you need any other part of the code please ask, thank you It shows an application error when i open the app through heroku first, the heroku logs --tail brings this result 2021-01-11T13:11:58.739363+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2021-01-11T13:11:58.739364+00:00 app[web.1]: mod = importlib.import_module(module) 2021-01-11T13:11:58.739364+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-01-11T13:11:58.739365+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-01-11T13:11:58.739365+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-01-11T13:11:58.739367+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2021-01-11T13:11:58.739367+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-01-11T13:11:58.739368+00:00 app[web.1]: File "/app/personalgallery/wsgi.py", line 16, in <module> 2021-01-11T13:11:58.739368+00:00 app[web.1]: application = get_wsgi_application() 2021-01-11T13:11:58.739368+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-01-11T13:11:58.739369+00:00 app[web.1]: django.setup(set_prefix=False) 2021-01-11T13:11:58.739369+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2021-01-11T13:11:58.739369+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-01-11T13:11:58.739370+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-01-11T13:11:58.739370+00:00 app[web.1]: self._setup(name) 2021-01-11T13:11:58.739374+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup 2021-01-11T13:11:58.739374+00:00 app[web.1]: self._wrapped = Settings(settings_module) … -
I want import my terminal(print) data to database in selenium project, i am using sqlite3
management/commands/pyr.py **from selenium import webdriver from django.core.management.base import BaseCommand from databackup.amazon.models import Amazon print1 = webdriver.Chrome(executable_path='/home/sr/PycharmProjects/selenium/automation/KPTGR/chromedriver')** **print1.get('https://www.google.com/') got = print1.find_element_by_id('SIvCob') print(got.text)** *#till here everything works fine in terminal as "Google offered in: हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ"* #now I am trying to send (got.text) into my database model named 'Amazon' and 'order_detail' as its textfield. **class Command(BaseCommand): help = 'Some description...' def handle(self, *args, **options): # … run selenium … Amazon.objects.create( got )** #after implementing class, this gave error as 'you must either define the environment variable DJANGO_SETTINGS_MODULE or ...'* is there any other method to access my terminal data to database or I can improve this command -
how to load javascript in django templates
i'm trying to apply my JS file to templates but it doesn't applied. i tried using <script src="{% static 'js/main.js' %}" type="text/javascrpit"></script> instead of <link rel="stylesheet" href="{% static 'js/main.js' %}"> plus stored my static files in my app folder instead of root directory HTML {% load static%} <!-- css --> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <!-- js --> <link rel="stylesheet" href="{% static 'js/main.js' %}"> JS const searchBtn = document.querySelector(".search_btn") const cancelBtn = document.querySelector(".cancel_btn") //const searchBtn = document.querySelector(".search_btn") const searchBox = document.querySelector(".searchBox") searchBtn.onclick = () =>{ searchBox.classList.add("active"); } settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'statics'), os.path.join(BASE_DIR, 'vendor'), ] and TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], ..... directory django: 3.1.5 python: 3.8.5 -
Update Query list in Django
I'm having a trouble on how can I automatically update my amount_unpaid when the time I updated my amount_paidcolumn. The result of amount_unpaid should be subtract my amount - amount_paid = amount_unpaid . The way I updated my data is using list like the code below, please check this out, Any help is much appreciated Thanks in advance. AttributeError: 'QuerySet' object has no attribute 'amount' def update_remarks(request): product_ids = request.POST.getlist('id[]') amt_paid = request.POST.get('amount_paid') for id in product_ids: unpaid_update = (Person.objects.filter(pk=id).amount - amt_paid) #Error no attribute Amount Person.objects.filter(pk=id).update(amount_paid = amt_paid) # this should update every amount_unpaid based on subtracted amount column Person.objects.filter(pk=id).update(amount_paid = amt_paid) -
django DetailView url hiding pk
//i have a detailview in Django http://www.test.nl/detail_view/1/ //is there a way to hide the /1/ in the url so users don't see that? -
Can we club multiple generic class based views in django?
I want to display a list of items and also a form to add further items at the end of the list. Hence I was thinking of creating a view as something below: I have come across a class called ListCreateAPIView but I don't want to use django rest framework. Please let me know your suggestions if and how can I club two generic class based view and how the path in urls.py would look like. Further how should we refer to the list and create form objects in 'listnadd_task.html'? <views.py> from django.views.generic import ListView, CreateView from .models import Task from .forms import CreateTask class ListAndAddView(ListView, CreateView) model = Task form_class = CreateTask context_object_name = 'listnadd_task' ... -
Django find object with 2 matching fields
I have an array of id’s: ['ypxiQsnL4Etm', 'eWGzBlgcBy5l', 'ki5H4U4unB2v'] And I have a 'Deal' object that has 2 fields with product 1 and 2. class Deal(models.Model): name = models.CharField(max_length=50, null=True) product1 = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='product1_product') product2 = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='product2_product') I want to loop through that array and see which of those arrays are in the same Deal object. If one of those id’s are in the same object, that is a match. After the match is created, delete the matched id`s from the array. I tried the following: for i in cart: try: product = Product.objects.get(product_id=i) if product.deal_type: product_id = product.product_id combi_products.append(product_id) print(combi_products) except: pass length = len(combi_products) if length > 1: for cp in combi_products: try: deal_1 = Deal.objects.get(product1__product_id=cp) if deal_1: try: print(cp) matched_through = Deal.objects.get(product1__product_id=deal_1.product1.product_id, product2__product_id=cp) print(matched_through) except: pass except: pass -
Which tech stack would someone recommend as a full stack developer? MERN or Django? or it is purposed centered choice? [closed]
Confused between these too full stack development stacks, MERN or Django, formal being JS based later being fully python based. share your reviews/ opinions.... -
i want to send terminal print data to database
enter image description here actually I'm new to Django, I have created selenium project in which It automates mobile recharge. After completion of "recharge successful" I needed to send successful receipt into my database. I used print(order_id.text) to get receipt in my terminal. now I don't know how to send that receipt to m -
Why in some case forms.hiddenInput() with initial value return None and some time the initial value?
I have 2 forms (form 1 RandomizationForm = modelForm and form 2 RallocationForm= form) with the same hidden field with initial value but they do not have the same behavior: form 1 return the initial value in self.cleaned_data['ran_log_sit'] form 2 return None in self.cleaned_data['ran_log_sit'] So I have to had clean_ran_log_sit(self) method to set initial value when self.cleaned_data['ran_log_sit'] return None I don't know why and so I am not sure with my code form 1: class RandomisationForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomisationForm, self).__init__(*args, **kwargs) ... SITE_CONCERNE = Site.options_list_site_concerne_randomization_or_reallocation(self.user,self.user_pays,self.user_site_type,self.language) if self.user_site_type == 'International': self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), required=True, widget=forms.Select, choices=SITE_CONCERNE) elif self.user_site_type == 'National': self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), widget=forms.Select, choices=SITE_CONCERNE) else: self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), widget=forms.HiddenInput(), choices=SITE_CONCERNE, initial = self.user_site, disabled=True) ... # vérification que la randomisation est possible (i.e. au moins une boite d'aspirine et une boite de placebo) def clean(self): cleaned_data = super(RandomisationForm, self).clean() # validation anti-doublon if Randomisation.objects.filter(ran_num = self.data.get('ran_num').upper()).exists(): bras = Randomisation.objects.get(ran_num = self.data.get('ran_num').upper()).ran_bra bras_libelle = OptionDeThesaurus.objects.get(the_id=10,the_opt_cod=bras).the_opt_lab_eng med = current_drug(self.data.get('ran_num').upper()) raise forms.ValidationError(str(_('This patient has already been randomized in arm '))+str(_(bras_libelle))+str(_(' - current box number '))+str(med)+str(_('. Please control patient number.'))) # vérification stock print("cleaned_data['ran_log_sit']",cleaned_data['ran_log_sit']) pays = Site.objects.get(sit_abr = cleaned_data['ran_log_sit']).reg.pay.pay_abr if patient_code_is_valid(cleaned_data['ran_num']) and … -
How do I display image in an object detail view without creating an extra ImageField?
I've it done in admin list display by simple creating a function and adding it to list_display. I want something similar in detail view. Can this be done? models.py class Log(models.Model): created = models.DateTimeField(null=True, auto_now_add=True) model = models.CharField(max_length=100) modified = models.DateTimeField(null=True, auto_now=True) req_endpoint = models.CharField(max_length=800) resp_json = models.TextField(max_length=1000) resp_img_uri = models.CharField(max_length=750) input_image = models.CharField(max_length=750) status_code = models.CharField(max_length=100) elapsed_time = models.CharField(max_length=100) score = models.CharField(max_length=100) request_domain = models.CharField(max_length=100) human_observation = models.CharField(max_length=50, choices = confusion_matrix, editable=True) def __str__(self): return self.human_observation admin.py class LogAdmin(admin.ModelAdmin): list_filter = ('model','human_observation') list_display = ['id','response_img','input_img','model','score','created','human_observation','admin_image'] ordering = ['-id'] def response_img(self, obj): return format_html('<img src="{0}" style=" object-fit: cover; width: auto;height: 60px;" />'.format(obj.resp_img_uri)) def input_img(self, obj): return format_html('<img src="{0}" style=" object-fit: cover; width: auto;height: 60px;" />'.format(obj.input_image)) -
csrf_token verification failed or aborted error with form
I'm getting CSRF verification failed. Request aborted. My index view: def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks,'form':form} return render(request, 'tasks/list.html', context) My list.html template with form: <h3>TO DO</h3> <form method="POST" action="/"> {% csrf_token %} {{ form.title }} <input type="submit" name="" value="Create Task"> </form> {% for task in tasks %} <div> <p>{{ task }}</p> </div> {% endfor %} -
Update model field after saving instance django
I have a Django model Article and after saving an instance, I want to find the five most common words (seedwords) of that article and save the article in a different model Group, based on the seedwords. The problem is that I want the Group to be dependent on the instances of Article, i.e. every time an Article is saved, I want Django to automatically check all existing groups and if there is no good fit, create a new Group. class Article(models.Model): seedword_group = models.ForeignKey("Group", null=True, blank=True) def update_seedword_group(self): objects = News.objects.all() seedword_group = *some_other_function* return seedword_group def save(self, *args, **kwargs): self.update_seedword_group() super().save(*args, **kwargs) class Group(models.Model): *some_fields* I have tried with signals but couldn't work it out and I'm starting to think I might have misunderstood something basic. So, to paraphrase: I want to save an instance of a model A Upon saving, I want to create or update an existing model B depending on A via ForeignKey Thanks in advance for any help or advice. -
How to open a picture as a pop up in the same window as the django template?
I am currently working with django and have encountered a problem whilst translating the original HTML code to fit with django template requirements. The code works just fine for the most part but the problem arises when I try to open a picture that should open as a pop-up. The picture is wrapped in the anchor tag and links to a file in a directory that contains the same picture which I then opened as a pop-up over the existing window. Django interprets the href as a URL and trees to find it in urlpatterns. If I were to add a urlpatter for the picture, or in this case each individual picture alone it would not serve the same purpose as I would have to render a new view and encounter the same problem. Is there a way to open pop-ups in django and do I need to add to the list of urlpatterns: the following are screenshots of the original HTML code and how it should look. <div class="column"> <a href="images/cases/cases1.jpg" data-lightbox="cases" data-title="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Fugiat, dolore!" > and pic1 pic2 -
Manage a class with too many instances in a table Django
I'm new in Django development and I need your help, please. I have a list of 44.000 rows of products (instances of product class).I displayed these products in a table using jquery, but it takes so much time to display them. So I would like to know if there is a way to manage a class with too many instances in a table This is my product class in models.py class Product(models.Model): STOCK_STATE = ( ("Vide", "Vide"), ("Faible", "Faible"), ("Moyen", "Moyen"), ("Satisfaisant", "Satisfaisant"), ("Plain", "Plain"), ) product_name = models.CharField( max_length=60, null=False, blank=False,) image_product = models.ImageField( upload_to=upload_location_image, null=False, blank=False) last_update = models.DateField(null=False, blank=False) price = models.FloatField(null=False, blank=False) num_art = models.IntegerField(null=False, blank=False) stock_state = models.CharField( max_length=60, null=False, choices=STOCK_STATE) #aisle = models.ManyToManyField(Aisle) product_group_code = models.IntegerField(null=False, blank=False) product_group_name = models.CharField( max_length=60, null=False, blank=False) product_subgroup_code = models.IntegerField(null=False, blank=False) product_subgroup_name = models.CharField( max_length=60, null=False, blank=False) def __str__(self): return self.product_name this is my views.py def consult_product_view(request, pk ): product= Product.objects.get(id=pk) anomalies_per_product = product.anomalie_set.all() context = { 'product': product, 'anomalies_per_product': anomalies_per_product} return render(request, 'anomalie/consult_product.html', context) and this is my table.html <script> $('#mydatatable').DataTable({ pagingType: 'full_numbers', }); </script> <div class="container mb-5 mt-3"> <table class="table table-striped table-bordered" style="width: 100%" id="mydatatable"> <thead> <tr> <th>Image produit</th> <th>Nom du produit</th> <th>Num_art</th> </tr> </thead> <tbody> … -
TypeError: object.__init__() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:50083]
I am building a chat app and I am stuck on an Error. When i runserver, it is working fine but when I refresh the browser then it is showing TypeError: object.init() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:50083] settings.py: ASGI_APPLICATION = 'brain.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I will really appreciate your Help. tHANK yOU iN aDVANCE. Best Regards -
Django: How To Remove Invalid Dates From DateField
My form allows users to input invalid dates like 31 of febuary, is there a way to exclude certain dates in a range? models: release_date = models.DateField(null=True, blank=True, default=None) froms: YEARS = [x for x in range(1900,2030)] class NewPost(forms.ModelForm): release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) -
How to extend custom error page template in Django?
I have the following layout for custom error pages: {% extends 'base.html' %} {% block title %}[TITLE]{% endblock title %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'page.css' %}"/> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="container"> <h1> [MAIN-TITLE]</h1> <h2> [SUB-TITLE]</h2> <div class="message"> [MESSAGE] </div> </div> </div> </div> </div> This means that I have the same html for each status code (400.html, 500.html and so on). I want to make error_page.html and each one of the status codes (400.html, 500.html and so on) will extend it. The only difference between the pages is the blocks I marked with []. How can I do such thing in Django? -
How to insert data in multiple tables from single html form using Django and MySQL?
I have created one HTML form for adding Class_name, Subject_name, Topics and Questions for creating Question Paper Set. All tables are interconnected to each other using Foreign Key in my Models. Now I want to insert these data into different tables named as Classes, Subjects, Topics etc from dropdown in HTML form. These are my code below: models.py class Classes(models.Model): options = (('JEE', 'JEE'),('IEEE', 'IEEE')) className = models.CharField(max_length=200, choices=options, null=True) status = models.CharField(max_length=50) class Subjects(models.Model): options = (('Physics', 'Physics'),('Chemistry', 'Chemistry'), ('Maths', 'Maths')) classes_id = models.ForeignKey(Classes, max_length=200, null=True, on_delete=models.CASCADE) subjectName = models.CharField(max_length=500, choices=options, null=True) status = models.CharField(max_length=50) class Section(models.Model): options = (('Sec1', 'Sec1'),('Sec2', 'Sec2'), ('Sec3', 'Sec3')) classes_id = models.ForeignKey(Classes, max_length=200, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subjects, max_length=200, null=True, on_delete=models.CASCADE) sectionName = models.CharField(max_length=500, choices=options, null=True) status = models.CharField(max_length=50) views.py def createQuestionPaper(request): if request.method == 'POST': Class = request.POST['Class'] Subjects = request.POST['Subjects'] Sections = request.POST['Sections'] Topics = request.POST['Topics'] createClass = Classes.objects.create(className=Class, status=1) classId = Classes.objects.latest('id') createSubjects = Subjects.objects.create(subjectName=Subjects, classes_id_id=classId, status=1) subjectId = Subjects.objects.latest('id') createSections = Section.objects.create(sectionName=Sections, classes_id_id=classId, subject_id_id=subjectId, status=1) sectionsId = Section.objects.latest('id') return redirect('/showPaper') else: return render(request, 'exams/createQuestionPaper.html') createQuestionPaper.html <form action="" name="paper" method="POST"> {% csrf_token %} <select name="Class" class="form-control"> <option selected="" name="Class">Class</option> <option value="JEE"> JEE </option> <option value="IEEE"> IEEE </option> <option value="PET"> PET </option> … -
Serve interactive 360 video on Django
I'm trying to build a website with Django where you can view different 360 videos. The videos are created with a software (3dVista) that generates a web build folder with an index.htm file and some javascript code and other media files. In order to view the web build I have to open the index.htm file. The problem is that inside the index file are referenced multiple javascript and media files like this: href="main.js?v=23182178412", so I have to substitute all the references with the Django syntax {% static 'path/to/main.js' %}. This is very tedious and sometimes it doesn't work because I cannot find all the references within all the files. \ Is there a way to avoid this in Django? Or is it better to host the web builds on another server?