Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ERROR: Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name
I have been trying to display the list of jobs in the template and when i call archived or current jobs url .i am getting the following error only when there is some jobs available Thanks in Advance Traceback Environment: Request Method: GET Request URL: http://localhost:1000/customer/jobs/current/ Django Version: 3.2.6 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'social_django', 'core.apps.CoreConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.ProfileMiddleware'] Template error: In template C:\Users\Subash A\venvdelivo\delivo\core\templates\base.html, error at line 0 Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name. 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : <head> 4 : <meta charset="UTF-8"> 5 : <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 : <title>Home</title> 8 : {% load bootstrap4 %} 9 : {% bootstrap_css %} 10 : {% bootstrap_javascript jquery='full' %} Traceback (most recent call last): File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Subash A\venvdelivo\delivo\core\customer\views.py", line 145, in current_jobs return render(request,'customer/jobs.html', { File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\shortcuts.py", line 19, in render content … -
How to show list data in Django Template?
I have a field receiver_address in my Booking Model I am storing list of address details as Road number, House number and Others. For example ['25 jalan', '35','Others'] Now i want to show data in my booking list. My Django template code {% for adress in booking.receiver_address %} address {% endfor %} But it's not working. I am willing to see as like 25 jalan,35,others in my booking list. My present result in this . How can i get full address as 25 jalan,35,others. -
How to Run Crontab within a Django Virtual Environment?
I'm running into issues when running a cron (using Crontab) within my Virtual Environment. If I do: python manage.py crontab add Terminal returns: sh: line 1: /usr/bin/crontab: No such file or directory (but it does recognise the details of the cronjob): /bin/sh: line 1: /usr/bin/crontab: No such file or directory adding cronjob: (325473fff5b0bfd8ec611f26efe10e43) -> ('*/1 * * * *', 'core.cron.my_scheduled_job') If I do: which crontab Terminal returns: which: no crontab in (/......../venv/bin:/app/bin:/usr/bin) It seems pretty clear this is a file routing problem, I just can't figure out a way to resolve, and there doesn't seem to be any similar cases I can find online. If relevant, I'm running this locally on Linux currently -
app[web.1]: Not Found: /static/js/index.js
This is my settings file from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '...' DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'game' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'reverenz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'game', 'templates', 'game')], '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', ], }, }, ] AUTH_USER_MODEL = 'game.User' WSGI_APPLICATION = 'reverenz.wsgi.application' DATABASES = { 'default': { 'ENGINE': '..', 'NAME': '..', 'USER': '..', 'PASSWORD': '..', 'HOST': '..', 'PORT': '..', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = '/img/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Here is my folder structure The project works fine on localserver but whenever I try to host it on Heroku, the js, css and img files don't get linked and in the heroku logs i see-> app[web.1]: Not Found: /static/js/index.js Any assistance in this … -
AttributeError: 'MigrationLoader' object has no attribute 'items' django migration error
i had sqlite conflict error, after merging i got another sqlite regex match error so i deleted migrations and sqlite files. when i run 'python manage.py makemigrations' i got this error and i don't know how to solve. File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 22, in <module> main() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle for app, names in conflicts.items() AttributeError: 'MigrationLoader' object has no attribute 'items' -
error loading data when deploying django with apache2
I have a django app working fine with runserver, but when I deployed it with apache2 and mod_wsgi I got this weird error: [Sat Sep 04 11:16:12.218713 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] 2021-09-04 11:16:12,217 WARNING load Error occurred during loading data. Trying to use cache server https://fake-useragent.herokuapp.com/browsers/0.1.11 [Sat Sep 04 11:16:12.218795 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] Traceback (most recent call last): [Sat Sep 04 11:16:12.218805 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 154, in load [Sat Sep 04 11:16:12.218825 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] for item in get_browsers(verify_ssl=verify_ssl): [Sat Sep 04 11:16:12.218842 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 99, in get_browsers [Sat Sep 04 11:16:12.218850 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] html = html.split('<table class="w3-table-all notranslate">')[1] [Sat Sep 04 11:16:12.218870 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] IndexError: list index out of range I don't understand the error at all! -
pip freeze raises an error cannot import name 'SCHEME_KEYS' pip._internal.models.scheme import SCHEME_KEYS, Scheme
In Django app on ubuntu, I tried to use pip freeze, it suddenly raises an error from pip._internal.models.scheme import SCHEME_KEYS, Schem, it cannot import 'SCHEME_KEYS'. Any clue? -
How to get each client video frame on django server in agora
Here is the scenario that I want to do with agora. Assume that there are N users connected on the same channel in the agora. I want to access the video frame of each user on the server-side so that I can apply AI and process that frame on the server and save their activity log into the database. How can I achieve this? I tried with https://github.com/AgoraIO-Community/Agora-Python-QuickStart but nothing seems to work for me. -
How to get queryset in django?
I am trying to send an email to those orders that is created 5 minutes before the datetime.now(). I try to filter the orders but it is not working, it is not giving me any queryset. How to do this? I am sharing my code. def my_email(): now = datetime.now() - timedelta(minutes=5) # 11:55 now = now.replace(tzinfo=pytz.utc) print(now) order = Order.objects.filter(createdAt__gt = now) print(order) for o in order: print(o._id) -
how to change herkou region from us to eu
i have pre deployed app on heroku but b default it region is us and i am from india so my load time is very much then expected so i want to change region to eu which exactly half of distance from us so my load time will improved i also tried the documentation https://devcenter.heroku.com/articles/app-migration but i falied to migrate if someone did it before please guide me step by step it would be very helpful for me and other future reader thank you for your time -
Django: Non-primary Foreign Key object can't access related model instance
I'm new in Django. I have 2 class tech_system adn equiptment in models.py class tech_system(models.Model): id_tech_system = models.BigAutoField(db_column='ID_tech_system', primary_key=True) system_descript_short = models.CharField(max_length=255, blank=True, null=True) #More field here tech_system_code = models.CharField(unique=True, max_length=40) class Meta: managed = False db_table = 'tech_system' def __str__(self): return self.system_descript_short class equiptment(models.Model): id_thietbi = models.BigAutoField(db_column='ID_thietbi', primary_key=True) tech_system_code = models.ForeignKey('tech_system', models.DO_NOTHING, db_column="tech_system_code", blank=True, null=True) class Meta: managed = False db_table = 'equiptment' I use python shell, equiptment model object can't access to related tech_system model instance. I got the error matching query does not exist. I want to get the value obj1.equiptment.tech_system_code.system_descript_short. How can I do? Thank you. >>> obj1 = equiptment.objects.first() >>> obj1.tech_system_code_id '530' >>> obj1.tech_system_code Traceback (most recent call last): File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'tech_system_code' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__ rel_obj = self.get_object(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 154, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "D:\Dev1\env1\lib\site-packages\django\db\models\query.py", line 437, in get self.model._meta.object_name app.models.tech_system.DoesNotExist: tech_system matching query does not exist. -
Django ORM - Primary key not available after save while using UUIDField and RandomUUID In Postgres
For a project I'm working on, in one of the models i am using models.UUIDField for primary key with the default value set to django.contrib.postgres.functions.RandomUUID Here's my model. from django.contrib.postgres.functions import RandomUUID from django.db.models import JSONField class NewsItem(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID()) title = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) subtitle = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) excerpt = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) text = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) image = models.ForeignKey(ImageObject, models.DO_NOTHING, related_name='+', null=True) priority = models.IntegerField(null=True, default=0) frequency = models.IntegerField(null=True, default=1) text_effects = JSONField(blank=True, null=True, default=dict) scroll_speed = models.IntegerField(null=True, default=1) scroll_direction = models.IntegerField(null=True, default=0) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'news_items' The issue here is that i need to immediately access the primary key after the object has been inserted into the database, however trying to access pk or id after calling save simply returns a literal string RandomUUID() In [1]: from media.models import NewsItem In [2]: n = NewsItem() In [3]: n.save() In [4]: n.id Out[4]: RandomUUID() In [5]: str(n.id) Out[5]: 'RandomUUID()' However, if i issue a query like model.objects.first() or model.objects.last() and then access the id or pk of the returned instance, it works as expected. In [6]: … -
Django how do I run a backend python function using GraphQL
I am using ariadne for graphql and Django in the backend with Vue in the front. How do I send the variables from vue to run a function in the backend? I am trying to do this REST API example except in GraphQL: Run Python script from rest API in django -
How to avoid to_representation to not be used in Child class from parent class using python and django?
i want to not use a to_representation method defined in Parent class to be used in child class. i have a Parent class AccessInternalSerializer and child class AccessSerializer. below is my code, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } class AccessSerializer(AccessInternalSerializer): private_key = serializers.FileField( write_only=True, allow_null=True, required=False) ca_cert = serializers.FileField( write_only=True, allow_null=True, required=False) class Meta(AcessInternalSerializer.Meta): extra_kwargs = { **AccessInternalSerializer.Meta.extra.kwargs, 'private_key': { 'write_only': True } 'ca_cert': { 'write_only': True } } the above code works. but the AccessusernameInternalSerializer wasnt returning private_key and ca_cert fields in the output hence i used to_representation in the AccessInternalSerializer like below, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) def to_representation(self, obj): data = super().to_representation(obj) data['private_key'] = obj.private_key data['ca_cert'] = obj.ca_cert return data class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } the above code works. it returns private_key and ca_cert fields in the output. but it also returns these fields private_key and ca_cert fields in the AccessSerializer class (child class) i think its because of to_representation in AccessInternalSerializer (that … -
Invoking a function everytime when django server is closed
I am using yield function and want to store its state everytime the server is closed. Is there any method to do it ? -
what i wrote in admin.py didnt appear , i dont have idea what happening here? i think there is not problem [closed]
https://github.com/Angelheartha/tera this is my github i wrote before i dont have idea why after writting at admin.py it cant reflect as if i didnt write any code when i do http://127.0.0.1:8000/admin ? i thought because i missed something at setting.py but it seems not the case... in admin.py something too ,but is seems not i dont know what is the problem here i did python manage.py migrate but not change so what can be the problem? -
Creating Dynamic Form Fields in Django ModelForm
I am looking to search the instance, check a value in a specific field and then return a list for the field to Meta but it doesn't appear the __init__ can return anything. How can I make a dynamic form that based on a value in a field, shows only a predetermined other fields. Goal: Ultimately if subgrade_02_weight != None then make subgrade_02_title, subgrade_02_weight, subgrade_02_1_star, etc. visible. I have over 100 fields that I would need to make visible and do not want to do this in a hack way in the template. It seems like JS is the best approach but I have 0 experience in JS. class Inspection_ResultForm(forms.ModelForm): #work on this tomorrow def __init__(self, user, *args, **kwargs): super( Inspection_ResultForm,self).__init__(*args, **kwargs) #if user.groups.filter(name='Operations Manager').exists(): fields_list = ["subgrade_00_title", "subgrade_00_weight", "subgrade_00_1_star", "subgrade_00_2_star", "subgrade_00_3_star", "subgrade_00_4_star", "subgrade_00_5_star", "subgrade_01_title", "subgrade_01_weight", "subgrade_01_1_star", "subgrade_01_2_star", "subgrade_01_3_star", "subgrade_01_4_star", "subgrade_01_5_star" ] if self.instance.inspection_request.sample.order.specification.subgrade_02_weight != None: fields_extends = ["subgrade_02_title", "subgrade_02_weight", "subgrade_02_1_start", "subgrade_02_2_star", "subgrade_02_3_star", "subgrade_02_4_star", "subgrade_02_5_star"] fields_list.extend(fields_extends) print(fields_list) fields = fields_list return fields class Meta: model = Inspection_Result fields = ('subgrade_00_title', 'subgrade_01_title',) #would like this to be equal to field list calculated in __init__ -
File-field in Django admin not showing when upgraded Django to 3 from 2.1
Django admin file field is showing "loading" after upgrading Django to 3 from 2.1 The console shows the error It was working fine when it was 2.1. -
Django on button click open modal and populate the form
I have a modal which contains a HTML form with customer details. On button click I want to get the details for the customer from view, open the modal and populate the details in the modal <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg"><i class="fa fa-fw fa-edit"></a></td> It opens the modal but does not calls the function in view. I tried this way <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary edit_btn"><i class="fa fa-fw fa-edit"></a></td> By handling everything in js $(".edit_btn").click(function(){ var _url = $(this).attr('href'); $.ajax({ url: _url, success: function(response){ //show the modal //populate the form document.getElementById("customer_name).value = ""; ... }, error: function(error){ console.log(error) } }); }); But I don't want to do this way. I want to to populate in template only. Something like this - <form> <label>Customer Name:</label> {{ customer.customer_name }} <br> </form> Is it possible? -
How to annotate sum over Django JSONField (Array of objects) data?
I have models sth like this # models.py class MyModel( models.Model ): orders = models.JsonField(null= True, blank=True, default=list) category = models.ForeignKey(Category, on_delete=models.CASCADE) I stored json data in this structure. [ { "order_name": "first order", "price": 200 }, { "order_name": "second order", "price": 800 }, { "order_name": "third order", "price": 100 } ] I want to sum price of all json objects ie 200+800+100 -
Block title in child template does not override
I have been trying to inherit from the base.html template of my application but when I override the block title it in the child template does not render it. I have read and the read the documentation but I don not see what I am doing wrong. Hereunder is my code: Base.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>{%block title %} {%endblock%}</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ntegrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> {%block content %} {%endblock content %} </body> Childtemplate, {% extends 'simple_investing/base.html' %} <head> <title>{% block title %} Welcome to Simple Investing {% endblock%}</title> </head> {%block content%} <body> <br> <p style = "font-style: normal">This website has the goal of assisting <strong><em>you</em> </strong> in the process of making <strong><em>sound investment decisions</em></strong> in the <i>stock market</i>. In order to accomplish this goal we focus on:</p> <ul> <li><p> Basic concepts that everyone should know before making an investment.</p></li> <li><p> Providing the tools necessary to analyze the fundamentals of any public company. You can create a portfolio of companies that you are interested in.</li><p> </ul> <br> <p>Let's start by learning the main <a href ="http://127.0.0.1:8000/concepts">concepts.</a> </p> <p>If you already have a … -
Django Form Not Sending File via Modal
I'm trying to upload a file via a form inside a bootstrap modal. request.POST correctly shows the file name in QueryDict, but request.FILES shows an empty MultiValueDict. For comparison, I also tried another version of the form that is exposed in the page, which seems to be working perfectly. What's the difference? Thanks. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <!-- UPLOAD FILE --> <form action="." method='post' enctype="multipart/form-data"> {% csrf_token %} {{ file_form.as_p }} <input type="submit" value="Upload"> </form> <!-- MODAL VERSION --> <a href="#" type="button" class="btn" data-toggle="modal" data-target="#statusModal"> Modal </a> <div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">UPLOAD FILE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action =".?&status=status-update" enctype="multipart/form-data" method = "post"> <div class="modal-body"> {% csrf_token %} {{ file_form.as_p }} </div> <div class="modal-footer"> <input class="btn green-button" type = "submit" value = "Send"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </body> </html> views.py: from django.shortcuts import render, redirect from upload_file.forms import FileForm from upload_file.models import File def index(request): if request.method == "POST": print(request.POST) print(request.FILES) file_form … -
Django: How can I create a function in models to get the username that made that post and also in views
I am creating a forum and i’ve been paralized with this problem, i can’t create a model to get the username of the user that made a post in the forum, i made a search and found nothing hope someone can help me -
Requests in Vuejs returning different response than Postman from django-rest-framework backend
I have been trying to implement the Twitch user authorization code flow. I am working on getting the authorization url generated from the django backend and pass it to my Vue front end so the user can open the user authorization page. Postman recovers the generated url perfectly however when i try to do the same in Vue using Requests it is giving me an entirely different object. Object { _events: {…}, _eventsCount: 1, _maxListeners: undefined, uri: {…}, method: "POST", readable: true, writable: true, explicitMethod: true, _qs: {…}, _auth: {…}, … } auth.js:37:12 and here is what Postman returns "{'url': 'https://id.twitch.tv/oauth2/authorize', 'client_id': 'xxx', 'redirect_uri': 'http://localhost:8000/api/twitch/callback', 'grant_type': 'token', 'scope': 'user_read'}" I'm not sure what could be causing this. Below is the code used to get to this point. urls.py from django.conf.urls import url from django.urls import include, path from better_auth import views urlpatterns = [ url(r'^api/token$', views.get_twitch_token), url(r'^api/auth/login$', views.get_twitch_user_token_uri), url(r'^api/auth/twitch/callback$', views.save_twitch_user_token), ] views.py import json import os import requests from django.http.response import JsonResponse from rest_framework.decorators import api_view from rest_framework import status # get user access token @api_view(['POST']) def get_twitch_user_token_uri(request): endpoint = "https://id.twitch.tv/oauth2/authorize" token_url = { 'url': endpoint, 'client_id': settings['TWITCH_CLIENT_ID'], 'redirect_uri': settings['TWITCH_REDIRECT_URI'], 'grant_type': 'token', 'scope': 'user_read' } Json = json.dumps(token_url) Json = … -
can't passe form's attrs in ModelForm to Template
I'm trying to set a ModelForm, but when I don't get the attrs that I set in my Form in the Template. also I wan't to get the date input in the format dd/mm/yyyy, this is my model: class Delivery(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=_("delivery_user")) full_name_reciever = models.CharField(_("Reciever Full Name"), max_length=50) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.CharField(max_length=250) destination_city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=_("delivery_city")) destination_post_code = models.CharField(max_length=20) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) boxes_number = models.PositiveIntegerField(_("Number of Boxes"), default=1) boxes_wight = models.PositiveIntegerField(_("Boxes Wight"), default=1) boxes_volume = models.PositiveIntegerField(_("Boxes Volume"), default=0) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) billing_status = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def __str__(self): return str(self.created_at) The ModelForm: class UserDeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = [ "full_name_reciever", "pickup_address", "destination_address", "destination_city", "destination_post_code", "operation_date", "boxes_number", "boxes_wight", "boxes_volume", "document", "invoice", "delivery_key", "billing_status", "delivery_status", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["full_name_reciever"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "full name reciever "} ) self.fields["pickup_address"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "pickup address "} …