Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get absolute url of a Cloudinary Obejct
I am using Cloudinary in my django app. But, I get an output like this: { "post": "Test", "image_field": "image/upload/v1613308988/cizqjtpk59j5orvl2l5e.jpg" } My MODEL: class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="image_field", default=None) image_field = CloudinaryField('image') def __str__(self): return self.post.title My SERIALIZER: class ImageSerializer(serializers.ModelSerializer): post = serializers.StringRelatedField() class Meta: model = Image fields = ["post", "image_field"] MY VIEWS: class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = ['post', 'image_type'] def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return [permissions.IsAuthenticatedOrReadOnly()] return [permissions.IsAdminUser()] Thanks for any help. :) -
TypeError at /products/ object of type 'ModelBase' has no len()
So I'm trying to use pagination, When I visit the page I get TypeError at /products/ object of type 'ModelBase' has no len(). The traceback shows this line has the error books = haha.page(page) views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book, 2) page = request.GET.get('page') if page is None: page = 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha.page(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name }}</h3></a> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if not user.is_authenticated %} <p>Please login</p> {% else %} {% if book.id in cart %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} … -
How can handle UpdateView on same page
am new to django , i want to make updateview shows the edit form in same page rather than opening an new page class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'slug', 'content', 'category', 'post_image'] template_name = 'update.html' def get_context_data(self, **kwargs): data = super(PostUpdateView, self).get_context_data(**kwargs) data['update_form'] = data.get('form') return data def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False -
accepting and saving the data entered into input field (email) using django
I'm a newbie currently learning how to work with django. I rendered a static homepage with an email input field for a project. The field is supposed to get inputs from folks that would want to be on my waitlist for the project when it's ready. enter image description here I'm confused about how to capture this data and store it in my database and now i'm stuck. I tried creating an app within my project called Waitlist with a model class(Waitlist). This class has just one attribute "email".enter image description here. would really appreciate some kind assistance. thanks -
why my wsgi module is not found and why the process has failed
I'm not sure why my wsgi module is not found and why the process has failed despite following the steps. Can someone advise which file is causing the problem? Please let me know if more code is required. This is the tutorial i am following: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 (myprojectenv):~# 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 9min ago Main PID: 12810 (code=exited, status=3) Feb 14 13:44:02 ubuntu-s-1vcpu-1gb-nyc1-01 gunicorn[12810]: return _bootstrap._gcd_import(name[level:], package, level) gunicorn[12810]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import gunicorn[12810]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load gunicorn[12810]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked gunicorn[12810]: ModuleNotFoundError: No module named 'hello.wsgi' gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12829] [INFO] Worker exiting (pid: 12829) gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12810] [INFO] Shutting down: Master gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12810] [INFO] Reason: Worker failed to boot. systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED systemd[1]: gunicorn.service: Failed with result 'exit-code'. My gunicorn service code: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/myprojectdir ExecStart=/root/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ hello.wsgi:application [Install] WantedBy=multi-user.target -
How to create a URL that links directly to open a Modal with data
When i click td(title) on the table, the data is retrieved via api and displayed in a pop-up modal window using ajax. is there any chance to create url so that I can get the data I want by launching pop-up right away without click on the table page? What i want to is When you click on an url, redirect to the page(the table page ) and the corresponding data modal is opened immediately. plz help me up my ajax and jquery to open modal and get data $(".title_txt").click(function (e) { e.preventDefault(); var currentNum = $(this).closest('tr').prevAll().length + 1; var td = get_td(currentNum); get_consul(td,currentNum); }) function get_consul(td,currentNum) { var pk = td.eq(8).text(); var lastNum = $("#orders__table tbody tr").length; if (lastNum == currentNum) { $(".next_consul").hide(); $(".prev_consul").show(); } else if (currentNum == 1){ $(".prev_consul").hide(); $(".next_consul").show(); } else{ $(".next_consul").show(); $(".prev_consul").show(); } $.ajax({ type: 'GET', url: "{% url 'get_consul' %}", data: {"pk": pk}, dataType: "json", success: function (response) { /* modal value changed */ var student_url = "{% url 'student_detail' 1 2 %}" $(".title_con").text(response[0].fields.title) $(".con_con").html(response[0].fields.content) $(".con_txt_created_by").text(response[0].fields.created_by) $(".con_txt_created_at").text(response[0].fields.created_at) $(".con_txt_classification").text(response[0].fields.classification) $(".con_txt_status").text(response[0].fields.status) $(".con_txt_status").removeClass('imp_01 imp_02 imp_03') $(".con_txt_status").addClass(response[0].fields.status_css) $(".con_txt_name").text(response[0].fields.created_to) $(".con_txt_name").attr("href", student_url .replace('2',response[0].fields.student_pk) .replace('1',response[0].fields.school_year)) $(".con_txt_school_year").text(response[0].fields.get_school_year_display) $(".con_txt_type").text(response[0].fields.get_type_display) $(".con_txt_admission_date").text(response[0].fields.admission_date) $(".con_txt_picture").attr("src", '/media/' + response[0].fields.picture) $(".currentNum").text(currentNum) /* list css changed to read */ td.removeClass('on') … -
How to connect postgresql to django
hello everyone hense i connect my separeted django settings to databse it start making problem, i make migration to new postgress and everything looks good succesfully connected and create new tables on postgress but cannt start service what should be a problem? Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: self.stop() Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: time.sleep(0.1) Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: self.reap_workers() Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Feb 14 13:27:45 ip-88-99-22-33 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Feb 14 13:27:45 ip-88-99-22-33 systemd[1]: gunicorn.service: Failed with result 'exit-code'. but when i run manage.py runserver it works base.py base settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } -
Per-record classifying dates by another table's names for those date ranges
Bit of a long-winded title, but essentially I've got Models for projects, with various foreign key sub-models for aspects of it. One related table is a Model where specifically named Date periods are defined, ie. a start and end date are provided and that date is then named by the user, and linked to a set project. It's easiest to think of it as maybe quarters based off that specific project's start date, but it's not always strictly quarters so I can't use conventional 'built-in' date tools. The user has to be able to define assymetrical reporting periods. Every project also has an Events model linked to it for specific occasions/happenings on the project, each with a date that I then need to stratify into these Project_Periods. Since it falls in a range of dates I can't just call up the usual foreign-key relations. The absolute easiest would be just to force the user to select a Project_Period for each Project_Event they add - but there's a lot of events and I want it to be set automatically without a user being able to mismatch it. I've thought of saving a date/calendar table for every project once the Project_Period is … -
Url in django template contains domain
Trying to insert {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} in an email as a link, but the result is something as http://domain//domain.localhost:8000/... which is an invalid link. When only outputting the {% url ... %} block, it begins with //domain.localhost:8000/reset..., which also occurs when trying with different url endpoints. -
TemplateSyntaxError at / 'xxx' is not a registered tag library. Must be one of:
... admin_list, admin_modify, admin_urls, cache, i18n, l10n, log, static, tz I have problems with creating a custom tag. I followed the instructions on the official Django documentation. I also copied the code but still get this error. The file it contains the tag is xxx.py that is in the templatetags dir. Is in app's root directory: app/ migrations static template templatetags __init.py__ admin.py apps.py models.py ....etc The tag in xxx.py: from django import template import datetime register = template.Library() @register.simple_tag def current_time(format_string): return datetime.datetime.now().strftime(format_string) The code in template index.html {% load xxx %} {% current_time "%d/%m/%Y %H:%M:%S %p" %} The traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Python Version: 3.9.0 Installed Applications: ['auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] Template error: In template C:\Users\paren\OneDrive\Documenti\Programmazione\copia progetti corso harvard\CS50\project2\commerce\commerce\auctions\templates\auctions\index.html, error at line 1 'xxx' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 : {% load xxx %} 2 : 3 : 4 : {% block body %} 5 : {% if message %} 6 : <div class="alert">{{message}}</div> 7 : {% endif %} 8 : <div class="main"> 9 … -
Deploying flask app as url in django site
I am using Apache2 I have my main app (django) in /opt/site and a docs app (flask) in /opt/docs I use a shared virtualenv in /opt/env I tried the following WSGIScriptAlias /docs/ /opt/docs/docs.wsgi WSGIScriptAlias / /opt/site/site/wsgi.py WSGIDaemonProcess my-wsgi user=www-data group=www-data python-path=/opt/env/lib/python3.8/site-packages:/opt/site:/opt/docs WSGIProcessGroup my-wsgi WSGIScriptReloading On I want site.com/docs/. I do not want docs.site.com. Unsurprisingly, the above does not work in routing /docs/ to my flask app. How do I do that? How to Use Django with Apache and mod_wsgi is not much help in this instance. Merging docs into the site codebase is not an option currently. Note: I know that my usage of WSGIDaemonProcess may also be outdated and can be replaced with WSGIPythonHome and WSGIPythonPath -
Doing a filter of Python string list against a Django model JsonField
I have the following Django JSONField data structure: searchtermlist = {'terms': ['test', 'cache', 'hello', 'as'], 'subscribed': ['product', 'test']} Given a searh string as such: searchterm = 'hello test' What I am doing now to match if JsonField subscribed field has a matching string to searchterm is: for user in CustomUser.objects.all() if user.searchtermlist and any(s in (searchterm).lower() for s in user.searchtermlist['subscribed']): # Has a match proceed pass My fear is that when the number of users gets large, I can't afford to be doing the objects.all() routine. Except that shouldn't be a problem? My question; is there any more efficient way to achieve the above using tools like Django QuerySet filter? -
ModuleNotFoundError: No module named 'members.urls'
I tried to start a app so that I can create a Login for my blog but I came by this error. So I thought to post a question in stack over flow. I hope yu can take some time to answer my question. This is the trace back error, Traceback (most recent call last): File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\simpleblog\virt\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\simpleblog\virt\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\simpleblog\virt\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\simpleblog\virt\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, … -
Get response in Django testing?
I have a problem with getting response in django testing this is the problem appear in terminal self.assertEquals(self.response.status_code, 200) AttributeError: 'StoreCreateTest' object has no attribute 'response' This is the command py manage.py test This is my def def test_store_create_view_status_code(self): self.assertEquals(self.response.status_code, 200) and this is my import from django.test import TestCase from configuration.models import Stores please help me getting this. -
MultiValueDictKeyError at /products/ 'page'
So I'm trying to use pagination, When I visit the page I get MultiValueDictKeyError at /products/ 'page', and when I go to localhost:8000/thatpage/?page=1 then I get TypeError at /products/ 'Paginator' object is not callable. This error occurs when i visit the page and i don't know what i'm doing wrong, Any help would be great. views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book, 2) page = request.GET['page'] fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name }}</h3></a> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if not user.is_authenticated %} <p>Please login</p> {% … -
Django/channels chat api calls interfering with other backend api calls
For my application, I have set up a real-time chat messaging system implemented using django-channels. As per their official tutorial, I have my ASGI deployment server listening on localhost:8000 with a Websocket URL defined as follows: ws://127.0.0.1:8000/ws/chat/. I call my other backend endpoints from my frontend React application through axios. The issue I'm currently facing is that my websocket endpoints are interfering with my other backend endpoints. Here is quick summary of how I have things set up: The chat component is set it to render on all routes. My 'Dashboard' component is being served through a specific route. In my 'Dashboard' component, I utilise my useEffect hook to fetch data whenever a particular state variable changes. This data fetches information from my backend endpoint. Here is a description of the problem: Whenever my state variable updates, the fetch logic executes. While these requests go through, if I send a message through my chat component (which in turns triggers the websocket endpoint) the messages do not come through instantaneously. Upon close inspection, I've noticed that the chat messages wait for the backend endpoint requests to go through and then only do the websocket messages come through. How can I resolve … -
Proper way of making an external API call based on given data - DRF
I am trying to save location data based on given IP address using Django REST Framework. So, I have a few questions about the sturcture of this process. The program should call external API based on given data and after that it will create a new object in the database. The question is - How I can pass the given IP address to the call function? I tried to use serializers.CharField and take the value from there with validated_data but it throws an attribute error after creating a new object. And where I must use the create() function in order to save response data? I just need to know what is the proper way of passing data(given IP address) to the create() function? serializers.py from rest_framework import serializers from core.models import GeoLocation from .services import get_location class GeoLocationSerializer(serializers.Serializer): url = serializers.CharField(max_length=255) def create(self, validated_data): url = validated_data.get("url", None) validated_data.pop('url') geo_data = get_location(url) return GeoLocation.objects.create( ip=geo_data['ip'], country_name=geo_data['country_name'], region_code=geo_data['region_code'], city=geo_data['city'], latitude=geo_data['latitude'], longitude=geo_data['longitude'], zip_code=geo_data['zip'] ) views.py from rest_framework import viewsets, mixins, generics from geolocation import serializers from core.models import GeoLocation from geolocation.services import get_location class GeoLocationViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): queryset = GeoLocation.objects.all() serializer_class = serializers.GeoLocationSerializer def get_queryset(self): return self.queryset.order_by('-id') def perform_create(self, serializer): serializer.save() -
Django Allauth - Cannot retrieve profile picture from Facebook
I am trying to build a website and integrate it with Facebook to authenticate. I'm also trying to get the profile picture and show it in the website. As Django Authentication I'm using django-allauth. I managed to login in and authenticate with Facebook, however I seems to have an issue when trying to get the profile picture. I'm using this html code in my template: <img class="rounded-circle account-img center-align" src="{{ user.socialaccount_set.all.0.get_avatar_url }}" width="80" height="80"> Am I'm getting this picture. Any help please on what I'm doing wrong or maybe there is an alternative to get the profile picture of a user? Thanks -
Postman-django for messaging between users
I just installed postman-django so that site users can exchange messages, but after installation according to the instructions, everything that appears on the screen (attached), no response when pressed. Links such as for example {% url 'inbox'%} do not work, in the admin panel everything works there is an opportunity to compose messages. what are my next steps? -
One view for two models with redirect
I have Django app with the following model: class Author(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) This is now using simple generic view: class AuthorDetail(DetailView): model = Author def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # some additional context thingies return context and with the following URL configuration: path('author/<slug:slug>/', AuthorDetail.as_view(), name='author-detail'), Now I want to introduce simple aliases for authors, so for example instead of /author/william-shakespeare I can reach the page also as /author/ws or /author/my-favourite-author. I came up with this idea (I know that destination could be key to Author, but that (I think) would not change much in the case): class AuthorAlias(models.Model): slug = models.SlugField(max_length=200, unique=True) destination = models.CharField(max_length=200) So to achieve the redirect I came up with the following in the view: def get(self, request, **kwargs): slug = kwargs['slug'] try: self.object = self.get_object() except Http404: self.object = get_object_or_404(AuthorAlias, slug=slug) return redirect(reverse('author-detail', args=[self.object.destination])) context = self.get_context_data(object=self.object) return self.render_to_response(context) Everything seems to be working fine, but I was wondering it there is a better approach and if this approach can cause any issues I'm not seeing? -
adding a new path or something other that will work, pls help :(
So im trying t implement a feature to my project that will add a new article. Basically the project is creating my own wikipedia. I have been stuck on this problem for a few weeks so i really need help as i dont have unlimited amount of time. What i want to happen is after pressing a button in new article page it should "put" a link in the index page where all the links to articles are. views: from django.shortcuts import render from django.http import HttpResponse from . import util import random def index(request): entries = util.list_entries() random_page = random.choice(entries) return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "random_page": random_page, }) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) def new_article(request): return render(request, "encyclopedia/new_article_tem.html", { "article_Django": "this is a framework" }) index: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block … -
Flask UnboundLocalError
I have a simple flask application and there is an option to register in this application but I am getting the UnboundLocalError error. I did not understand this error and could not solve it please help. App: from flask import Flask,render_template,request,redirect import os,string from random import choices #from wtform_fields import * from datetime import datetime from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////storage/emulated/0/Download/mysite/site.db' db = SQLAlchemy(app) @app.route("/") @app.route("/home") def index(): return render_template("index.html") @app.route("/login") def login(): return render_template("login.html") @app.route("/register",methods=["GET","POST"]) def register(): error='' if request.method=="POST": username=request.form["username"] email=request.form["email"] password=request.form["password"] re_password=request.form["re_password"] # if not username or not email or not password: # error="" if username == "": error="Please , enter a username" elif password == "" or re_password == "": error="Please,enter a password" elif password != re_password: error="Passwords are not the same." elif email == "": error="Plesase, enter a email." else: check_mail=user.query.filter_by(email=email).first() check_user=user.query.filter_by(username=username).first() if check_user: error="This username already in use." elif check_mail: error="This email already in use." else: user=user( username=username, email=email, password=password, re_password=re_password ) db.session.add(user) db.session.commit() return render_template("register.html",error=error) class user(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(15)) email = db.Column(db.String) password = db.Column(db.String) def __repr__(self): return "<user(id='%s' , username='%s',email='%s',password='%s')> " % (self.id,self.username,self.email,self.password) if __name__=="__main__": app.run(debug=True) But I'm getting this error UnboundLocalError:Local variable … -
Delete file after updating or deleting a file or an image in Django
I have the following Django models: class Dealer(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT) kyc_verified = models.BooleanField('kyc status',default=False) aadhar = models.FileField(upload_to='aadhar_images/') pan = models.FileField(upload_to='pan_images/') Here kyc,aadhar and pan are file fields. When we update or delete record, how to delete the file corresponding after the db is updated or the record is deleted. Also, how to change the name of the file before saving the record. I am updating the record as follows: def update(request): if request.method=='POST': dealer = request.user.dealer if request.FILES.get('aadhar',None): dealer.aadhar = request.FILES['aadhar'] dealer.save() if request.FILES.get('pan',None): dealer.pan = request.FILES['pan'] dealer.save() if request.FILES.get('gts',None): dealer.gts = request.FILES['gts'] dealer.save() -
Custom from validation in ModelForm
I am new in Django and i start writing my first web application. https://ibb.co/jDPwSHG I want to make custom validation, for exemple winner cannot be also lost. How can i do that using ModelForm ? Can anybody show me a example of this solution ? -
Django | Decimal Field is required even tho i set it to NULL=True
im trying to play a little bit around with django but i have run into problems... I have a Decimal Field which is not required so i set it to "blank=True" and "null=True". But it still says its required :( Here is my models.py from django.db import models weightUnit = { ('kg' , 'kilogram'), ('g', 'gram'), ('t', 'tons'), ('n', '-'), } class Product(models.Model): pname = models.CharField( max_length=50, ) pdesc = models.TextField( max_length=5000, ) pprice = models.DecimalField( max_digits=6, decimal_places=2, ) psn = models.CharField( max_length = 30, null=True, blank=True, ) pweightunit = models.CharField( choices=weightUnit, default='n', null=True, blank=True, max_length=5, ) pweight = models.DecimalField( null=True, blank = True, max_digits=10000, decimal_places=2, ) plimage = models.ImageField( blank=True, null=True, )