Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show linked objects in Django Admin View?
I have two models that are linked by a foreign key relationship: class A(models.Model): q1 = models.CharField(max_length=60) q2 = models.CharField(max_length=60) ... class B(models.Model): b = models.CharField(max_length=60) a = models.ForeignKey("A", on_delete=models.CASCADE) In my admin site I have the A model showing, and ideally would like to keep it that way. Is there a way for me to within the individual A instances show the B instances? I have only been able to find solutions for the reverse (showing a dropdown of A instances in the individual B instances). -
Ajax function not showing values in django
Bit of a problem. What i am trying to do is determine what date the user has selected from an option picker and print the value from a main.py function. So let me show my set up. first thing i have done is calculate the date and in my views.py: def index(request): #GOING TO PUT THE DATE DIFFERENCE CALCULATION HERE the_uploaded_excel_file = excel_upload.objects.order_by('-id').first() excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) wb = load_workbook(excel_file_path_from_db) ws = wb["Sheet1"] df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) max_date_column = ws.max_column last_date_entered = ws.cell(row=1, column=max_date_column).value todays_date = datetime.datetime.now().date() Date_difference = pd.date_range(start= last_date_entered, end=todays_date, freq='D') print("last date entered was ") print(last_date_entered) print("todays date is ") print(todays_date) print("the days not done are") print(Date_difference) for date in Date_difference: print(date) return render(request, "index.html", { 'Date_difference': Date_difference }) Then I show the dates in my html: <h2> {% for daterange in Date_difference %} <h5>{{ daterange|date:"d M Y" }}</h5> {% endfor %} </h2> <select style="background-color: #ceedd0;" id="date_selector" onchange="what_date_has_been_picked()" name="filter_for"> {% for daterange in Date_difference %} <option value={{ daterange }}>{{ daterange|date:"d M Y" }}</option> {% endfor %} </select> this produces the following: now what I want to do is to be able to print this result in my main.py. so i set up an ajax function. … -
Django rest framework bulk post object
I want insert bulk json via django rest_framework however, I get a error message ; typed following line ; "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 6 (char 7)" my serializer.py file include following code block; class DrfSerializerV2(serializers.ModelSerializer): def __init__(self,*args,**kwargs): many=kwargs.pop('many',True) super(DrfSerializerV2,self).__init__(many=True,*args,**kwargs) class Meta: model = DrfData fields=['id','name','duration','rating','typ'] and my views.py file ; class ActionViewSet(viewsets.ModelViewSet): queryset = DrfData.objects.filter(typ="action") serializer_class = serializers.DrfSerializerV2 finally send json file via post; [ {'name':'m1','duration':120,'rating':4.7}, {'name':'m2','duration':120,'rating':4.5} ] however, I can't handle this error message. if I send sperataly, there is no problem. but, I can't resolve this error for bulk insert -
Can't run the server on Django TCP/IP conection?
I've already download all packages from django, whitenoise, etc, and the error continues. The cmd is running with the env and triyng to push i'm still on the same error I'm trying to run with a local host my server and that happend : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Domestico\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
How to pass variable from JavaScript to Django as part of url?
I'm building video player in Django. I use JavaScript to change prev/next video without refreshing the page by passing queryset from Django to JS. I need to add Like button to like currently played video. I can bring variable (ID) of current video but don't know how to include it in URL. This is how I'm bringing variable from JS to HTML. JavaScript: document.getElementById("video_controler").innerHTML=video_controler; Displaying it in HTML: Video controler: <a id="video_controler"></a> And in this form I want to replace hardcoded 'videos.0.pk' with 'video_controler' varibable: <form action="{% url 'like_post' videos.0.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="post_id" value = '{{ videos.0.pk }}'>LIKE</button> </form> -
Passing values from Jquery with Ajax to Django views
I'm building an django app where user can organize notes in three columns "To Do", "Progress" and "Done" with drag and drop made with Jquery sortable. On screen load, notes are imported from database and put inside column matching their status values. After user changes, "save" button can be clicked. That's where i want to make an update to note's status in database. Here's HTML with Javascript {% load staticfiles %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static '/css/bootstrap-5.0.0-beta1-dist/css/bootstrap.css' %}"> <script src="{% static 'css/bootstrap-5.0.0-beta1-dist/js/bootstrap.js' %}"></script> <script src="{% static 'js/jquery.js' %}"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script> </head> <body> <div id="con_p" class="col-sm-10 "> <div id="2"> <div class="row "> <div class="col text-center"><h3 class="display-5">TICKETS</h3></div> </div> </br></br> <div class="d-flex flex-row-reverse"> <button id="add-ticket" class="btn btn-primary btn-sm mx-2 " type="button" name="button">Add Ticket</button> <button id="save_tickets" class="btn btn-primary btn-sm " type="button" name="button">Save</button> </div> <div class="row border"> <div class ="col text-center"> <h4>To Do</h4> </div> <div class ="col text-center"> <h4>In Progress</h4> </div> <div class ="col text-center"> <h4>Done</h4> </div> </div> <div class="row"> <div class ="col border text-center" > <fieldset class="sortable"> <ol id="to_do" class="min-vh-100"> {% for i in ticket %} {% if i.status == "To Do" %} <li class="ticket" > … -
Django MSSQL: Override Foreign Key Constraint Name Generation
I am attempting to create a database model in Django 3.0 using django-mssql-backend as by db backend for SQL Server 2019. The database uses multiple schemas for the tables included in it with some of the tables being non-managed (already exist), and others being created from scratch through migrations. To get multiple schemas working, I used a hack I found on another answer on here that suggested formatting the tablename as follows: class MyModel(models.Model): ... class Meta: db_table = 'schema].[table' This is so that the SQL compiles to have the wrapped square brackets that automatically form on the outside complete the schema/table definition. The problem with this is that ForeignKey objects have their constraint names generate using this table name which causes invalid constraint names arise, causing the migration to fail once the tables are done being created and it comes time for the constraints to be created.\ They generate like this: [schema1].[table1_colname_id_bc165567_fk2_schema2].[table_colname] Is there a way to override this behaviour? If this can be overridden by forking the backend and adding manual compilation code how would I even go about doing that? Otherwise, how can I have foreign keys in my models while using multiple schemas and fully utilizing … -
Cookies are blocked during development DRF and Vue app
I have Django Rest Framework API and Vue SPA frontend app. I deploy both of them in the DigitalOcean App platform. I use Session Authentication. My problem is that Session and CSRF Token cookies do not work during development when Django and Vue are served by their default servers. I guess it is because of the Same Origin Policy and other security stuff. In the production, everything is working fine when they are on the same domain. I do not have this issue earlier because I was using Token Authentication which I found out is not suitable for web Apps. I need some way of using session and csrftoken cookies during development on my computer. Is this possible with Dockerazing both apps (they are in separete repositories currently) and starting them with some reverse-proxy like Nginx so they will have the same domain? Or mayby some other way so i could develop and deploy such app easier? I cant find any information about this problem in the internet, so maybe I am missing something, or should do something differently? -
Django: how to redirect to page with list of newly created objects after form post bulk_create
I have a simple form that allows user to paste csv data with the goal to create multiple model objects at one go. The form method is 'post'. Action url is a method that calls the django `bulk_create` to create the model objects returning the pks. Goal: After submission, I want to redirect to page showing a list of the objects corresponding to the pks. Is that possible? I have tried: return render(request, "list_template.html", context={'object_list': objects_with_pks}), passing the model objects as context data to another template (but there would be danger of duplicate submission upon refresh) Redirect user to a model DetailView which contains the pk in the url (but I have more than one pks created) return HttpResponseRedirect to a new page with a success message (but I won't be able to pass the pks to the new page) Other ways that I've thought but could not find an answer Can I pass multiple pks in a url? Is there a way to transform a POST request to a GET? Can querysets in a model ListView instance be passed as parameters? I am fairly new to web development and posting questions on stackoverflow. Please comment if its unclear and … -
Django: TypeError: Object of type ModelBase is not JSON serializable
I get Error 'TypeError: Object of type ModelBase is not JSON serializable'. But i don't use JSON. And i don't put any 'ModelBase' object to templates. It's started when i began to use request.session for global variables store. When i used global variables like in pure Python - this project worked ok. (On local developer server, but was a problem with works on deploy for multiuser load.) I can't understand where it problem is appears: I use Debug mode - my views.py function is runned proprly, it return exit_ for temlate: def page_Category_Main(request, cat_): #... exit_ = { 'category_name': category['category_name'], #str 'categories_list': categories_list, #list 'action': cat_, #str 'tbl_ttx_col': [x for x in tab_marketability.keys() if x not in ['id', 'brand', 'name', 'price_avg', 'appear_month']], #list 'tbl_data': tab_marketability, #dict 'tbl_data_nov': tab_novelty, #dict 'new_form': new_form, #dict 'enabled': enabled_return, #list 'checked_items': post_return, #list 'period': request.session['period_mth_rus'], #list 'tab_active': tab_active, #str 'tab_list': list(dict_tabs.keys()), #list 'tab_data': dict_tabs #dict } return render(request, template_name="al_category.html", context=exit_) And server begin to handles template al_category.html (I see it in Python Debuger, becouse template use some @register.filter function from views.py). And in unknown point raise this TypeError: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Nb/ Django Version: 3.1.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', … -
Dynamic Model Creation, Migration, and Registration in Django 3.1
I'm working on a project where I've to dynamically create models. So far I've been able to create a model and store its instance in a variable. But when I'm trying to migrate and register it to admin panel, Django is throwing an error. This is the error that pops up when I try to load the admin panel. NoReverseMatch at /admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Exception Location: D:\DynamicModelCreation\environment\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\DynamicModelCreation\environment\Scripts\python.exe Python Version: 3.6.6 Python Path: ['D:\\DynamicModelCreation', 'D:\\DynamicModelCreation\\environment\\Scripts\\python36.zip', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\DLLs', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\lib', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36', 'D:\\DynamicModelCreation\\environment', 'D:\\DynamicModelCreation\\environment\\lib\\site-packages'] Server time: Thu, 11 Feb 2021 01:30:23 +0530 This is the function where I'm trying to migrate and register the model. def createModel(tableName, fields): class Meta: pass setattr(Meta, "app_label", "System") fields['__module__'] = "System.models" fields['Meta'] = Meta model = type(tableName, (models.Model, ), fields) class Admin(admin.ModelAdmin): pass admin.site.register(model, Admin) print(model._meta.fields) return model My aim is to create and migrate the models and register them successfully during the runtime. App name - System Project name - DynamicModelCreation -
Problem with accessing static files when deploying Django API using Google App Engine
I have schema.yml in the static folder in my project and during development everything seems to be working properly however after deployment to the App Engine I get the error Not Found /static/schema.yml. My configuration looks in the way shown below. Do you have any ideas what can be the cause of the problem? settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) STATIC_URL = '/static/' app.yaml: runtime: custom env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi service: mysite-service handlers: - url: /static/ static_dir: static -
How to display data base table by using forms.py in Django
My name is R Kartheek. I'm new to Django. I know how to display database table by using HTML in Django. But, I don't know by using forms.py. Present learning that. Anyone, please help me with how to print the database table by using forms.py in Django. Just like <.objects.all()> how to use this by using Forms.py in Django? models.py: from django.db import models # Create your models here. class Emp_Data(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile = models.BigIntegerField() email = models.EmailField(max_length=50) company = models.CharField(max_length=50) location = models.CharField(max_length=50) salary = models.IntegerField() views.py from django.shortcuts import render from .models import Emp_Data from .forms import Emp_Data_Form from django.http import HttpResponse from django.contrib import messages # Create your views here. def Emp_View(request): if request.method == 'POST': form = Emp_Data_Form(request.POST) if form.is_valid(): first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') mobile = request.POST.get('mobile') email = request.POST.get('email') company = request.POST.get('company') location = request.POST.get('location') salary = request.POST.get('salary') data = Emp_Data(first_name = first_name, last_name = last_name, mobile = mobile, email = email, company = company, salary = salary ) data.save() messages.success(request, f'Data submitted successfully...') form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', context) else: return HttpResponse('Invalid form') else: form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', … -
django paginator is not working but the link is working manually
I have a page that represents the articles based on categories. I am trying to make a pageinator for this page but I see no pageinator in my webpage. However when I enter the link manually it works. i don't know what I'm missing here... #my HTML page <div class="blog-pagination"> <ul class="justify-content-center"> {% if cat_articles.has_previous %} <li><a href="{% url 'website:category' cat_articles.previous_page_number %}"> <i class="icofont-rounded-left" ></i></a></li> {% endif %} <li><a href="#">1</a></li> <li class="#"><a href="#">2</a></li> <li><a href="#">3</a></li> {% if cat_articles.has_next %} <li><a href="{% url 'website:category' cat_articles.next_page_number %}"> <i class="icofont-rounded-right" ></i></a></li> {% endif %} </ul> </div> </div><!-- End blog entries list --> #my view def category(request, slug, page=1): cat = get_object_or_404(Category, slug=slug, status=True) articles_cat = cat.articles.filter(status='Published') paginator_cat = Paginator(articles_cat, 1) cat_articles = paginator_cat.get_page(page) context = { "category": cat_articles } return render(request, 'website/category.html', context) -
Server ERROR: smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server
This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance. I'm trying to send mail through my Gmail Account. I did get an App Password for it and everything. I'm using the newest version of Python. This is the Error I get: Traceback (most recent call last): File "E:\Python_old\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Python_old\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Python_old\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "E:\Python_old\WebshopV4\ecommerce\store\views.py", line 71, in checkout send_mail( File "E:\Python_old\venv\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "E:\Python_old\venv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 67, in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) File "C:\Users\Jeamp\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 755, in starttls raise SMTPNotSupportedError( smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Here is my Email configuration: # Email Settings EMAIL_HOST = 'smtp.gmail.com' Email_PORT = '587' EMAIL_HOST_USER = 'jeampo.jeampo@gmail.com' EMAIL_HOST_PASSWORD = 'MYPASSWORD' EMAIL_USE_TLS = True And here is my Django sendmail() function: # send an email send_mail( 'message from ' + message_name, # subject message_to_send, # message message_email, # from email ['myemail@outlook.de'], # To Email ) -
how to update value in database in django?
code It is Screenshot of my code for delete and update in django database. but here if I click on delete button it correctly deletes the targited value but if i press update button of any record it only update and show the value of last record. here I'm attaching the output screenshots main_output here if i print on any of update button it will show and update only the most recently added record modal -
Why does my heroku bash instance show my app folder to be empty?
I've deployed an app to heroku and ran heroku run bash -a {app_name} Once it successfully opens a bash console and I run ls I see nothing. If I run pwd it says I'm in the /app directory where my project files should be. I am also unable to run any commands using my manage.py file e.g. heroku run python manage.py migrate results in a python: can't open file 'manage.py': [Errno 2] No such file or directory -
'DatabaseOperations' object has no attribute 'geo_db_type'
I'm using 2 databases in my project. Sqlite3 for most things and then Postgis to create a geospatial database for my 'store locator' app. What I've done so far: 1] My postgres DB has been setup with the postgis extension 2] I have added the database in my settings.py, and also added'django.contrib.gis' under INSTALLED_APPS. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'geospatial': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geospatial', 'USER': '*****', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432' } } 3] I came across 'Database Routers' to make sure that my app was using the postgis db and not the default sqlite3 one and gave it a go but to no avail. facility/routers.py: from django.conf import settings class dbRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'facility' or obj2._meta.app_label == 'facility': return True return None def allow_syncdb(self, db, model): if db == 'geospatial': return model._meta.app_label == 'facility' elif model._meta.app_label == 'facility': return False return None mainapp/settings.py: DATABASE_ROUTERS = ['facility.routers.dbRouter'] Can someone please tell me what I'm doing wrong? Any and all help is … -
Staticfiles not copied to STATIC root (0 static files copied)
I am trying to get my app on heroku have the relevant settings as follows STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) if not DEBUG: AWS_ACCESS_KEY_ID = get_environment_variable("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = get_environment_variable("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "the-bucke-name" AWS_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_DEFAULT_ACL = "public-read" AWS_LOCATION = "static" STATIC_URL = f"https://{AWS_CUSTOM_DOMAIN}/{AWS_LOCATION}/" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" else: STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") import django_heroku django_heroku.settings(locals(), staticfiles=False) When i run docker-compose run --rm web-app python manage.py collectstatic --noinput I get 0 static files copied to '/code/staticfiles' locally and on heroku 0 static files copied I cant seem to figure out which setting I am missing. The staticfiles folder is empty so not a case of unmodified files or there being no chnages to the css. -
Use video part as thumbnail
In you when upload videos with thumbnail on feed show that. But when no upload video with thumbnail YouTube randomly choose thumbnail from video part how to do this use python and django. -
How to prevent deletion of instance from Inline in Django Admin correctly?
I have two models look like: class Client(models.Model): # some client fields class User(models.Model): # some user fields owned_by = models.ForeignKey(Client, on_delete=models.CASCADE) is_main_user = models.BooleanField() Also I made admin part. StackedInline for User and ModelAdmin for Client which includes UserStackedInline. My goal is prevent deleting User which has is_main_user==True. I've made signal handler for pre_delete from User and raise ValidationError("You cannot delete main user") when condition is true. But when I try to delete user in admin, I was getting 500 error. I've expected to get readable message in admin. How I can correctly handle ValidationError on instance deletion in StackedInline? Or am I incorrectly preventing a specific instance from being deleted? -
NoReverseMatch at / Reverse for 'blog' not found. 'blog' is not a valid view function or pattern name
Not sure why I'm getting this error. It also says: "Error during template rendering In template /Users/aydanaslanova/Desktop/Travel_Project/todo/templates/todo/base.html, error at line 0" I don't have a blog.html or a blog url or a blog view? I only have one app (todo), that'all. For reference, I tried to add another app earlier called "blog" but later deleted it. Attaching settings.py, urls.py and base.html where I am getting the error. Similar questions were not helpful, unfortunately. -
Django model.FilePathField returns paths that have additional 'static' directories
I am new to Django, writing my first project (portfolio website) and stumbled upon such problem: So i a nutshell: model.FilePathModel when called in my .html site as {% static project.image %} returns: /static/projects/static/img/project1.png while it should return: /static/projects/img/project1.pn My question is: Why does addtional /static/ appears when there is none in my file sturcture? I am not sure if something with my understanding of Django static file managment is wrong, or of models.FilePathField for that matter. dir sturcture: Link to the snapshot procejts/models.py file : class Project(models.Model): allow_folders=True def __str__(self): return self.title title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length = 20) image = models.FilePathField(path='projects/static/projects/img' ) settings.py(static settings part) STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR /'projects/static/', ] -
line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon'
I am creating a django3 Ecommerce website and I've come through the following error when a guest user tries to enter a coupon : Traceback (most recent call last): File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/miryamelliye/development/comdjanco/ecommerce/store/views.py", line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon' views.py def get_coupon(request, code): try: coupon = Coupon.objects.get(code = code) return coupon except ObjectDoesNotExist: messages.info(request, 'This coupon does not exist') return redirect('checkout') def add_coupon(request): data = cartData(request) if request.method == "POST": form = CouponForm(request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = data['order'] order.coupon = get_coupon(request, code) order.save() messages.success(request, 'Successfully added coupon!') return redirect('checkout') except ObjectDoesNotExist: messages.info(request, 'You do not have an active order') return redirect('checkout') return redirect('checkout') my utils.py def cookieCart(request): #Create empty cart for now for non-logged in user try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('CART:', cart) items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'id':product.id, 'product':{'id':product.id,'name':product.name, 'price':product.price, 'imageURL':product.imageURL}, 'quantity':cart[i]['quantity'], … -
django 1.8.5 + Python 2.7 to Django 3.0 + Python 3.9
I have a massive Django 1.8.5 and Python 2.7.6 project. I need to upgrade it to Django 3.0, Python 3.9. Any recommendations on how to proceed ? Thanks.