Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass parameters to URL in render
I'm building a commerce site and the user could access any listing through site_url/<id:listing_id>. Through the listing page, the user can bid on an item. If the form is valid, the user is redirected to the same listing page using the following logic return HttpResponseRedirect(reverse("listing", args=[listing_id])) However, if the form is not valid (the new bid is less than the current bid), the user should be redirected to the main page and an error message should be shown. I figured out that I may have to use render function to pass a context which will include the message to be displayed in HTML template. However I couldn't pass the listing id. This is the logic of this function: def listing_page(request, listing_id): """Shows the listing page based on id""" if request.method == "POST": # Create a form instance and populate it with data from the request: form = BidForm(request.POST) if form.is_valid(): # Get the current bid current_bid = Listing.objects.get(pk=listing_id).current_bid # Get the new bid from the cleaned_data new_bid = form.cleaned_data["bid"] # If the new bid is less than the current, return an error if new_bid < current_bid: return render(request, "auctions/listing.html", listing_id=listing_id) # Here I failed # Save a new bid object … -
Problem not display datetime field form in browser in django
What I can't see input datetime form.form django in my browser? Thank you for your reply forms.py forms.py views.py views.py my_html.py my_html.py browser page browser page -
Django: Reference user's first_name using AbstractUser?
My goal is to add non-authentication values to a user. Like, bio, nationality, etc. I am trying to use a custom user model. I am having trouble accessing the values. I can use the new ones I created, but not the original ones like first_name, last_name, email. my model.py looks like from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.CharField(max_length=500, blank=True) phone = models.CharField(max_length=20, blank=True) Settings.py I added: AUTH_USER_MODEL = 'publication.User' INSTALLED_APPS = [ 'publication.apps.PublicationConfig, ... My admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) How to I add bio and nickname to the admin page? And how do I access first name, email, bio, phone outside in forms and such? Many thanks. -
Django - Changing a graph using dropdown values
I have a pandas dataframe (created by pulling data from an API) that has information on various assets, such as name, price, time, volume, ect. My goal is to display a graph that changes based on information that a user selects in a couple dropdowns above, such as name and a time range. On a high level, I'm a bit unsure on how to begin implementing this. Should I render the graph in views and connect those views to the app html file? Should I store the dataframe in some sort of SQL database via the models file? Any and all information or examples for implementing this idea would be appreciated. -
test async task that retries a couple of times and revokes if fails
I want to test a task that is called 5 times incase there's an error, and the worker stops after that. Below is my code: @app.task(bind=True) def my_func(self): try: print('---------retrying') try: # check if the object exists and do something except Exception as exc: # some other thing my_func.retry(max_retries=5, countdown=15) return False except MaxRetriesExceededError as mexc: print('*****revoking') revoke(task_id=self.request.id, terminate=True, state='REVOKED') tests.py class TestTasks(TestCase): @patch('app.tasks.my_func') @override_settings(CELERY_ALWAYS_EAGER=True) def test_my_func(self, mock): # create an object my_func() assert mock.assert_called_once() The test crashes with an error that Expected 'my_func' to have been called once. Called 0 times. Please help Thanks in advance. -
Connection refused error when using Stripe webhooks
I'm constantly getting a connection refused error when trying to receive webhooks. (venv) alexa@main:/etc/nginx/sites-available$ stripe listen --forward-to localhost:5000/webhook/ go package net: built with netgo build tag; using Go's DNS resolver > Ready! Your webhook signing secret is whsec_************************* (^C to quit) 2021-04-05 18:13:03 --> customer.subscription.updated [evt_1Icwv5HrsuAsSZROjKy4Z5CK] 2021-04-05 18:13:03 [ERROR] Failed to POST: Post "http://localhost:5000/webhook/": dial tcp 127.0.0.1:5000: connect: connection refused) The port is enabled through my firewall: To Action From -- ------ ---- 5000 ALLOW Anywhere 5000/tcp ALLOW Anywhere 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 5555 ALLOW Anywhere 5000 (v6) ALLOW Anywhere (v6) 5000/tcp (v6) ALLOW Anywhere (v6) 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) 5555 (v6) ALLOW Anywhere (v6) My webapp is running on Ubuntu 20.10 -
django development show plugin (DjangoQLSearchMixin) but not in production
I have a develop env (local run on windows pycharm terminal with --insecure set) that is working properly with this plugin DjangoQLSearchMixin - I can see it on the search engine. But for some reason it is not activated on the production admin panel (nginx + ubunto + django). The code is the same, not sure what went wrong. Maybe I need to recreate static files ? Suggestions ? -
'ReverseManyToOneDescriptor' object has no attribute 'filter'
'ReverseManyToOneDescriptor' object has no attribute 'filter' why?) I'm trying to create a blog in django, got to the stage of adding comments and categories and got stuck I get an error. views.py from django.shortcuts import render, get_object_or_404 from .models import Post, Comment from django.views import generic from django.http import HttpResponse from .forms import CommentForm def blog_list(request): post = Post.objects.all().order_by('-date') return render(request,'blog/blog_list.html', {'posts':post}) def blog_detail(request, slug): #return HttpResponse(slug) detail_post = Post.objects.get(slug=slug) comments = Post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render(request,'blog/blog_detail.html', {'detail_post':detail_post, 'comments':comments, 'new_comment': new_comment, 'comment_form': comment_form}) I hope someone helps, also with the problem of adding a category 14.comments = Post.comments.filter(active=True) … ▶ Local vars here is my models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) first_src = models.CharField('первоисточник', blank=True, max_length=100) author = models.ForeignKey(User, on_delete= models.CASCADE ) thumb = models.ImageField(default='default.png', blank=True) # add AND GO TO MIGRATE AND MAKEMIGRATIONS … -
How do i serve Media files on production in Django in Apache
I currently have a Django site running on amazon lightsail, i ran python manage.py collectstatic an had all static files running fine but i have issues with my media files..i can't upload to my project. Below are my codes settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /opt/bitnami/apache2/conf/vhosts/messages-http-vhost.conf (edited also for messages-https-vhost.conf) <IfDefine !IS_MESSAGES_LOADED> Define IS_MESSAGES_LOADED WSGIDaemonProcess messages python-home=/opt/bitnami/python python-path=/opt/bitnami/projects/messages </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup messages Alias /robots.txt /opt/bitnami/projects/messages/static/robots.txt Alias /favicon.ico /opt/bitnami/projects/messages/static/favicon.ico Alias /static/ /opt/bitnami/projects/messages/static/ Alias /media/ /opt/bitnami/projects/messages/media/ <Directory /opt/bitnami/projects/messages/static> Require all granted </Directory> <Directory /opt/bitnami/projects/messages/media> Require all granted </Directory> WSGIScriptAlias / /opt/bitnami/projects/messages/messages/wsgi.py <Directory /opt/bitnami/projects/messages/messages> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> models.py message_audio = models.FileField(upload_to='audio/', null=True) message_image = models.ImageField(upload_to='message-pics/', null=True) When i try to upload a file i get "Server Error (500)" -
How to connect marg ERP api to django e-commerce website website database
I am working on a project in which client has multiple store and these store has its products with different price and category. Client has marg ERP api and he wont to connect his ERP to our django e-commerce database so that he managed all his sold product by website through ERP. Please help me to connect marg ERP api to my django project. -
Why can different URLs give the same result. Please advise where to look for the bug
I am not sure how to provide the code. I have "views", "models", "urls" files and don't know where to look. Here is my GitHub project link: https://github.com/zaliubovskiy/horder I presume that the bug is here: /horder/products/templates/search.html The "for" cycle probably wrongly linked <div class="product-list"> <div class="product-container"> {% for product in product_list %} <a href="{{ product.get_absolute_url }}" class="card"> <div class="image"> <img src="http://drive.google.com/uc?export=view&id={{ product.image }}" alt="image"> </div> <div class="title"> {{ product.name }} </div> </a> {% endfor %} </div> </div> -
How to eliminate Permission error in django xlrd
I try creating model fields by importing an excel with the details but get the permission errors. What could be the problem... The view. def UploadTeacherView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] try: import os import tempfile import xlrd fd, tmp = tempfile.mkstemp() # create two temporary file with os.open(fd, 'wb') as out: # create new file objects out.write(excel_file.read()) book = xlrd.open_workbook(tmp) print(book) sheet = book.sheet_by_index(0) obj=TeacherData( code = sheet.cell_value(rowx=1, colx=1), first_name = sheet.cell_value(rowx=2, colx=1), last_name = sheet.cell_value(rowx=3, colx=1), email = sheet.cell_value(rowx=4, colx=1), phone = sheet.cell_value(rowx=5, colx=1), ) obj.save() finally: os.remove(tmp) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'new_teacher.html', {'form':form,'message':message}) Below is the error I get upon uploading a file. PermissionError at /teachers/upload [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\FRGULI~1\\AppData\\Local\\Temp\\tmpm87yli8l' -
How to delete a row in table with Django
I am new in Django. I am trying to add a delete button to delete the row. However, the output is not what I want because it outputs multiple times because I create a loop to get data for other columns. For this reason, is there a solution the delete button can run outside the loop? add_stock.html {% extends 'base.html' %} {% block content %} <h1>Add Stock</h1> <form action="{% url 'add_stock' %}" class="form-inline my-2 my-lg-0" method='POST'> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Add Stock" aria-label="Search" name="ticker"> <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add Stock</button> </form> <br/> <table class="table table-striped table-bordered"> <thead> <tr> <th scope="col">Symbol</th> <th scope="col">Company Name</th> <th scope="col">Last</th> <th scope="col">Extended Hours</th> <th scope="col">Change</th> <th scope="col">% Change</th> <th scope="col">Volume</th> <th scope="col"></th> </tr> </thead> <tbody> {% if ticker %} {% for list_item in output %} {% for item in ticker %} <tr> <th scope="row"> {{ list_item.symbol }} </th> <td>{{ list_item.companyName }}</td> <td>${{ list_item.latestPrice }}</td> <td>${{ list_item.extendedPrice }}</td> <td>{{ list_item.change }}</td> <td>{{ list_item.changePercent }}%</td> <td>{{ list_item.volume }}</td> <td><a href=" {% url 'delete' item.id %} "> Delete </a></td> </tr> {% endfor %} {% endfor %} </tbody> </table> {% endif %} urls.py from django.urls import path from . import views urlpatterns = [ path('', … -
Forgot Password - Django Rest Framework
I need to create an endpoint that sends the token to reset the lost password in Django Rest Framework, for that I installed the django-rest-passwordreset package and followed the steps below: However, when accessing the endpoint created with the POST method with the email in the body, it does not even return the token in the terminal, much less send the email, what am I doing wrong? settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'django_rest_passwordreset', ] EMAIL_BACKEND = 'django_amazon_ses.EmailBackend' AWS_SES_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', None) AWS_SES_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', None) AWS_SES_REGION = 'us-east-1' urls.py: from django.urls import path, include urlpatterns = [ ... path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] models.py: from django.dispatch import receiver from django.urls import reverse from django_rest_passwordreset.signals import reset_password_token_created from django.core.mail import send_mail @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): email_plaintext_message = "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) send_mail( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) Execute in my venv: python manage.py migrate -
Python application doesnt work on GoDaddy Shared Hosting after SSL Certifcate change
I had my django application hosted on the GoDaddy shared hosting platform which i set up using the SetUp Python Application. It was all working fine but then the free CloudFare SSL certificate. Hence i had to rename the DNS servers and replace the old Cloudfare SSL certificate with a new GoDaddy SSL certificate. But since then the website has been showing Incomplete response received from application. I called goDaddy support but they asked me to check my code. I did and I find no issues in it. I am unable to find the reason behind this issue. When i checked the network tab, it is showing a 502 error. The link to my website is Mint Chalk Media Can anyone pls help me find a solution? -
Django best practice for varying querysets dependant on user permissions and database values
I am new to Django and just trying to work out the best way of implementing some business logic. I am representing access to AV devices in a building with multiple floors. Each floor is leased by a separate tenant. Each tenant has one or more users than can access one or more of the AV devices on the floor. There is a tenant admin responsible for defining the users and their devices per tenancy. I have three roles - superuser, tenant admin and tenant user. I have a set of tables in the DB that define the floors, AV objects on the floors and which tenants can access which objects. The admin of this in Django works fine. I now want to display this in a simple front end so that the following is possible: super user - sees each floor and then can see devices on a selected floor and operate them tenant admin - sees just their floors and can operate all devices on their floor(s) tenant user - sees just the floor and devices they have been allocated access to To my mind this can all be done in one one template with some view based … -
Django: annotate count of replies by user through relation of field
I am struggling with this queryset for days, here's the model with three classes, User, Category, Post: from django.db import models from django.db.models.deletion import CASCADE class User(models.Model): name = models.CharField() @property def most_reply_to(self): return self.post_setvalues('reply_to')\ .annotate(reply_to_count=Count('user'))\ .order_by('user') @property def most_replied_by(self): pass class Category(models.Model): name = models.CharField() class Post(models.Model): title = models.CharField() user = models.ForeignKey(on_delete=models.CASCADE) category = models.ForeignKey(on_delete=models.CASCADE) url = models.URLField() reply_to = models.URLField() The reply_to filed contains the information of user interactions, unfortunately it's not ForeignKey'ed to the Post model itself, but only to point to the url field of other post. What I'd like to achieve here, is to annotate each user with: the counts of replies received, grouped by (source) user; the counts of replies given to, grouped by (target) user; For the most_reply_to method, I have experimented as seen in my code, but the code only gave me count of replies to each individual post (from the user), not the total count of replies to each other users, I have lost in the aggregate/annotate logic here. For the most_replied_by method, I understand I need to start with the entire Post.objects.all() queryset, but I have no clue as how should I filter out those that are replies to … -
How to paginate a class-based list view with django-filters
Do you guys know how to paginate a generic class-based ListView that uses django-filters as a search bar? When I read some articles regarding this issue(which wasn't a lot for class-based views), it seems that django-filters and pagination don't work together very well. Here is my view: class StudentListView(OrganisorAndLoginRequiredMixin, generic.ListView): template_name = "leads/student_list.html" context_object_name = "leads" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = StudentFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): organisation = self.request.user.userprofile return Lead.objects.filter(organisation=organisation).order_by('first_name') I would really appreciate it if you guys could tell me what code I need to write for my view as well as what code I need to add into my template to make this work. I don't think the code for the actual filter and the template is necessary, but if you guys need it, I can add it to this question. Thanks. -
Why django gives TypeError mistake?
TypeError at/admin/ 'set' object is not reversible Only admin page gives error.Home page doesnt.How can i fix this?Help please. -
how to setup postgresql on Circle CI
I have the following build configuration that succeeded on Circle CI but i don't understand why postgresql result is actually grey. it look like its not working properly when i click on the database report: here is the report from the console: **************************************************** WARNING: No password has been set for the database. This will allow anyone with access to the Postgres port to access your database. In Docker's default configuration, this is effectively any other container on the same system. Use "-e POSTGRES_PASSWORD=password" to set it in "docker run". **************************************************** The files belonging to this database system will be owned by user "postgres". This user must also own the server process. The database cluster will be initialized with locale "en_US.utf8". The default database encoding has accordingly been set to "UTF8". The default text search configuration will be set to "english". Data page checksums are disabled. fixing permissions on existing directory /var/lib/postgresql/data ... ok creating subdirectories ... ok selecting default max_connections ... 100 selecting default shared_buffers ... 128MB selecting default timezone ... UTC selecting dynamic shared memory implementation ... posix creating configuration files ... ok running bootstrap script ... ok performing post-bootstrap initialization ... sh: locale: not found 2021-04-05 17:06:05.104 UTC … -
pythonanywhere django static files are not collected from application
The problem is that static files from Django app are not being collected in pythonanywhere. After the command python manage.py collectstatic In the directory /home/user/user.pythonanywhere.com/static Only the admin folder appears. settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] Css file location: +---myapp | +---static | | \---myapp | | \---css | | \---myapp.css When I run the command python manage.py collectstatic in my local command line, static files from the application are collected, the problem is in pythonanywhere. All actions are standard, I did everything strictly according to the guide, I cannot understand what's the matter. Thanks a lot I have read all the articles on this topic on pythonanywhere and everything I found on stackoverflow and in the documentation, but nothing helps to solve the problem. https://help.pythonanywhere.com/pages/DjangoStaticFiles https://help.pythonanywhere.com/pages/DebuggingStaticFiles/ https://help.pythonanywhere.com/pages/StaticFiles -
How to dynamically update a django form field queryset based on selection in previous field?
I currently have the following form and view: class CreatePreferenceForm(Form): object_1_type = ModelChoiceField(queryset=ContentType.objects.filter(model__in=['course', 'baseuser'])) object_1 = ModelChoiceField(queryset=Course.objects.all()) object_2_type = ModelChoiceField(queryset=ContentType.objects.filter(model__in=['course', 'timeblock'])) object_2 = ModelChoiceField(queryset=Course.objects.all()) class CreatePreferenceView(LoginRequiredMixin, FormView): template_name = 'crud/create_preference.html' form_class = CreatePreferenceForm success_url = '/crud/create-preference' What I want to achieve is: When the user selects the Course model in the object_1_type field, the object_1 queryset should be updated to be Course.objects.all(). Inversely, if they choose the BaseUser model, the queryset will be BaseUser.objects.all(). Equivalent logic will be applied to the second pair of fields, although with different models. I've researched this for some time and was able to find a few potential approaches, however, I am still struggling with implementing them. Advice or alternative approaches would be greatly appreciated. Potential Approaches: Use an Ajax call to update the frontend to filter out the portions of the queryset you do not want (so I'd start with having the queryset be both models and then remove all instances of the "wrong" model using Ajax). I haven't worked with Ajax before, so I'm unsure on how I would write this. Django form fields can be updated programmatically and it's theoretically possible to achieve what I'm looking for by updating the fields during … -
Django Docker How to only migrate in Container?
Question can be little unclear so let me explain. I have a Django Project and for this time I wanted to use Docker. So I dockerized my project from the tutorials on the internet. As Django users know, if you want to extend the user model you need to make migrations afterwards you edit the model So I was editing my custom user model and wanted to test a feature for my model. What I wanted to achieve was, test migrated version of my Django app on Docker container and if it fits my needs I would make the migration on local files. But after I ran the docker-compose exec web python manage.py make migrations users command my also local files changed. So my question is, if I want to test a feature on migrated version of my app can I test it on Docker container and then migrate on local machine? or did I not understand the logic of docker? docker-compose.yml version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/backend/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=admin - POSTGRES_DB=db - POSTGRES_PASSWORD=password volumes: postgres_data: -
Django Crispy forms Return missing labels in the browser
I am working with django forms recently and each time i add the |crispy tag as below on my forms, they come back missing labels in the browser. What could be the problem? Below is my form from the .html file. {% load crispy_forms_tags %} . . . <form method="post"> <fieldset class="form-group"> Enter details. </legend> {% csrf_token %} {{ form | crispy }} </fieldset> <button type="submit">Submit</button> </form> My form class from the forms.py file is below class MyPlanForm(forms.ModelForm): class Meta: model = MyPlan fields = [ 'title', 'intent', 'description' ] I have the latest version of django-crispy-forms which is a pip installation. I use chrome for development but the same issue happens in firefox. I really need help anyone. Thanks in advance! -
How I can compare content of fields?
I want to compare content of fields. It is work without errors, but fields arent comparing. Where if my misstake? views class check(DetailView): def get_object(self, **kwargs): print(kwargs) return test.objects.get(pk=self.kwargs['pk']) m = 5 if test.check1 == test.answer1: m=m-1 if test.check2 == test.answer2: m=m-1 if test.check3 == test.answer3: m=m-1 if test.check4 == test.answer4: m=m-1 if test.check5 == test.answer5: m=m-1 template_name = 'main/test_detail.html' html {% if m == 5 %} <a href={% url '' %}></a> {% elif m == 4 %} <a href={% url '' %}></a> {% elif m == 3 %} <a href={% url '' %}></a> {% elif m == 2 %} <a href={% url '' %}></a> {% elif m == 1 %} <a href={% url '' %}></a> {% elif m == 0 %} <a href={% url '' %}></a> {% endif %} Models class test(models.Model): answer1 = models.CharField() answer2 = models.CharField() answer3 = models.CharField() answer4 = models.CharField() answer5 = models.CharField() check1 = models.CharField(null=True, blank=True) check2 = models.CharField(null=True, blank=True) check3 = models.CharField(null=True, blank=True) check4 = models.CharField(null=True, blank=True) check5 = models.CharField(null=True, blank=True)