Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'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 … -
django 'dict' object has no attribute 'job_id'
I've got this code: def create_full_data_spb(contains_name: str, language="cs", system=False) -> tuple: full_data = [] labels = [] data_pass = [] data_fail = [] data_skip = [] data_duration = [] data_estimated_duration = [] if not system: queryset = BuildRunMultiJob.objects.select_related("job_id") \ .filter(job_id__full_display_name__contains=contains_name) \ .filter(language=language) \ .values('job_id', 'job_id__pass_count', 'job_id__fail_count', 'job_id__skip_count') \ .order_by('-job_id__timestamp')[:10] for i in queryset: labels.append(str(i.job_id)) data_pass.append(i.pass_count) data_fail.append(i.fail_count) data_skip.append(i.skip_count) # stop using mili mili = int(i.estimated_duration) temp = datetime.datetime.fromtimestamp(mili / 1000).strftime('%H:%M:%S') data_estimated_duration.append(temp) mili = int(i.duration) temp = datetime.datetime.fromtimestamp(mili / 1000).strftime('%H:%M:%S') data_duration.append(temp) full_data.append([i.job_id, i.pass_count, i.skip_count, i.fail_count, temp]) return labels, data_pass, data_fail, data_skip, data_duration, data_estimated_duration, full_data Even though value() is defined, I get the error 'dict' object has no attribute 'job_id' I guess the error will also be for pass_count, skip_count and fail_count What am I supposed to do here? -
How to get linkedin access token with django python?
I am working on an django (python) application that needs that access token from Linkedin API. I tried the following library social-auth-app-django but it didn't help me because I do not need only to sign in, I want to store that access token in the below database to use the token in the future features of the app and I am not sure how to print it or get it from social-auth-app-django. ---------------------------------------- id | username | password | LinkedinToken ---------------------------------------- -
Application Error on Heroku (Django Web-App)
I am trying to deploy my Django web-app on Heroku. Build succeeds but still I get an Application Error. Below are my app's logs. Logs: 2022-03-04T12:47:48.701018+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-03-04T12:47:48.701018+00:00 app[web.1]: ModuleNotFoundError: No module named 'SASTRAScrapper' 2022-03-04T12:47:48.701025+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-03-04T12:47:48.745701+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2022-03-04T12:47:48.841738+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [INFO] Shutting down: Master 2022-03-04T12:47:48.841740+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-03-04T12:47:49.032701+00:00 heroku[web.1]: Process exited with status 3 2022-03-04T12:47:49.097253+00:00 heroku[web.1]: State changed from up to crashed 2022-03-04T12:48:02.499473+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=f5454869-83fe-41bc-a081-a0b11b419ad1 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:48:03.140143+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com request_id=8e31ba10-6112-41f6-b8f8-6c58e86acb4a fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:00.300756+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=e0c472d9-2ce4-4c99-9048-87e95a834255 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:00.916514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com request_id=f4a4d43f-aa19-4784-9602-f897e2a71238 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:04.938317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=8e3167e6-c97e-42e7-8fe0-1e2a5136acc4 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:05.403850+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com … -
How to get rid of the first comma in Python
tags = ProductInStore.objects.get(id=product_in_store_id).product.tags.values_list('name', flat=True) converted_list = list(tags) tags_string = '' for tags in converted_list: tags_string += ',' + tags return tags_string The output is ,tag1,tag2,tag3,tag4,tag5 but i'd like to get rid of the first comma. Do you have any idea how to do it? -
Multiple many-to-many relations through the same model in Django problem
i have a problem i don't know how to make multiple many-to-many relations through the same model. This is my DB relations : Db architecture and this is my code, i want to know if what I did is right or not ? class Projects(models.Model): Project_name = models.CharField(max_length=50) Poject_key = models.CharField(max_length=50) CITools = models.ForeignKey(CITools,null=True,on_delete=models.CASCADE) UsersO = models.ManyToManyField(User,through='OwnerShips') # for user Ownerships UserF = models.ManyToManyField(User,through='Favorites') # for user Favorites This is my OwnerSHips class : class OwnerShips(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) project = models.ForeignKey(Projects,on_delete=models.CASCADE) And this is my Favorites Class: class Favorites(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) project = models.ForeignKey(Projects,on_delete=models.CASCADE) -
how to solve No 'Access-Control-Allow-Origin' while creating new endpoints with terraform cloudfront and django
I have created an application using django react, terrafor, aws cloudfront and nginx all my endpoints that i have been working on for weeks work well. Now i have tried to add new endpoints when i try to make a request from the front end, i get the following errors: Access to XMLHttpRequest at 'https: //api.foo.com/new-url-enpoints/' from origin 'https: //www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. main.a1abe898.chunk.js:1 Page error: Error: Network Error at e.exports (1.v3s1s213.chunk.js:1:21345) at XMLHttpRequest.p.onerror (1.v3s1s213.chunk.js:1:63362) 1.v3s1s213.chunk.js:1 POST https: //api.foo.com/new-url-enpoints/ net::ERR_FAILED 500 S3 bucket resource "aws_s3_bucket" "my_bucket" { bucket = "some-bucket" ... cors_rule { allowed_headers = [ "Accept", "Accept-Encoding", "Authorization", "Content-Type", "Dnt", "Origin", "User-Agent", "X-Csrftoken", "X-Requested-With", ] allowed_methods = ["PUT", "POST", "GET", "DELETE", "HEAD"] allowed_origins = ["https: //www.foo.com"] # i have created the space to be able to post this question on stackoverflow expose_headers = ["Etag"] max_age_seconds = 3000 } FRONTEND locals { s3_origin_id = "www.foo.com" } resource "aws_cloudfront_distribution" "front_end_cloudfront" { origin { domain_name = aws_s3_bucket.my_bucket.bucket_regional_domain_name origin_id = local.s3_origin_id s3_origin_config { origin_access_identity = "${aws_cloudfront_origin_access_identity.s3_oai.cloudfront_access_identity_path}" } } enabled = true is_ipv6_enabled = true default_root_object = "index.html" aliases = ["www.foo.com"] custom_error_response { error_caching_min_ttl = 500 error_code = 403 response_code = 403 … -
CSS doesnt link to HTML in django
I am watching beginner course on django . So basically i am running server from cmd and when i want to change anything on css file it doesnt change live . STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) my html : {% load static %} <link type = "text/css" href="{% static 'style.css' %}" rel="stylesheet"> <h1>Hi welcome to my page </h1>