Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Reverse Error upon attempting to delete account
I am unsure of what went wrong but I cannot delete my own account. I receive the following error: Reverse for 'delete_account' with keyword arguments '{'user_id': 'testuser1'}' not found. 1 pattern(s) tried: ['account/delete/(?P[^/]+)$'] NoReverseMatch at /account/2/ Views.py def delete_user(request, username): if request.method == 'DELETE': try: user = request.user user.delete() context['msg'] = 'Bye Bye' except Exception as e: context['msg'] = 'Something went wrong!' else: context['msg'] = 'Request method should be "DELETE"!' return render(request, 'HomeFeed/snippets/home.html', context=context) urls.py from account.views import ( delete_user, ) path('delete/<username>', delete_user, name='delete_account'), account.html <a class="mt-4 btn btn-danger deleteaccount" onclick="return confirm('Are you sure you want to delete your account')" href="{% url 'account:delete_account' user_id=request.user.username %}">Delete Account</a> traceback File "/lib/python3.8/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/lib/python3.8/site-packages/django/template/defaulttags.py", line 443, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/lib/python3.8/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/lib/python3.8/site-packages/django/urls/resolvers.py", line 673, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'delete_account' with keyword arguments '{'user_id': 'testuser1'}' not found. 1 pattern(s) tried: ['account/delete/(?P<username>[^/]+)$'] -
Django + Angular
i am new to the world of web development and i have a very good foundation on django for backend operations. i am also learning angular for front-end applications. so far i am quite happy writing in django for backend, but i dont like to work with the django templates. My question is, is there any way to integrate angular as the front-end portion in a django environment, keeping the django as the backend?? also while we at it, is there any good designing (UI design) courses available and where (free or paid)? -
WSGI Mod with Django and Pyenv on CentOS "no module named encodings"
I have an issue with CentOS 8 running a Django 3.0 application using Apache 2 as an httpd service. When trying to serve the application I get a dump of the environment as follows in the error_log: Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = '/srv/test/venv/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/srv/test/venv/bin/python' sys.base_prefix = '/root/.pyenv/versions/3.9.0' sys.base_exec_prefix = '/root/.pyenv/versions/3.9.0' sys.platlibdir = 'lib' sys.executable = '/srv/test/venv/bin/python' sys.prefix = '/root/.pyenv/versions/3.9.0' sys.exec_prefix = '/root/.pyenv/versions/3.9.0' sys.path = [ '/root/.pyenv/versions/3.9.0/lib/python39.zip', '/root/.pyenv/versions/3.9.0/lib/python3.9', '/root/.pyenv/versions/3.9.0/lib/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f6034d44880 (most recent call first): <no Python frame> I have the documentation and read a bit on this and there isn't a valid solution. This is the process by which I'm setting this up. I pull down the repo into /srv/test Go into that directory Create a virtual environment with virtualenv using ~/.pyenv 3.9 that I previously installed. Activate into virtual … -
Update db after successful payment - DRF
In my project I use Django as my backend, vue as my frontend and stripe as my payment processing software. The users of my program will be able to buy in game currency (points). So whenever I recieve the checkout.session.completed webhook event I essentially want to change the users' points accordingly in the db. I thought of making an internal api request, through django, that updates the users' points but I quickly found out that it would be bad practice and should only be done when testing. I was just wondering how you would tackle this problem and what you think would be the best practice in this situation. If you need any more information, just ask. Thanks in advance. -
How to make the outlinked image (included in rich text) retrieved from django template languange responsive
The out linked image which is retrieved from the rich text (article.body) stored in database can't be responsive, its size is even over the border of the cotainer, how can I get it responsive? <div class="container-xl p-3 my-3 border"> {{article.body|safe|linebreaks}} </div> The content of article.body is like the below: <h3>1 - Say the truth</h3> <p> <img alt="Check" src="https://media-exp1.licdn.com/dms/image/C4D12AQFGX-qEDVN8KQ/article-inline_image-shrink_1500_2232/0/1608331886504?e=1614816000&amp;v=beta&amp;t=FrftEfk4TS7slp1blmqoPiZbdpup_Un54SQ3WLacKWo" /> </p> <p>Everything you say Records will remain online and on networks&#39; archives. So it&#39;s h... </p> Thanks -
python: can't open file 'manage.py': [Errno 2] No such file or directory when compose docker
I run two different Apps in containers. Django App Flask App Django ran just well. I configured my Flask App as follow: This Is a docker-compose.yml version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8001:5000 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: main MYSQL_USER: shedd MYSQL_PASSWORD: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33067:3306 This also is my Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python main.py Problem: When I run docker-compose up the following error occurs backend_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory I don't know why it tries to open manage.py file since it is Flask and not Django App. I need your help. Thanks in Advance. -
Name error: why can't i query the number of likes and the like button in the home page through the home screen view
These are the views for my like button and home page. I am unsure of why i cannot query the number of likes and the like button in the home page, which caused this name error. Any help is greatly appreciated I'm shown that the problem lies here : blog_post = get_object_or_404(BlogPost, slug=slug) but how can i change it to define the slug, ive already tried to have more arguments for slug but it didnt work views.py def LikeView(request, slug): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect('HomeFeed:detail', slug=slug) def home_feed_view(request, **kwargs): context = {} blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True) blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['blog_posts'] = blog_posts context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, "HomeFeed/snippets/home.html", context) html {% for post in blog_posts %} <td class="table-primary"><form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST">{% csrf_token %} <button type="submit" name="blog_post_slug" value="{{post.slug}}" class='btn btn-primary btn-sm'>Like</button> {{ total_likes }} Likes</form></td> {% endfor %} TraceBack: NameError at /HomeFeed/ name 'slug' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/HomeFeed/ … -
Apache2 WebServer with django, creating problems
I have a problem with creating a web server with apache 2 and django. I just want to set up the apache server with one site for now however in the future I may want one or two more. I am using raspberry pi OS and python3 and django 3.1 and apache 2. I am following a tutorial however there seems to be a problem with mine when running the config test and I can't work out what is wrong. I am very very new to apache and django. Here is the error message AH00526: Syntax error on line 14 of /etc/apache2/sites-enabled/djangoproject.conf: Alias must have two arguments when used globally Action 'configtest' failed. The Apache error log may have more information. and here is the file it is referencing: ServerAdmin admin@djangoproject.localhost ServerName djangoproject.localhost ServerAlias www.djangoproject.localhost DocumentRoot /home/pi/webServer ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/pi/webServer/static <Directory /home/pi/webServer/static> Require all granted </Directory> Alias /static/home/pi/webServer/media <Directory /home/pi/webServer/media> Require all granted </Directory> <Directory /home/pi/webServer/CCC> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_project python-path=/home/pi/webServer python-home=/home/pi/webServer$ WSGIProcessGroup webServer WSGIScriptAlias / /home/pi/webServer/CCC/wsgi.py </VirtualHost> -
Radio Button that show saved selected option, with Python Bootstrap
I'm pretty new with Python Bootstrap, and I created a Python Bootstrap Form with Radio Button options for a specific field entrepot.etage I am wondering what is the best way to show which option is checked, on saved database record ? Like if "Option 2" is saved on my record, I want it checked when you edit or view with Radio Button. There is my HTML file (Just the important part) <form action="/entrepots/edit_entrepot" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-lg-12"> <div class="form-group"> <div class="col-sm-4"> <label class="control-label">Étage : </label> <div class="form-group"> <label class="radio-etage"> <input type="radio" name="etage" value="1">1 </label> <label class="radio-etage"> <input type="radio" name="etage" value="2">2 </label> </div> </div> <div class="form-group"> <input type="hidden" value="{{ entrepot.id }}" name="id"> <input type="submit" name="submit" class="btn btn-block btn-success" value="Modifier Entrepots"> </div> </div> </div> </form> -
Saving a QR Code in django python as base64 for to_artistic method
I would like to save my QR Code from the to_artistic method. For my other qr codes I have been doing: buffer = io.BytesIO() qr_img.save(buffer, format="PNG") qr_code = "data:image/png;base64,"+base64.b64encode(buffer.getvalue()).decode("utf-8") How can I do this for qr.to_artistic? Documentation: https://segno.readthedocs.io/en/latest/web-development.html Thanks! -
Displaying user uploaded image in Python Django
I am creating a website using the Django python framework and am currently stuck on a problem. I am using function views to display a page called myaccount, and on 'myaccount' i would like all user details to be displayed using context objects, for this page it is 'user'. I also have another model called Profile, which holds the profile picture and date of birth of the user. However when i attempt to display the image which has been uploaded during the account creation into the media folder named '/media/%y/%m/%d/imagename.filextension' i receive an error saying "The 'profilepicture' attribute has no file associated with it." I have been searching vastly for fixes to this issue and have so far found no result which has worked, i have tried to create a property function which gets the url from the image called 'get_absolute_url' by doing user.profile.profilepicture.get_absolute_url but it fails to work and displays the same error. I was wondering if anyone could point me in the direction of a fix for this or a solution. The code to display the image, views.py and urls.py is down below views.py @login_required def myaccount(request): return render(request, 'account/myaccount.html', {'section': 'myaccount'}) urls.py path('', views.myaccount, name='myaccount'), myaccount.html <img … -
How to call post_save signal after adding object to ManyToMany field on another model
I have two models, Post and Comment. Now I have a custom function using post_save signal on a comment object. However, since I add the object to the many to many field after saving it, I cannot get the attributes of the Parent post object. So I have: comment.save() post.comments.add(comment) Now I have a function: @receiver(post_save, sender=Comment) def update_comment_count(sender, instance, **kwargs): cache.set("post_comment_count_{}".format(instance.post.id), instance.post.comments.all().count()) However, this will not work since the post object hasn't added the comment object yet, is there any way to fix this? -
How to make dynamic data in Javascript from Django views
I have js like this, I want make that data is dynamic from database. I want to pass that value from views. How to do that? data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database' }, { value: 234, name: 'UIX' }, { value: 135, name: 'Manajemen' },] I try this code : cursor.execute('SELECT k.nama_ktg as name, COUNT(m.nim) as value FROM mahasiswa_mhs_si m, mata_kuliah_kategori_utama u, mata_kuliah_kategori k WHERE k.kode_ktgu_id = u.id AND m.kode_ktg_id = k.id GROUP BY k.id') ktg_mhs = cursor.fetchall() #JSON CHART result = [] chart_ktg =[ { 'value' : ktg_mhsi[1], 'name' : ktg_mhsi[0] } for ktg_mhsi in ktg_mhs ] data = json.dumps(chart_ktg) And the result is this : [{"value": 51, "name": "Coding"}, {"value": 27, "name": "Database"}, {"value": 223, "name": "UI/UX"}, {"value": 34, "name": "Manajemen"}, {"value": 7, "name": "Dasar Sistem Informasi"}, {"value": 64, "name": "Bisnis"}, {"value": 18, "name": "Kesehatan"}, {"value": 235, "name": "Lain-lain"}] -
Why delete method not allowed in django?
I have added delete method in my view but I keep getting error as below "detail": "Method \"DELETE\" not allowed." Not sure whats wrong? Can anyone help? defining delete method as this def delete(self, request): -
Django duplicate column name: Username
I'm getting the following error when I try to migrate: django.db.utils.OperationalError: duplicate column name: Username howerever I don't even have a username field -
django controlcenter url name
while using django-controlcenter package, I am trying to set a url in a html template to access a dashboard. In my urlpattersn I have: path('admin/dashboard/', controlcenter.urls, name='dashboard'), In my settings, I have a set a dashboard: CONTROLCENTER_DASHBOARDS = ( ('admindash', 'myapp.dashboards.AdminDashboard'), ) So for a url that normally resolves as /admin/dashboard/admindash , what the template url should be? django.urls include would not work with the package and the issue would be to register a proper namespace. I directly tried {% url 'dashboard:admindash' %} but it returned a NoReverseMatch error. -
Django Fixing UnicodeDecode Error Decoding
I am following a Django CRUD tutorial and am getting this error when I try and load my url. The rest of my views all work except this one, and I've never seen this error before. I googled similar issues and found a few proposed solutions (posted below) but nothing has worked on my end. Any ideas how to fix this? I have already tried adding from __future__ import unicode_literals and def __str__(self): return "(%s)" % self.name into my views.py file with no luck 'utf-8' codec can't decode byte 0xd7 in position 2046: invalid continuation byte html {% extends 'base.html' %} {% load static %} {% block title %}Django Ajax CRUD{% endblock %} {% block content %} <div class="container"> <h1>Django Ajax CRUD</h1> <div class="row"> <div class="col-md-4 "> <h3>ADD USER</h3> <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required> </div> <button class="btn btn-primary form-control" type="submit">SUBMIT</button> </form> </div> <div class="col-md-8"> <h3>USERS</h3> <table id="userTable" class="table table-striped"> <tr> <th>Name</th> <th>Address</th> <th colspan="3">Age</th> </tr> {% if users %} {% for user in users %} <tr id="user-{{user.id}}"> <td class="userName userData" name="name">{{user.name}}</td> <td class="userAddress userData" … -
Running Django with gunicorn (on a K8s node created from a Docker Image) produces poor performance and CORS errors
I'm Deploying Django via gunicorn onto a K8s node from a Docker Image. For a Dockerfile using CMD python manage.py runserver 0.0.0.0:8000, the front end works fine. For a Dockerfile using CMD gunicorn ..., frontend either loads SUPER-slow or fails: Here's the Dockerfile: FROM python:3.9-buster LABEL maintainer="hq@deepspaceprogram.com" RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y gcc && \ apt-get install -y git && \ apt-get install -y libcurl4 && \ apt-get install -y libpq-dev && \ apt-get install -y libssl-dev && \ apt-get install -y python3-dev && \ apt-get install -y librtmp-dev && \ apt-get install -y libcurl4-gnutls-dev && \ apt-get install -y libcurl4-openssl-dev && \ apt-get install -y postgresql-9.3 && \ apt-get install -y python-psycopg2 ENV PROJECT_ROOT /app WORKDIR /app # install python packages with poetry COPY pyproject.toml . RUN pip3 install poetry && \ poetry config virtualenvs.create false && \ poetry install --no-dev COPY accounts accounts COPY analytics analytics COPY commerce commerce COPY documents documents COPY leafsheets leafsheets COPY leafsheets_django leafsheets_django COPY marketing marketing COPY static static COPY manage.py . # This should be an empty file if building for staging/production # Else (image for local dev) it should contain the complete .env … -
I want to create a database record with a click of a button, when im clicking a button, nothing happens. Could anyone tell me what am I doing wrong?
I want to create a database record with a click of a button (registered user answers to a question selected from 2 possible answers represented by two buttons), when im clicking a button, nothing happens. Could anyone tell me what am I doing wrong? html page <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <button type="submit" name="butt_ans" value="{{ q.answer1.value }}">{{ q.answer1 }}</button> <button type="submit" name="butt_ans" value="{{ q.answer2.value }}">{{ q.answer2 }}</button> {% endfor %} </form> views.py @login_required def select_interests(request): questions_data = InterestQuestion.objects.all() if request.method == 'POST': questionnaire_form = InterestSelectionForm(request.POST) if questionnaire_form.is_valid(): test = questionnaire_form.cleaned_data.get("value") else: questionnaire_form = InterestSelectionForm() return render(request, 'quiz/quiz_form.html', locals()) forms.py class InterestSelectionForm(forms.ModelForm): class Meta: model = UserInterest fields = ('selectedInterest',) models.py class UserInterest(models.Model): q_id = models.ForeignKey(InterestQuestion, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) selectedInterest = models.CharField(max_length=64) -
tuple indices must be integers or slices, not tuple
I'll try to make a JSON for i in ktg_mhs: chart_ktg ={ 'value' : ktg_mhs[i][1], 'name' : ktg_mhs[i][0] } result.append(chart_ktg) data = json.dumps(chart_ktg) but, I get an error at this 'value' : ktg_mhs[i][1], 'name' : ktg_mhs[i][0] How to solve it and why? -
inputs are not being stored in Mysql database
i am currently having an issue with my program my some of my input are not being saved in the MySQL database - any help will be appreciated this creates a custom user which are the employee, admin and senior employee - this is a different model so another table class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) this the model for one of my usertypes class senioremployee(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() Wage = models.TextField() Passportnumber = models.TextField() passportexpirydate = models.DateField() gender = models.CharField(max_length=255) profile_pic = models.FileField() kinname = models.TextField() kinrelation = models.TextField() kinaddress = models.TextField() kinphonenumber = models.TextField() kinemail = models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects = models.Manager() this function add user's data to the table @receiver(post_save,sender = CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type==1: admin.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") if instance.user_type==2: senioremployee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") if instance.user_type==3: employee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") this is the function that is meant to save the inputs into the senioremployee's table and email,password , firstname, lastname,username into the custom user's table but currently it only stores email,password , firstname, lastname,username into the custom user's table and just ignores the other user … -
Django jquery ajax comment reply create multiple values
I am in pazzle to create a comment reply activities using django jquery and ajax. It's create multiple values to comment or reply on blog. How can I solve this problems? Thanks in advance. models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(max_length=1000) reply = models.ForeignKey('Comment', on_delete=models.CASCADE, related_name='replies', null=True, blank=True, default=None) post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE) objects = models.Manager() class Meta: ordering = ['-timestamp'] def __str__(self): return self.user.username comment_section.html {% extends "base.html" %} {% block content %} <div class="container-fluid mt-2"> <div class="form-group row"> <form class="comment-form" method="post" action="."> {% csrf_token %} <div class="form-group"> <textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea> </div> <button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button> </form> </div> </div> {% if not post.comments.all %} <small>No comments to display</small> {% endif %} {% for comment in comments %} <blockquote class="blockquote"> <img style="float:left; clear: left;" class="rounded-circle article-img" height="10" width="10" src="#"><a href="#" style="text-decoration: none; color: black;"><h5>{{ comment.user.username|capfirst }}</h5></a> <p style="font-size: 8px;">{{ comment.timestamp }}</p> <p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p> <a type="button" name="button" class="reply-btn ml-4"><i class="fas fa-reply fa-sm"></i></a>&emsp; {% if request.user == comment.user %} <a href="#"><i class="fas fa-trash fa-sm" style="color: brown;"></i></a></td> {% endif %} </blockquote> {{ comment.replies.count }} <div class="replied-comments col-md-5" style="display: none;"> {% for reply in comment.replies.all %} … -
Mock a test with a external api rest in Django Rest Framework
Context I am developing an API Rest with Django Rest Framework, and some of my endpoints consume an external API Rest to create a model instance, the code works but right now I am trying to test my code but I have very struggled with that. I am a little beginner developing tests and maybe the question is very obvious but, I tried so many things, with the below links but I couldn't achieve it. Mocking external API for testing with Python How do I mock a third party library inside a Django Rest Framework endpoint while testing? https://realpython.com/testing-third-party-apis-with-mocks/ Codes This is my view from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from app.lnd_client import new_address from app.models import Wallet from api.serializers import WalletSerializer class WalletViewSet(viewsets.ModelViewSet): queryset = Wallet.objects.all() serializer_class = WalletSerializer lookup_field = "address" @action(methods=["post"], detail=False) def new_address(self, request): response = new_address() if "error" in response.keys(): return Response( data={"error": response["error"]}, status=response["status_code"] ) else: return Response(response) def create(self, request, *args, **kwargs): response = self.new_address(self) if response.status_code >= 400: return response serializer = self.get_serializer(data=response.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) This is my client with the call to the external api … -
Is there any way to organize filelds in django models?
I have many tables in my django models, each responsible for a different form in my template. I wrote some code to convert this fields directly into tempalte using python and JavaScript. Next I've been trying to add sections into template, which means that in my template each section has own title and own fields. After a few tries my code looked like an example: #before class forms_n(Models.Model): field1 = models.IntegerField() field2 = models.ForeignKey(ForeignModel, on_delete=models.CASCADE,null=False,blank=False) field3 = models.IntegerField() field4 = models.IntegerField() #after class form_n_cfg: @section_decorator(section=0,title="This is seciton 0") class form_n_0(models.Model): field1 = models.IntegerField() field2 = models.ForeignKey(ForeignModel, on_delete=models.CASCADE,null=False,blank=False) class Meta: abstract = True @section_decorator(section=1,title="This is seciton 1") class form_n_1(models.Model): field3 = models.IntegerField() field4 = models.IntegerField() class Meta: abstract = True class form_n(forms_n_cfg.form_n_0,forms_n_cfg,form_n_1): pass #utils.py def section_decorator(**kwargs): def set_attrs(obj): fields = obj._meta.fields for i in fields: for key,value in kwargs.items(): setattr(getattr(obj,i.name),key,value) return obj return set_attrs Everything worked fine, in time I realized that Foreignkey unlike other fields doesn't have any values from my decorator. I think the problem is because i added attrs to for parent class, not subclass form_n which i use (just why other fields had values from decorator). I noticed that just classes inner form_n_cfg has @section_decorator attributes for … -
Django variable inside static tag?
This is part of index.html: {% for listing in active_listings %} <tr> <td>{{ listing.title }}</td> <td>{{ listing.description }}</td> <td>{{ listing.bid }}$</td> {% if listing.image %} <td>{{ listing.image }}</td> <td><img src="{% static 'auctions/'|add:listing.image %}" alt="photo"></td> {% else %} <td>No photo.</td> {% endif %} </tr> {% endfor %} This is the corresponding views.py: def index(request): return render(request, "auctions/index.html", { "active_listings": Listing.objects.filter(active=True), }) And that is my Listing Model: class Listing(models.Model): CATEGORIES = [ ('BO', 'Books'), ('TO', 'Toys'), ('EL', 'Electronics'), ('FA', 'Fashion'), ('HO', 'Home'), ] title = models.CharField(max_length=64) description = models.TextField(max_length=256) bid = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) category = models.CharField(max_length=2, choices=CATEGORIES, null=True, blank=True) active = models.BooleanField(default=True) Why can't I add the variable listing.image in the html??? It gives me: "GET /static/ HTTP/1.1" 404 1634