Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
local variable 'username' referenced before assignment django
I have created a function called a panel. When i run the server it gives an error " UnboundLocalError at /service-panel/ local variable 'username' referenced before assignment" . I don't know what is getting wrong. Here is views.py @login_required def panel(request): if(request.session.has_key('username')): username = request.session['username'] data = Enquiry.objects.filter(service=request.session['service']) return render(request, 'service-provider-panel/base.html', {'username':username, 'data':data}) -
How can I use elasticsearch in my django Project?
I'm working on a search bar in my site made with django . I want to include elasticsearch while I already have saved my data in postgresql. what should I do to connect elasticsearch with my django application and postgresql ? -
After form submit change div height. django (python)
I have registration form and one submit button. when i click submit, if there is an error the height of the div increases so I do auto = "height". but when i click submit changes div (.continer) height size. it's auto but after one second refresh page and back same css. also remove error if i have in console how fix? please help me. this is my code --> base.html (only submit code) <button type="submit" name="register" id="btn" onclick="changeSize()">registration</button> script.js function changeSize() { var el = document.querySelector(".continer").setAttribute("style", "height:auto"); } -
Heroku Datsbase Migration Error (django.db.utils.DataError)
I have made a website using Django and hosted on Heroku. Everything was working fine until I try to alter my one of the column in the database. The thing is that I alter the column from max_length=1000 to max_length=60 but I forgot that I have entered value more than 60 so I got django.db.utils.DataError error that value is too long for 60. For this problem solution, I refer one of the solutions available in StackOverflow to remove all the migrated file from its folder except init.py and then do fresh migration. So I tried that and I work with charm and I have changed the value so it could fit the max limit. But now, when I try to create new column in database it says django.db.utils.ProgrammingError django.db.utils.ProgrammingError: column "column_name" of relation "table" does not exist Actually, when I try to run my app on the local server it works fine and even it allows me to create a new column in my database but when I try to migrate it to Heroku database it shows django.db.utils.ProgrammingError -
Is there a way to remove the ImageField's URL in Django?
My Django app has a Profile Page but the issue is that when I go to "Edit Profile", it looks really bad cause of ImageField's URL especially in the mobile view. Note that the URL doesn't fit and it messes up with the navbar too in the mobile view. Is there a way to hide this "Currently" field? -
Using the same view returned form variable for two different templates
I have a subscribe form view which displays to a subscribe page, and I also want to display that same form in the home page, I tried using {% include 'accounts/subscribe.html' %} in the home page (a recommendation from a similar question but not the same). How can I please go about this ? view that leads to the subscribe.html def subscribe(request): if request.method == 'POST': subscribe_form = EmailListForm(request.POST) if subscribe_form.is_valid(): subscribe_form = subscribe_form.save() return render(request, 'accounts/subscribe_done.html', {'name': subscribe_form.name}) else: subscribe_form = EmailListForm() return render(request, 'accounts/subscribe.html', {'sub_form': subscribe_form}) -
Django models to HTML. Then, HTML to PDF
I am trying to export django models data (admin side data) into a PDF file. For that first I created a HTML file to render the data from models. The HTML file I created It worked successfully and showed the data from the models correctly. Successfully worked (I create a url for it to check whether it is working or not) Then I tried to render the same html file to PDF. I ran the server and I generated a pdf file. PDF file I expected it will show the data also. But It only showed the table border. You can see my folders and names in the 1st photo. I thing it is enough to add this code. If you need full code please tell me. This is my views.py from app. def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('app/pdf_template.html') return HttpResponse(pdf, content_type='application/pdf') def index(request): context = {} return render(request, 'app/index.html', context) Can't I use the same html file to get the data as pdf? Can anyone tell me what wrong I did? -
Displaying images directly using FTP server on web page in Django
I want to read an image from the FTP server directly then displaying it in HTML directly without storing it on the server. @login_required(login_url='login') def index(request): img = urllib.urlretrieve("ftp://username:password@url.com/1.jpg") print(type(img)) img = list(img) img_path = img[0] # img_path = "file:///C://Users//Daud//AppData//Local//Temp//tmpcik5w5mw" print("Img your are looking for is") print(img) context = {"img": img_path} return render(request, 'dashboard/index.html', context=context) <img src="{{img}}" /> #<img src="C://Users//Daud//AppData//Local//Temp//tmpcik5w5mw"> But the image is not getting render. Is there a way we can create a temporary image in a static folder. Maybe the specific folder access is not allowed. Is there a way to achieve this without exposing FTP server credentials publicly. -
why does it inject "/product/image-name/" before image source
why does it inject "/product/image-name/" before image source product.html: <div class="product-gallery product-gallery-vertical"> <div class="row"> <figure class="product-main-image"> <img id="product-zoom" src="{{product.image1.url}}" data-zoom-image="{{product.image1.url}}" alt="product image"> settings.py: MEDIA_URL = "assets/images/" MEDIA_ROOT = os.path.join(BASE_DIR, 'ecommerce/static/assets/images/') views.py: def product(request, slug): product = Product.objects.get(slug=slug) print(product.image1.url) context = {'product': product} return render(request, "product.html", context) error: Not Found: /product/iphone-11/assets/images/products/Apple-iPhone-11-Black-frontimage.jpg -
How to create different objects depending on input?
What I have so far: import app.models as models if table_name == "Appliances": model = models.Appliances elif table_name == "ArtsCraftsAndSewing": model = models.ArtsCraftsAndSewing ... for index, row in df.iterrows(): model = model(param1=row[column1], param2=row[column2], ...) TypeError: 'Appliances' object is not callable Basically I'm trying to call model = models.Appliances(param1=row[column1], param2=row[column2], ...) except the specific object changes depending on input. -
Celery in dokku doesn't see sqlite records
My stack is: Django, Celery(Redis broker), Dokku. My code put the record in sqlite database and put the task for Celery: package = Package.objects.get(pk=package_id) package.download_status = 'QUEUE' # package is Django ORM object package.save() task_download_package.delay(package.id) # put a task to redis for celery Now I need to get this object from sqlite database inside the Celery task. But inside the Celery task process I can't see the record: @app.task(bind=True) def task_download_package(self, package_id: int): try: package = Package.objects.get(pk=package_id) except ObjectDoesNotExist: print("Package with pk={} not found".format(package_id)) # I HAVE GOT THIS MESSAGE return But when I ask package.download_status from Django process by my special endpoint I got "QUEUE" status. It looks like Django and Celery processes has different containers or diffenrent databases. I have checked connection.settings_dict['NAME'] and it's return the same "/app/db.sqlite3" value for Django and Celery processes. This code without Dokku works fine, but now I need it with Dokku. Why Celery doesn't see record in sqlite db? Is it actually the same database? May be I need something like a Commit? (I use Django save method) How I can fix it? -
django and html output
this program takes the input and displays it with the time (using python and HTML) I have a problem with the output below ' enter image description here here with adding out.stdout to take the output only .. enter image description here but the output have a (b') enter image description here how can I display the output without this 'b and the \r\n'? -
How can i use ssl in nginx?
hi i'm trying to make my own django server. i use django uwsgi nginx. i got ssl encryption on my nginx. but just only my localhost. ex) my localhost ip = 1.2.3.44 if i https://1.2.3.44, it work. direct to django server. but when i input https://my.domain.com:9002 , it won't work. just lead nginx.html and not working ssl. what am i wrong? why localhost ip ssl work and dns not working? here is my code. this file is /usr/local/etc/nginx/nginx.conf server { listen 443 ssl; server_name fidochallenge486.tk; ssl_certificate /Users/junbeomkwak/Downloads/fidochallenge486.tk/bundle.crt; ssl_certificate_key /Users/junbeomkwak/Downloads/fidochallenge486.tk/privkey.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_pass http://172.30.1.40:8000/; } } include servers/*; } server { listen 9002; server_name fidochallenge486.tk; large_client_header_buffers 4 64k; location ~/.well-known { root /Users/junbeomkwak/Downloads/fidochallenge486.tk; allow all; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location / { proxy_pass http://172.30.1.40:8000/; } } and this file is /usr/local/etc/nginx/sites-available/fido_project.conf upstream django { server 172.30.1.40:8000; #server unix:///Users/junbeomkwak/Desktop/fido_virtual/fido_project/fido.sock; #server unix:///tmp/fido.sock; } server { listen 9002; server_name fidochallenge486.tk; charset utf-8; client_max_body_size 75M; location /media { alias /Users/junbeomkwak/Desktop/fido_virtual/fido_project/media/; } location /static { alias /Users/junbeomkwak/Desktop/fido_virtual/fido_project/staticfile; } location / { uwsgi_pass django; include /Users/junbeomkwak/Desktop/fido_virtual/fido_project/uwsgi_params; proxy_redirect off; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme … -
<int:pk>/ in my Django new version project doesn't work for some reason
I am a newbie in Django and trying to create a basic project. I am currently stuck at int:pk/ and for some reason I couldn't link the details page to the school list page. Please help! thanks a lot! Below are the code: in my urls.py file: app_name = 'basic_app' urlpatterns = [ path('list/',views.SchoolListView.as_view(), name='list'), path('<int:pk>/',views.SchoolDetailView.as_view(), name='detail'), path('create/',views.SchoolCreateView.as_view(),name='create'), path('update/<int:pk>/', views.SchoolUpdateView.as_view(),name='update') ] in my views.py: class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School query_pk_and_slug=True def get(self, request, *args, **kwargs): return render(request,'basic_app/school_detail.html') class SchoolUpdateView(UpdateView): fields = ('name','principal') model = models.School in template: {% for school in school_list %} <h2><li><a href="{{ school.id }}">{{school.name}}</a></li></h2> {% endfor %} in models.py: from django.db import models from django.urls import reverse class School(models.Model): name = models.CharField(max_length=200) principal = models.CharField(max_length=200) location = models.CharField(max_length=200) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:detail",kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=200) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) this is the error that I got: NoReverseMatch at /basic_app/1/ Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/1/ Django Version: 3.0.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P<pk>[0-9]+)/$'] Exception Location: C:\Users\MyPC\Anaconda3\envs\MydjangoEnv\lib\site- packages\django\urls\resolvers.py in … -
How to prevent a container from shutting down during an error?
Everytime I make a mistake or something in my code, the container is shutting down and leaves me with shotel_backend exited with code 1. How to prevent it? Here's Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN pip install pipenv RUN mkdir /backend WORKDIR /backend ADD Pipfile Pipfile.lock /backend/ RUN pipenv install ADD . /backend/ and here docker-compose version: '3' services: backend: container_name: shotel_backend build: ./backend volumes: - ./backend/:/backend working_dir: /backend/ command: pipenv run python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 -
excluding the titles with no entries after elimination of blocked and suspended entries
I have a classic title and entry models where titles are FK in entries. I also let users block other users model below: class Block(models.Model): blocker= models.ForeignKey("auth.user",on_delete= models.CASCADE,related_name="blocker") blocked= models.ForeignKey("auth.user",on_delete= models.CASCADE,related_name="blocked") And also admins can suspend users by setting last_name to suspeneded in auth.user. I have a list of titles and I need to exclude titles which have no entries after elimination of suspended and blocked user's entries. Right now I just iterate over all titles and check one by one whether they have any remaning entries. -
How can I allow spaces in the default django user model username?
I am trying to allow spaces in the django user model, I tried overwriting its validator and it still does not work. -
How to implement single sign-on django auth in azure ad?
I have a django-based web application, a client requested that we integrate the login with Azure AD, following the documents I managed to integrate with the following flow. In django the user types only the email, I identify the user and his company and redirect him to the microsoft ad login screen, after login, the redirect uri is activated and in my view I do some validations and authenticate the user on my system. The problem is that every time the customer is going to log in he needs to enter his credentials in azure, would it be possible with the microsoft user_id or the token acquired the first time the user logs in to login? Or another way to log in faster? This my callback view, called in redirect_uri: def callback(request): user_id = request.session.pop('user_id', '') user_internal = User.objects.filter(id=user_id).first() company_azure = CompanyAzureAd.objects.filter(company=user_internal.employee.firm).first() # Get the state saved in session expected_state = request.session.pop('auth_state', '') # Make the token request url = request.build_absolute_uri(request.get_full_path()) token = get_token_from_code(url, expected_state, company_azure) # Get the user's profile user = get_user(token) #in this moment i have user microsoft profile, with token and id # Save token and user store_token(request, token) store_user(request, user) ... if it is possible … -
how can i display my admin panel question in static java script
this is my js file in static folder: let questions = [ { question :"my question", choiceA : "Correct", choiceB : "Wrong", choiceC : "Wrong", correct : "B" } this is admin.py from django.contrib import admin from .models import Question admin.site.register(Question) this is model.py class Question(models.Model): name=models.CharField(max_length=300) views.py def quiz(request): question=Question.objects.all() return render(request,"index.html",{"question":question}) this question is what should be written in js file for the place of "my question"? -
What is `class Meta` property in python-django
I watched some tutorials and read articles and now I got a lot of info about django.But almost in every one of them, people use class Meta property for some reason (for example,to serialize a class in rest-framework).I understand pretty much everything but except this one. Can anybody give a brief explanation of class Meta property? Thanks -
How can I find records that have the same values in a ManyToMany field in Django?
These are the models: class Post(models.Model): name = models.CharField(max_length=20, unique=True) class Subscription(models.Model): name = models.CharField(max_length=25) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='subscriptions') posts = models.ManyToManyField(Post, related_name='subscriptions') I want to find all the users that are subscribed to the same posts so that I can send them the same email instead of creating a different email for each user. The code should basically list all the times in Subscription that have the same values in the posts field. I spent the last four hours on this, googling the heck out of this but to no avail. I'm confiding in the Force, which is strong on StackOverflow. -
Django login system won't log user and won't display any error
Im doing login system on a main page if user is logged the form disappears and that's is working as expected but login form isn't working. I don't get any error so it's probably little mistake that i can't find. Any help would be much appreciated views.py def loginView(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') return redirect(request,'website/home.html') login.html <form method="POST"> {% csrf_token %} <input class="inpLogin" type="text" placeholder="Your username" name="username"/> <input class="inpLogin" type="password" placeholder="Password" name="password" /> <button class="btnLogin" type="submit" name='submit'> Log In</button> </form> urls i have nothing in there related to login -
Refreshing page on database modification
In the main page of my website there is a long list, <ul>. Each list item represents a model object. Within the list there are the objects attributes, for example its name etc, and also buttons to change those attributes. The list is loaded from the sqlite database. The issue is since each button changes data in the database, to display the changed data, the view function reloads the page on each button click. That is fine, except the list is very long, and is necessary to scroll down, and on each button click, the page is reloaded therefore goes to the very top of the list. This makes the webpage almost unusable, or at least very annoying to use. Can someone recommend a workaround to this problem. Please let me know if my question is not clear -
form submit not work in django project (python)
I have registration form and one submit button. when you click submit, if there is an error the height of the div increases so I do auto = "height". but now submit button not work when i submit I do not fill out the inputs, it does not show anything.the submit button inside form. how fix? this is my code ---> script.js function changeSize(event) { event.preventDefault(); var el = document.querySelector(".continer"); el.style.height = "auto"; } home.html (submit code) <button type="submit" name="register" id="btn" onClick = "changeSize(event)">registration</button> -
How to execute a PHP script on a remote server from my Django app?
As I am learning Django I encounter this problem. In my Django app, I have a form. After filling that form I'd like to send the data to another server to execute a PHP script with those data. How do I do that? If this was PHP calling PHP I'd do something like this $DATA = input data from a form; $URL = "https://pathofmyremotescript.com/script.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URL); curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $DATA); curl_exec($ch); I wonder if Django has anything similar to this?