Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not Found: /style.css/ , django
I'm trying to create my own website on Django, but some problems stop me and I can't solve them myself. I want to create a sidebar. I found a website with css and HTML code for it. style.css: @import url('https://fonts.googleapis.com/css?family=Montserrat:600|Open+Sans:600&display=swap'); *{ margin: 0; padding: 0; text-decoration: none; } .sidebar{ position: fixed; width: 240px; left: -240px; height: 100%; background: #1e1e1e; transition: all .5s ease; } .sidebar header{ font-size: 28px; color: white; line-height: 70px; text-align: center; background: #1b1b1b; user-select: none; font-family: 'Montserrat', sans-serif; } .sidebar a{ display: block; height: 65px; width: 100%; color: white; line-height: 65px; padding-left: 30px; box-sizing: border-box; border-bottom: 1px solid black; border-top: 1px solid rgba(255,255,255,.1); border-left: 5px solid transparent; font-family: 'Open Sans', sans-serif; transition: all .5s ease; } a.active,a:hover{ border-left: 5px solid #b93632; color: #b93632; } .sidebar a i{ font-size: 23px; margin-right: 16px; } .sidebar a span{ letter-spacing: 1px; text-transform: uppercase; } #check{ display: none; } label #btn,label #cancel{ position: absolute; cursor: pointer; color: white; border-radius: 5px; border: 1px solid #262626; margin: 15px 30px; font-size: 29px; background: #262626; height: 45px; width: 45px; text-align: center; line-height: 45px; transition: all .5s ease; } label #cancel{ opacity: 0; visibility: hidden; } #check:checked ~ .sidebar{ left: 0; } #check:checked ~ label #btn{ margin-left: … -
Why boto3 dose not recognize my AWS_ACCESS_KEY_ID in Django on EC2?
I was connecting the S3 to Django on EC2. I confirmed that it works on the my computer (window), but when I uploaded it to AWS EC2 Ubuntu and ran it, I saw the following message. when i ran python manage.py commands File "/home/ubuntu/django/e/lib/python3.6/site-packages/botocore/session.py", line 821, in create_client aws_secret_access_key)) **botocore.exceptions.PartialCredentialsError: Partial credentials found in explicit, missing: aws_secret_access_key** But I think I set it up correctly. in my settings.py AWS_S3_HOST = 's3.me-south-1.amazonaws.com' AWS_S3_REGION_NAME= config('AWS_S3_REGION_NAME') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_kEY = config('AWS_SECRET_ACCESS_kEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') I tried Give IAM permission on EC2 Delete EC2 retry set env var via export throw away virtualenv and try install awscli and configure it s3 bucket policy configure tried to write it inline because it might not be able to refer to the .env file, but it gave me same message. I struggled with this problem all day today. When it comes to AWS Config, I think I've tried everything I can. If you have any guesses about the cause of this problem, please give me a hint. And I only think boto3 looks up keys in a peculiar way on EC2 -
django what is best way to handle Exception in views
I have like 15 views , I dont want to add try, except for every view . Should I create a middleware or decorator or mixins or something else for error handling ? -
alternative option of blank=True in django model
I want to have a ForeignField that can be null some times depending on a BooleanField. so is this necessary to make it blank=true. Explaning the requirement: I have in models.py class InfaUsers(models.Model): first_name = models.CharField(max_length=30, default=None, null=True) last_name = models.CharField(max_length=30, default=None, null=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) role = models.ForeignKey(UserRoles, on_delete=models.CASCADE) dispute = models.ForeignKey(Disputes, on_delete=models.CASCADE) ...[some more fields]... class CorporatePartyNames(models.Model): name = models.CharField(max_length=100, default=None, null=True) is_added_by_infa_user = models.BooleanField(default=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) # can not make it blank=True because of some api, which may go in fault. party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) ...[some more fields]... in admin.py: class DisputeUserRoleInline(admin.TabularInline): model = DisputeUserRole form = DisputeUserRoleForm # fields = ['corporate_party', 'is_individual', 'address', 'nationality', # 'infa_user', 'is_added_by_infa_user', ] @admin.register(Disputes) class DisputesAdmin(admin.ModelAdmin): list_display = ('id', 'case_id', 'status', 'created_at') inlines = [ DisputeUserRoleInline, ] fields = ['is_new_case', 'case_id', 'claim_amount', 'type_of_dispute'] # list_filter = ('group', 'collection_type') form = DisputesForm class Meta: model = Disputes in forms.py: class DisputesForm(forms.ModelForm): class Meta: model = Disputes exclude = [] class DisputeUserRoleForm(forms.ModelForm): full_name = forms.CharField(required=False) # … -
Gunicorn , no module named mysite.wsgi
I tried to configure gunicorn but i'm an error i can't solve. I looked around to see, but no issue ... I think it's a simple trick , if you can help me I based my configuration on this tutorial here I started on a brand new installation , so folder are standard: -tripplanner | -my_env/ | -mysite/ | mysite/ | firstapp/ | manage.py when I'm on the Step 7 — Testing Socket Activation i got this error for sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-09-14 14:38:46 UTC; 10s ago Process: 7946 ExecStart=/home/debian/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock mysite.wsgi:application Main PID: 7946 (code=exited, status=3) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: return _bootstrap._gcd_import(name[level:], package, level) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: ModuleNotFoundError: No module named 'mysite.wsgi' Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7950] [INFO] Worker exiting (pid: 7950) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7946] [INFO] … -
Django data migration fails unless it's run separately
I've run into this a couple other times and can't figure out why it happens. When I run the migrations all together through ./manage.py migrate then the last migration (a data migration) fails. The solution is to run the data migration on it's own after the other migrations have been completed. How can I run them all automatically with no errors? I have a series of migrations: fulfillment/0001.py order/0041.py (dependency: fulfillment/0001.py) order/0042.py order/0043.py I followed this RealPython article to move a model to a new app which which works perfectly and is covered by migrations #1 to #3. Migration #3 also adds a GenericForeignKey field. Migration #4 is a data migration that simply populates the GenericForeignKey field from the existing ForeignKey field. from django.db import migrations, models def copy_to_generic_fk(apps, schema_editor): ContentType = apps.get_model('contenttypes.ContentType') Order = apps.get_model('order.Order') pickup_point_type = ContentType.objects.get( app_label='fulfillment', model='pickuppoint' ) Order.objects.filter(pickup_point__isnull=False).update( content_type=pickup_point_type, object_id=models.F('pickup_point_id') ) class Migration(migrations.Migration): dependencies = [ ('order', '0042'), ] operations = [ migrations.RunPython(copy_to_generic_fk, reverse_code=migrations.RunPython.noop) ] Running the sequence together I get an error: fake.DoesNotExist: ContentType matching query does not exist. If I run the migration to order/0042.py then run order/0043.py everything works properly. How can I get them to run in sequence with no errors? -
import OAuth2Authentication ImportError: No module named 'oauth2_provider.ext'
I'm trying to login by Facebook in my python projcet .it keeps telling me that ImportError: No module named 'oauth2_provider.ext' whenever I migrate it using terminal my installed using pip freeze : certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 cryptography==3.1 defusedxml==0.7.0rc1 dj-database-url==0.5.0 Django==2.2.16 django-braces==1.14.0 django-oauth-toolkit==1.3.2 django-oauth2==3.0 django-rest-framework-social-oauth2==1.0.4 djangorestframework==3.11.1 gunicorn==19.6.0 idna==2.10 oauthlib==3.1.0 Pillow==3.3.0 pycparser==2.20 PyJWT==1.7.1 python-social-auth==0.3.6 python3-openid==3.2.0 pytz==2020.1 requests==2.24.0 requests-oauthlib==1.3.0 shortuuid==1.0.1 six==1.15.0 social-auth-app-django==1.1.0 social-auth-core==3.3.3 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==3.2.1 and requirements.txt file contains: Django==1.10 gunicorn==19.6.0 Pillow==3.3.0 whitenoise==3.2.1 dj-database-url==0.5.0 psycopg2==2.7.5 django-rest-framework-social-oauth2==1.0.4 and my runtime.txt file : python-3.5.2 and the code I used to login by Facebook from the site I used in settings.py in INSTALLED_APPS = [.., 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] TEMPLATES = [ ..., 'OPTIONS': {..., 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = '355645928947054' SOCIAL_AUTH_FACEBOOK_SECRET = 'c606775c70e7dc01626ee41cbf95a0b8' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } and in urls.py : in urlpatterns = [... , .., url(r'^api/social/', include('rest_framework_social_oauth2.urls')), ] -
Form in django not saving in Psql
Sorry I am learning Django and this is my first project. I want to allow the user to up/down vote others users post. I have a model. I am using postgresql as database, and I am able to create users, and was even able to create posts for each users, but when I added in my model Django the following vote fields: upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") it just stopped saving users post in the database. It does not display any errors nothing, it just does not save. model.py from django.db import models from django.contrib.auth.models import User # Create your models here. from django.conf import settings class UserPost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL ) title = models.CharField(max_length=250, blank=False) description = models.CharField(max_length=500, blank=False) images = models.ImageField( upload_to='post_pictures/', null=True, blank=True) videos = models.FileField(upload_to='post_videos/', null=True, blank=True) upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") In the view.py the login and the registering works, but since I want to display all the post in the index I see nothing. Bc the DB is empty. @login_required(login_url='/login-page/') def personalPage(request): form = FormPost(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, "Successfully created") return render(request, 'accounts/personal-page.html', … -
Upload a CSV file using AJAX in djngo
I want to upload a CSV file using ajax query. template: <form id="attendance-form" method="POST" enctype="multipart/form-data"> <input type="file" id="upload-attendance" name="employee-attendance-file"> </form> AJAX: $("#upload-attendance").change(function(e) { e.preventDefault(); // disables submit's default action var input = $("#upload-attendance")[0]; var employeeAttendanceFile = new FormData(); employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]); console.log(employeeAttendanceFile); $.ajax({ url: '{% url "attendance:employee-attendance-upload" %}', type: 'POST', headers:{ "X-CSRFToken": '{{ csrf_token }}' }, data: { "employee_attendance_file": employeeAttendanceFile, }, dataType: "json", success: function(data) { data = JSON.parse(data); // converts string of json to object }, cache: false, processData: false, contentType: false, }); }); after uploading a CSV file, when I console.log the file(console.log(employeeAttendanceFile);) variable nothing return. When I fetch ajax request from django view, it(print(csv_file)) also returns None. views.py: class ImportEmployeeAttendanceAJAX( View): def post(self, request): csv_file = request.FILES.get("employee_attendance_file") print(csv_file) Where am I doing wrong? -
Django Private Channel - two users
I'm trying to build a channel. I'd like to restrict the detail views to consumer and seller. I don't want the other users have an access to the detail views. The thing is I can make it accessible to one but I don't know how to make it accessible for both consumer & seller? class Group(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="") ... def __str__(self): return self.name #Detail channel @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView): ... def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.consumer or self.object.seller != request.user: #it's redirect me to home page return HttpResponseRedirect('/') return super(CheckoutDetail, self).get(request,*args,**kwargs) -
I am getting an error when running server in Django
when executing py manage.py runserver command I get the error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\users\galen\mysite\mysite\urls.py", line 20, in <module> path('polls/', include('polls.urls')), File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\conf.py", … -
Converting data types for python and django
I have two main variables, week_order_overall_total which is a custom python money data type using this (https://github.com/mirumee/prices) and then the actual integer references below (5, 200, 15 etc). When I try I do a calculation with the two using payout = week_order_total_card - hm_fees, I get an error message: '>=' not supported between instances of 'Money' and 'int' I imagine this is because there are two different data types being used. I have tried resolving it using int(week_order_overall_total) but that doesn't work. CODE: if trial_status =="yes": if admin_value <=5: hm_fees=5 else: hm_fees=admin_value elif early_customer =="yes" and week_order_overall_total >=1 and week_order_overall_total <= 200: hm_fees=15 elif week_order_overall_total == 0: hm_fees=0 elif week_order_overall_total >= 1 and week_order_overall_total <= 200: hm_fees=20 elif week_order_overall_total >= 201 and week_order_overall_total <= 400: hm_fees=35 else: hm_fees=55 payout = week_order_total_card - hm_fees Any help is appreciated. -
Redirect back to previous page after login in django-allauth
There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared: LOGIN_REDIRECT_URL = "projects:home" I searched and I found this could be a solution: <a href="{% url 'account_login' %}?next={{request.path}}">Please login to reply</a> but this even didn't work. Thank You -
How to make Django template engine recognize an expression from an injected string
I am injecting meta/title tags dynamically for each page by using a yaml file full of html tags. HTML {% if meta_tags %} {% for tag in meta_tags %} {{ tag|safe }} {% endfor %} YAML trending_bonds: - '<title>Trending Searches for {% now "Y-m-d" %}</title>' The view just loads the yaml into a dict of strings and passes it along to template in that meta_tags variable. I need that {% now %} expression to be run and show the current date but it keeps getting inserted as a string just like shown above. Any ideas? -
Django html template how to display variable inside variable?
i have templater which contains.Driver, Car and campaign model and i have template base model wherere all model and body, text and another field contains and i added in body {driver.fleet} but when i try to see html template its not shwoing value of fleet its just shows {driver.fleet} like this. <section class="table_driver" style="margin: 0 auto; max-width: 760px;"> <div class="somehtinff_fix"> {{template.container_en|safe}} #this is fiels </div> </section> conainer_en text is like this Our tips for you: (General tip) To give you more peace of mind and a safer driving, next morning, you should go and inflate you tires to the currect pressure. Why?(link) {driver.fleet} #this should through that driver fleet name (Specific tip) We also noticed that you have the tendecy to drive in a lower gear even on a straight, this forces your engine to overspeed, use more fuel and overheat. Try to drive on a higher gear on a straight even if you driving slow. Try driving in a 4th or 5th gear, 6th might be to hight but you can try, less noise, smoother driving and less 5 to 10% fuel consumption. Trip(Link this is the code where template file exist ctx = { "driver": self.driver, # `here … -
How to save user input in database from django form
I hava created a small project in django where i have created a form and with 3 fields now i want if user type his name , email and invite message then it should save in databse. i am unable to save the data in database. form.py from datetime import datetime from bootstrap_datepicker_plus import DatePickerInput from django.contrib.admin.widgets import AdminDateWidget from bootstrap_datepicker_plus import DateTimePickerInput from bootstrap_datepicker_plus import TimePickerInput # from .models import check class Email_app(forms.Form): Name = forms.CharField() Email = forms.EmailField() Invite = forms.CharField() start_date = forms.DateField(label="Start_Date", widget=DatePickerInput()) start_time = forms.DateField(label="Start_Time", widget=TimePickerInput()) end_date = forms.DateField(label="End_Date", widget=DatePickerInput()) end_time = forms.DateField(label="End_Time", widget=TimePickerInput()) def __str__(self): return self.Name Form > enter image description here below is the view.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import formatdate # from email import encoders from email.encoders import encode_base64 import os,datetime COMMASPACE = ', ' # from django.shortcuts import render # Create your views here. from django.shortcuts import render from operators.settings import EMAIL_HOST_USER from . import forms from django.core.mail import send_mail # Create your views here. #DataFlair #Send Email def email_app(request): sub = forms.Email_app() if request.method == 'POST': sub = forms.Email_app(request.POST) subject = 'Welcome to Email Event' message = … -
Passing Data Through AJAX Call Causes Failure
I am building a really simple AJAX call using Python/Django. I've never had issues with it before, but now I keep on getting a Not Found error if I ever put actual data in the AJAX call. Works fine if I place no data. I must be making a very obvious mistake that I just can't see. In my code below, if I comment out the #test value it will work fine, so I know all the URLs are working correctly. It's just if I add any real data it fails (#product_id_notes is just filler, does not refer to an actual ID). Can anyone help bail me out here? This has been driving my crazy for the last several hours. My error: Not Found: /admin/ajax/order_analysis My code: <button id = 'test1234' >Submit</button> <input id = "submit-order-analysis-url" type = 'hidden' value = ' {% url 'admin:order_analysis' %} '> <div id = "test" value = "123">This is a test</div> <script> $('#test1234').click(function(){ var url = $('#submit-order-analysis-url').val(); var data = {'test':$('#test').val(), 'product_id':$('#product_id_notes').val() } $.ajax({url: url, data: data}) .done(function(data){ //do nothing }) .fail(function(){ //do nothing console.log("Something went wrong") }); }) </script> -
How to aggregate time for each employee in bi-weekly pay schedule in Django
How to add up time_work for each employee up to 15th of each month? class TimeLog(models.Model): employee = models.IntegerField(null=True, blank=True, related_name='employee id') start_date = models.DateTimeField (null=True, blank=True) end_date = models.DateTimeField (null=True, blank=True) time_worked = models.DurationField(null=True, blank=True) -
Python requests login to django
hey im trying to login into the django page at https://extensions.gnome.org/ import requests from bs4 import BeautifulSoup client = requests.Session() client.headers.update({"referer": "https://extensions.gnome.org/accounts/login/"}) data = client.get("https://extensions.gnome.org/accounts/login/") soup = BeautifulSoup(data.text) mtoken = soup.find("input", {"name": "csrfmiddlewaretoken"}) print(mtoken["value"]) csrftoken = client.cookies["csrftoken"] login_data = client.post("https://extensions.gnome.org/accounts/login/", data={ "csrfmiddlewaretoken": csrftoken, "username": "email", "password": "password", "next": "/" }) print(login_data.text) but the response is always invalid csrf token. has someone an idea how to get this working? -
Update Django model instance only if certain condition is met
I'm trying to solve what looked like an easy problem at first to me and probably I'm overthinking it, but I'm unsure where to put the bit of logic required, so any input would be much appreciated. Following situation (example code, not real project) # models.py class Product(models.Model): title = models.CharField() price_in_cents = models.IntegerField() # ... class ProductImage(models.Model): product = models.ForeignKey('Product', null=True, blank=True) image = models.ImageField() user = models.ForeignKey(get_user_model()) # ... So in short I have products and images that show these products. This is part of a DRF project which is consumed by a Vue frontend. The flow is as follows: The client creates new images by posting the image data to /api/productimages/ The API creates the Image instance and returns the data including the created instances PK. The client then posts a list of image ids along with the data to create the product to /api/products/ the api creates the product and should now associate the passed images with the created product. This should only happen if current user == image.user and image.product is not set yet (==Null) Now my question: Where should I put the logic to associate the images with the created product? I see the … -
Django ValidationError when serializing nested object
So I have a serializer like this: class FirstSerializer(serializers.ModelsSerializer) second = SecondSerializer() class Meta: model = First While validating SecondSerializer may raise ValidationError. If it does, in return I get this: { "first": { "second": [ "Error" ] } } How can I make this error not connected with validated field, for example: { "non_field_errors": [ "Error" ] } -
Django whats the .distinct('column_name') for SQLite equivalent?
In my current project, I need to select all distinct elements from my SQLite database and I wanted to use: distinct_ingredients = Ingredients.objects.all().distinct('ingredient') But I learned that this just works for I think PostgreSQL, so my question is what is the equivalent to .distinct(column_name) for an SQLite Database? I tried different things out but the didn't give me the distinct ones. Thanks for your help. -
Currency symbol not displaying correctly on Saleor platform
Please I have some issue with displaying the right currency symbol for Naira in saleor platform. In the documentation, I saw it could be changed by redefining DEFAULT_CURRENCY in settings.py DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD") How I approached the issue: Saleor-platform default currency came with USD which displayed $ as the currnecy symbol (e.g $ 1000) Then I changed it to NGN but it displayed NGN as the currency symbol (e.g NGN 1000) instead of ₦1000 And then I tried changing it to EUR and it displayed € as the currency symbol (e.g €1000) Maybe minor countries where not considered while building the platform. Please could there be a way to tweak this? see screenshot of the display below: saleor currency display -
Django: get_or_create not creating object, only reporting error that matching query does not exist
I am making my first django web (mostly for fun -hence the theme, toilet rating app- and learning). But this stopped being fun a day ago. I am trying for user to be able to create and rate the toilets (create/update user's rating). Creation is fine, the rating is where I have all the issues. The current and biggest problem is that line rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) is throwing rating.models.Rating.DoesNotExist: Rating matching query does not exist. Now the snippets: VIEW: @login_required(login_url='login') def rate_toilet_view(request, upk, tpk, *args, **kwargs): toilet = Toilet.objects.get(id=tpk) user = User.objects.get(id=upk) rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) form = RatingForm(instance=rating) if request.method == "POST": form = RatingForm(request.POST, instance=rating) if form.is_valid(): form.save() toilet = Toilet.objects.get(toilet_id = toilet) # SOME COMPUTATIONs HERE toilet.save() return redirect('/') context = {'form': form} return render(request, 'pages/rate_toilet_form.html', context) MODELS: class Rating(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) user_id = models.ManyToManyField(User, through='RatingUser') toilet_id = models.ManyToManyField(Toilet, through='RatingToilet') # FIELDS TO BE RATED HERE class RatingUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class RatingToilet(models.Model): toilet = models.ForeignKey(Toilet, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class Toilet(models.Model): CATEGORY = (#CATEGORIES OF TOILETS HERE#) id = models.IntegerField(primary_key=True, auto_created=True) category = models.CharField(max_length=120, null=False, choices=CATEGORY, default=None) place = models.CharField(max_length=120) # OVERAL VALUES OF RATED … -
URL Keep Adding Backslash Django
I need your help in fixing this issue. urlpatterns = [ path('', views.dashboard, name='dashboard'), path('menu', views.menu, name='menu'), path('close', views.close, name='close'), path('lead', views.lead, name='lead'), path('audience', views.audience, name="audience"), path('audience/<action>', views.audience, name="audience") ] That's my code URLs but I keep getting a backslash at the end of the URL. For instance, if I link to dashboard/menu, I get dashboard/menu/