Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conversion from website to mobile application
I am developing a website for a startup and plan to have a mobile app version. The technologies used to build the website are: Frontend: HTML, CSS, JavaScript Backend: Python (Django) DataBase: SQLite I would like to know if the conversion from website to mobile app maintains the same level of performance and is it advantageous? -
django Expiration object
I am using an activation system to verify the user email and now in the active_code model , I wnat only the objects that are created 120 seconds ago . Help me please! def Activation_page(request): if request.method == "POST": form = forms.Active(request.POST) if form.is_valid(): data = form.cleaned_data past_seconds = timezone.now().date() - timedelta(seconds=120) if active_code.objects.filter(email = request.session['email'] , code = data['num'] , expiration__gte=past_seconds).exists() : try: b = User.objects.get(email = request.session['email']) b.is_active = True b.save() return redirect('home:loginveiw') except: messages.error(request , 'error') else: messages.error(request , 'error_2') else: form = forms.Active() return render(request , 'home/activation.html' , {'form' : form}) -
Issues with django Group formsets
Am trying to implement a group form where a choice in a model field will determine the options in the other field. kindly checks my code below models.py class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) mobile_number = models.CharField( max_length=11) # validators should be a list type = models.CharField(choices=Main.TYPES, max_length=10) operator = models.CharField(max_length=15) circle = models.CharField(max_length=20) plan = models.DecimalField(max_digits=6, decimal_places=2) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) plan_id = models.DecimalField(max_digits=6, decimal_places=2) network_id = models.DecimalField(max_digits=6, decimal_places=2) api_development_no = models.CharField(max_length=15) class Meta: ordering = ["-timestamp"] fields.py class GroupedModelChoiceField(ModelChoiceField): def __init__(self, *args, choices_groupby, **kwargs): if isinstance(choices_groupby, str): choices_groupby = attrgetter(choices_groupby) elif not callable(choices_groupby): raise TypeError('choices_groupby must either be a str or a callable accepting a single argument') self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby) super().__init__(*args, **kwargs) forms.py class RechargeDataForm (forms.ModelForm): class Meta: model = RechargeData fields = ['mobile_number', 'type', 'operator', 'circle', 'plan'] class GroupedRechargeDataForm(forms.ModelForm): operator = GroupedModelChoiceField(queryset=operator.objects.exclude(operator=None), choices_groupby='operator') class Meta: model = RechargeData fields = ['mobile_number', 'type', 'operator', 'circle', 'plan'] This form rendering is bringing a different outcome by fetching only operator field created in model but am trying to render the rest form based on choice on operator. for example. if the User choices Mtn As operator then the cycle, the plan, the type, the network_id, the plan_id will … -
Why do I get a Key Error when raising Validation Error in a form.py file?
No idea what is going on here, but when I include this validation check function in form.py file, I get a Key Error on the field: def clean_student_loan_payment_method(self): student_loan_payment_method = self.cleaned_data['student_loan_payment_method'] student_loan_boolean = self.cleaned_data['student_loan_boolean'] if student_loan_payment_method == None: student_loan_payment_method = '' if student_loan_boolean == True and student_loan_payment_method == '': raise forms.ValidationError(_("Please choose the method by which you repay your Educational Loan.")) return student_loan_payment_method If I hash out the line called 'raise forms.Validation(...', I get no Key Error. The form submits, and all is fine. Any ideas? Specifically this is the error Request Method: POST Request URL: http://localhost:8000/app/profile/edit/employment/ Django Version: 4.0.2 Exception Type: KeyError Exception Value: 'student_loan_payment_method' Exception Location: /Users/....Website Development/Github Pages/.../forms.py, line 432, in clean_student_loan_plans Python Executable: /Users/....Website Development/Github Pages/....python3 Python Version: 3.8.9 -
How do you handle non-standard 4xx and 5xx Django Errors?
We have the 404, 500, etc. templates created for our Django app to handle the built-in HTTP Errors that Django supports. But how do you handle the non-standard 4xx and 5xx HTTP Errors? For example, when I submit a really long URL param, I see a 414 Request-URI Too Long message instead of one of our templates. How do I set up Django to error handle HTTP Error codes like: 411, 414, 505, etc? -
How to run python function from Django
I would like to run a python script (or even better a function inside the script) inside my Django app. Basically I think AJAX would be the right choice for this, since the web page should not reload when the button is clicked. Can someone help me with the structure or give me tips? What I got so far is basically my template and a reference for my button: "page.html" <form method="post"> <button type="button" type="submit" class="btn btn-primary">Resync</button> </form> How can I put this into my "views.py" and run an python script from my project folder when click on the button (basically the python script will do some database updates in the background)? -
Testing Django Wagtail - assert that a child of the given Page type with an image can be created under the parent
I've defined a custom page model (a blog post) as a child of a parent model (a blog index page) and I want to test that the child can be created under its parent. The BlogPage and BlogIndexPage models are copied from the wagtail "basic blog" example in the documentation, and works as expected. I'm trying to follow the documentation but I get the following error: AssertionError: Creating a page failed for an unknown reason Through trial and error, I know that the error is caused by including an InlinePanel that references another model (BlogPageGalleryImage). If I remove this panel from my BlogPost model definition then the test will pass. I don't understand why including the panel causes an error, or how to solve this problem. Any help is much appreciated! The problematic line: ... InlinePanel("gallery_images", label="Gallery images"), ... The models: class BlogIndexPage(Page): template = "blog.html" intro = models.TextField(blank=True) subpage_types = ["cms.BlogPage", "cms.SimpleBlogPage", "cms.BlogTagIndexPage"] def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context = super().get_context(request) blogpages = self.get_children().live().order_by("-first_published_at") context["blogpages"] = blogpages return context content_panels = Page.content_panels + [FieldPanel("intro", classname="full")] class BlogPage(Page): template = "blog-post.html" parent_page_types = ["cms.BlogIndexPage"] date = models.DateField("Post date") intro = models.CharField(max_length=250) … -
'cryptography' package is required for sha256_password or caching_sha2_password auth methods
Request Method: POST Request URL: http://192.168.0.110/admin/login/?next=/admin/ Django Version: 4.0.1 Exception Type: RuntimeError Exception Value: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods Exception Location: /home/chickoos/explab/ExpLab/venv/lib/python3.8/site-packages/pymysql/_auth.py, line 143, in sha2_rsa_encrypt Python Executable: /home/chickoos/explab/ExpLab/venv/bin/python Python Version: 3.8.10 Python Path: ['/home/chickoos/explab/ExpLab', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/chickoos/explab/ExpLab/venv/lib/python3.8/site-packages'] Server time: -
unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date
In model, I have a property accepted_at = models.DateTimeField(blank=True, null=True) When I save it from datetime import datetime Entry.objects.last().accepted_at = datetime.now() I'm trying to know if is accepted before 30 minutes from datetime import datetime if (datetime.now() - Entry.objects.last().accepted_at).total_seconds() > 1800: return True But I'm getting the following error unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date Can someone help me? -
Redirect URL does not match on azure
I am building a django app which is hosted on azure web app service. I have used azure ad for authentication and to support that I have used MSAL library of python. In localhost, I have been able to login using azure and view site data but cannot visit the site when application is deployed to azure web app. I am getting the following error. I have used HTTP://localhos:8000/auth/redirect as redirect uri and using same for app deployed to azure web app: https://.azurewebsites.net/auth/redirect but it is not working and is showing the following error above. I am using the following code provided from https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication . I do not what is the issue. Please help. -
Cant render HTML file on Django
Django 4.0.3 and Python 3.10.2 I cant render a html file on my project. What am i missing? Main parts of code below. Settings.py at INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] Settings.py at TEMPLATES: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, # 'DIRS': [r'project1\app1\templates\app1'], 'DIRS': [os.path.join(BASE_DIR, 'templates')], }, ] Project-Urls: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')), # main will be the name of your app ] App1-Urls: from django.urls import path from . import views urlpatterns = [ path('', views.simple_function, name='simple_function'), ] Views: def simple_function(request): print("Print executes correctly, but the render doesn't") return render(request, r'project1\app1\templates\app1\home.html') Html file path: app1/templates/app1/home.html Github of this project Had to post this bunch of information to clarify. -
Override delete model in django
I have question model and also have Like and Dislike model, i want that if user have already liked this question and then click like button, delete Like object and question point increase by one. example: question has 10 like --> i send like, so question has 11 like --> i also send like, so delete object and question's like quantity (10) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user")) question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question")) def save(self, *args, **kwargs): if not self.pk: self.question.point += 1 self.question.save() return super(Like, self).save(*args, **kwargs) @receiver(post_delete, sender=Like) def delete_like(sender, instance, using, **kwargs): print(instance.question.point) #point is 3 instance.question.point -= 1 print(instance.question.point) #point is 2 when i print everything is fine but when i open database, result is not same edit: def get_context_data(self, *args, **kwargs): like_exist=bool(Like.objects.filter(user=self.request.user, question=self.get_object())) dislike_exist=bool(DisLike.objects.filter(user=self.request.user, question=self.get_object())) self.object=self.get_object() context = super(QuestionDetail, self).get_context_data(**kwargs) try: question = Question.objects.get(id=self.kwargs["pk"]) context['detail'] = question context['like_ex']=like_exist context['dislike_ex']=dislike_exist except Http404: return reverse("Profile:error") if "like" or "dislike" in self.request.GET: if "like" in self.request.GET: if Like.objects.filter(user=self.request.user, question=self.get_object()): Like.objects.filter(user=self.request.user, question=self.get_object()).delete() else: Like.objects.create(user=self.request.user, question=self.get_object()) if DisLike.objects.filter(user=self.request.user, question=self.get_object()): DisLike.objects.filter(user=self.request.user, question=self.get_object()).delete() if "dislike" in self.request.GET: if DisLike.objects.filter(user=self.request.user, question=self.get_object()).exists(): DisLike.objects.filter(user=self.request.user, question=self.get_object()).delete() else: DisLike.objects.create(user=self.request.user, question=self.get_object()) if Like.objects.filter(user=self.request.user, question=self.get_object()).exists(): Like.objects.filter(user=self.request.user, question=self.get_object()).delete() return context -
How to manually instantiate a SearchFilter in Django Rest Framework?
I have the following view but the search filter is not being applied. What am I missing? class ListMyModelView(generics.ListAPIView): permission_classes = (IsAuthenticated,) authentication_classes = (SessionAuthentication,) serializer_class = MyModelSerializer pagination_class = StandardResultsSetPagination filter_backends = (filters.SearchFilter,) search_fields = ('field1', 'field2') def get_queryset(self): results = MyModel.objects.all() return results.order_by('-last_modified').distinct() def get(self, request): paginator = self.pagination_class() queryset = self.get_queryset() results_page = paginator.paginate_queryset(queryset, request) serializer = self.serializer_class(results_page, many=True) return paginator.get_paginated_response(serializer.data) -
Django: following relationships "backward" with muliple models
I have a set of models similar to this, where both Novel and Magazine have a ForeignKey to Bookshelf: class Bookshelf(models.Model): name = models.TextField() class Novel(models.Model): bookshelf = models.ForeignKey(Bookshelf) class Magazine(models.Model): bookshelf = models.ForeignKey(Bookshelf) Following relationships backward according to the docs, I know I can use two Managers: bookshelf.novel_set and bookshelf.magazine_set. But what is the best way to get a single set of Novels AND Magazines on a Bookshelf? My actual setup has a growing list of models like this, running the same operations on many "_sets" seems unpythonic and way too much boilerplate. I've looked at GenericRelation and writing a custom Manager, but neither seems to do what I need cleanly. Using Django 3.2. -
display data of form 1 on form 2 django SessionWizardView
Django SessionWizardView: User fills in form 1 and then, some of the values of the fields in form one are needed to calculate a number. This number must then be displayed on form 2. I don't know how I can grab the data of form 1 and use it to make a calculation and then display it on form 2. models.py class CapsProd(models.Model): production = models.OneToOneField(Productions, on_delete=models.CASCADE, primary_key=True) amount_of_caps = models.IntegerField() conc_per_cap = models.FloatField() conc_per_tab = models.FloatField() amount_of_weighed_tabs = models.IntegerField() mass_all_tabs = models.FloatField() required_mass_powder = models.FloatField() weighed_mass_powder = models.FloatField() caps_size = models.FloatField(choices=CHOICES,) forms.py class CapsProdForm1(forms.ModelForm): class Meta: model = CapsProd fields = [ 'production', 'amount_of_caps', 'conc_per_cap', 'conc_per_tab', ] class CapsProdForm2(forms.ModelForm): class Meta: model = CapsProd fields = [ 'amount_of_weighed_tabs', 'mass_all_tabs', 'required_mass_powder', 'weighed_mass_powder', 'caps_size', ] urls.py app_name = 'caps_prod' urlpatterns = [ path('', views.CapsProdWizardView.as_view([CapsProdForm1, CapsProdForm2]), name="add_new"), ] views.py class CapsProdWizardView(SessionWizardView): template_name = "caps_prod/prod_form.html" html {% extends "base.html" %} {% load django_bootstrap5 %} {% block body_block %} <h1> Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }} </h1> <form class="custom-form" method="post"> {% csrf_token %} <!-- {% bootstrap_form form %} --> {{ wizard.management_form }} {% if wizard.form.forms %} {{wizard.form.management_form }} {% for form in wizard.form.forms %} {% bootstrap_form form %} {% endfor %} {% … -
Trouble solving "No module named 'encodings'" issue with mod_wsgi
First of all, I realize that this is a common problem but I think the issue is a mixture of some solutions not working and myself not being an expert on web servers and being a first-time deployer of a Django project, so I probably missed something. Just a nudge in the right direction would be very helpful. The issue mainly surrounds the Apache package mod_wsgi which facilitates the hosting of the Django application in question here. System-wide installation on my Red Hat Linux Enterprise (7) leads to this error (work server to which I have sudo access). I include anonymized system and error output below. Some important notes: The Django project runs in a virtualenv on /var/www. Both Python 2.7 and Python 3.6 are running on the system. Both mod_wsgi compiled for Python 2 and the newest mod_wsgi (installed with yum; python3-mod_wsgi.x86_64; including httpd-devel required for APXS) are on the system: /usr/lib64/httpd/modules/mod_wsgi.so /usr/lib64/httpd/modules/mod_wsgi_python3.so The former was first loaded, skipping the second, so I uncommented the relevant line in /etc/httpd/conf.modules.d/10-wsgi.conf, after which the warning disappeared. In /etc/httpd/conf.modules.d/10-wsgi-python3.conf, I have: <IfModule !wsgi_module> LoadModule wsgi_module modules/mod_wsgi_python3.so </IfModule> A former iteration (demo) of the project running on Python 2 was running on the … -
I want to assign a user to my card from the User table, but its not working for me
django.db.utils.ProgrammingError: column user_awaycardholder.assigned_user_id does not exist LINE 1: ...der"."id", "user_awaycardholder"."display_id_id", "user_away... class AwayCard(models.Model): Away_id = models.UUIDField(default=uuid.uuid4, editable=True) my_admin = models.ForeignKey(User, on_delete=models.CASCADE) display_id = models.CharField(default='', max_length=30) is_assigned = models.BooleanField(default=False) def __str__(self): name = str(self.display_id) return str(name) class AwayCardHolder(models.Model): display_id = models.OneToOneField(AwayCard, on_delete=models.CASCADE) assigned_user = models.ForeignKey(User, related_name="user_awaycardholder", on_delete=models.CASCADE) def __str__(self): name = self.display_id return str(name) -
How to Add Subscribe option in a Django Website
I am trying to add a subscribe to newsletter option on a django website. When a visitor enters a valid email address it will be stored in the database. The subscription form is part of the base.html template. All other templates of the website extend this template. I wish to implement this in a DRY way. This is how I am trying to do it : forms.py : from dataclasses import fields from django import forms from . models import Subscribers, MailMessage class SubcribersForm(forms.ModelForm): class Meta: model = Subscribers fields = ['email', ] views.py : def base(request): if request.method == 'POST': form = SubcribersForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = SubcribersForm() context = {'form': form} return render(request, 'base.html', context) The template: base.html <form method = "POST" class="signup-form form-inline justify-content-center pt-3"> {% csrf_token %} <div class="form-group"> <label class="sr-only" for="semail">{{context}}</label> <input type="email" id="semail" name="semail1" class="form-control mr-md-1 semail" placeholder="Enter email"> </div> <button type="submit" class="btn btn-primary">Subscribe</button> </form> models.py : class Subscribers(models.Model): email = models.EmailField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__self(self): return self.email In the backend, I can see that the Subscribers table has been created. However, when I enter any email address from the home page and click subscribe button it does not … -
Is there a way to get Django to report tests with compiling errors?
From what I can tell, tests that don't compile properly are not included in Django test results. Is there a way to get Django to report the tests or test files that did not compile properly so I'm not left thinking everything in the test suite passed, but in actuality one of the test files did not compile properly and was not included in the test results? -
How to export function via django export-import?
how to export function from model into the excel using django export-import? One of my field is an instance of the another model, so I want to create some functions to execute values from the instance of another model. -
Detect timezone in django admin
I'm working in a project with a Django backend (only backend and a default admin portal, no site) where the admin portal is used by people both in Europe and US. Because of this, it's important that the datetimes in the admin portal are displayed in the local timezone of whomever is using it. I've searched for solutions to achieve this (such as suggested in the docs, but also this package) but all the solutions I've found seem to be made for detecting the timezone of end-users accessing a custom website, not the default admin portal. I'm using Django 2.2 and Python 3.8. -
Optimizing unique_together in Django Models
I have a model containing an FK and a CharField, and this pair should be unique: class Map(models.Model): uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True) user = models.ForeignKey(User, related_name="uploaded_map", on_delete=models.CASCADE) workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE) c_layer = models.CharField(max_length=40, blank=False) class Meta: unique_together = ["workspace", "c_layer"] The project uses PostgreSQL, and I am a bit worried that this constraint will create heavy indexes because of the 40 chars limit for c_layer, but I'm not sure this is really something that will impact performance. Would index a sha1 hash version of this field be less heavy for the DB? -
Is it Models or the Database?
I'm getting these issues but not sure why I changed the models from in the master branch to as in Project Branch. This is my DB These are my tables My project URL: https://github.com/Bilal815/LWD/tree/Project Now, what should I do to get going? I have very little time left!!! Appreciate any help! -
Django - Form Validation Error not showing on Boolean Field
Not sure why, but no form validation error is showing on the below code. The form (when the condition of the error is met) doesn't save (which is fine), but there is not validation message on the form? FORM def clean_p45_boolean(self): p45_boolean = self.cleaned_data['p45_boolean'] if p45_boolean == False: raise forms.ValidationError(_("Please attach your latest P45.")) return p45_boolean TEMPLATE I've included both errors and nonfield errors <!-- Error --> <div class="field"> {% for error in employment_employee_form.p45_boolean.errors %} <p class="help is-danger"> {{error}} </p> {% endfor %} </div> <!-- Non Field Errors --> <div class="field"> {% if employment_employee_form.non_field_errors %} <p class="help is-danger"> {{employment_employee_form.non_field_errors}} </p> {% endif %} </div> MODEL # U.K. EMPLOYEE PAYE MODEL class UK_Employee_PAYE(models.Model): p45_boolean = models.BooleanField(verbose_name='Do not have a P45?', blank=False, default=False) -
With JS fetch-PUT i update my db (and it does indeed) but with fetch-GET it displays the data just before the update
Im working on a Django project kind of network. I have a JS code in which with a fetch-PUT i update my db and i can check from the file that it is updated. function update_like(identity) { fetch('/like',{ method: 'PUT', body: JSON.stringify({ id: identity, }) }, show(identity) ) }; And then with a fetch-GET i try to retrieve the data function show(identity) { fetch('/like', { headers: { 'Cache-Control': 'no-cache' } }) .then(response => response.json()) .then(likedic => { console.log(likedic); if (likedic[identity]){ document.getElementById(`arithmos${identity}`).innerHTML = ` ${likedic[identity].length}`; } else { document.getElementById(`arithmos${identity}`).innerHTML =' 0'; } }); } the thing is, that every time, it displays the data from the just previous updated db. I mean first time i run update_like function, the show function diplays the db as it was before update_like function runs. But i can see from the file that db is updated. Second time i run update_like function the show function diplays the db as it should be the first time, even if i can see again from the file that db is updated etc. I suppose that it doesn't have enough time to read the update db. I have tryied so many things but i cant make it work. Underneath …