Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make Django form fields required conditionally?
I am new to Django and I am trying learn about creating web apps. I am trying to delete a record without the form fields being required. I only want them to be required when creating a new record. Here is a screen shot: enter image description here Here is my form.py: from django import forms class ExpenseForm(forms.Form): name = forms.CharField( max_length=255, widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "Expense Name" }) ) amount = forms.DecimalField( max_digits=16, decimal_places=2, widget=forms.NumberInput(attrs={ "class": "form-control", "placeholder": "$400.00" }) ) Here is my view.py: from django.shortcuts import render from budget.models import Expense from .forms import ExpenseForm from django.http import HttpResponse, HttpResponseRedirect from django.db.models import Sum def budget_view(request): expenses = Expense.objects.all() total = Expense.objects.aggregate(total=Sum('amount'))['total'] form = ExpenseForm() if request.method == 'POST': form = ExpenseForm(request.POST) if form.is_valid() and 'create-expense' in request.POST: expense = Expense( name=form.cleaned_data["name"], amount=form.cleaned_data["amount"] ) expense.save() return HttpResponseRedirect('/') elif form.is_valid() and 'edit-expense' in request.POST: return HttpResponseRedirect('/') else: expense = Expense.objects.get(id=request.POST.get("delete-expense")) expense.delete() return HttpResponseRedirect('/') context = { "form": form, "expenses": expenses, "total": total, } return render(request, "budget_view.html", context) I tried adding form.fields[<field_name>].required() = False to the else block, but to no avail. Do I need to create a custom clean() in the form.py to perform validation on each field … -
Getting python usage errors using Django to display a table of files in a directory
So I am trying to get Django to display a template that shows a list of files on a local directory. My views.py looks like this: from django.shortcuts import render from django.http import HttpResponse from os import listdir def index(request): files = listdir("/path/to/directory/") filelen = len(files) return render(request, 'path/to/template.html') My html template looks like this: {%for i in range(1, filelen)%} <tr> <td>{{i}}</td> <td>{{files[i]}}</td> {% if "a" in files[i] %} <td>✓</td> {% else %} <td>x</td> {% endif %} {% if "b" in files[i] %} <td>✓</td> {% else %} <td>x</td> {% endif %} But when I try to run it I get the following error: Error at line 39 'for' statements should use the format 'for x in y': for i in range(1, len_files) Anybody know how to get this to work? I have tried replacing filelen with {{filelen}} but that gave me the same error. -
NoReverseMatch at /blog/ - Django by example code list and detail view issue
I'm working on the code in chapter 1 of the django by example. Followed all instructions and reviewed many feedbacks on this site and other areas but not to my luck. I had earlier attempted get_absolute_url and return reverse method unsuccessfully. I was trying an instructed approach and land exactly the same issues in listview and detailview. I'm a beginner so I guess I'm missing something may be fundamental. Is there any version dependency. I've installed latest django and python. Need advice and thanks for any help! This is the error message models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish_date = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # default Manager published = PublishedManager() # our custom manager class Meta: ordering = ['-publish_date',] def __str__(self): return self.title def get_absolute_url(self): return reverse( 'blog:post_detail', args=[ self.publish_date.year, self.publish_date.month, self.publish_date.day, self.slug, ] ) views.py from django.shortcuts import render, get_object_or_404 from … -
Django Built in PasswordChangeView keeps redirecting me to the admin password change after declaring my templates
urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from .views import ( dashboardview ) urlpatterns = [ `path('dashboard/', dashboardview, name='dashboard'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('change-password/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change_form.html'), name='password_change'), path('password/change/done', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ` ] -
how to upload 'django-rest-api server', and 'crawling.py'
Hi, guys. i have a problem. i made an android application written by kotlin. this app communicates to 'django-restapi server' to get some data. 'django-restapi server' gets data from 'crawling.py' file(using selenium,headless chrome). app : show data to people django-restapi server : get data from crawling.py, and saving data on database crawling.py(with chromedriver) : crawling data from website, and sending data to server so, what i want to know is, i don't know how to upload them. i want to use aws. what i'm thinking now is, upload 'django-restapi server' and 'crawling.py' to aws lambda seperately. then, i will run 2 lambda. but i think it's bad architecture. can you advice me better answer? -
"cleaned_data" isn't working as my browser shows back - " Exception Value: 'FormName' object has no attribute 'cleaned_data' "
and here is my VIEWS.PY, def form_view(request): form = forms.FormName() if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid: print("VALIDATION SUCCESS !!") d = form.cleaned_data['name'] print("name:", d) return render(request, 'baleno/form_pg.html', {'form': form}) -
how to complete my django app in the backend
I created a django app , I also set templates and static files . I made migrations my questions is : I want to scrape data from different websites and save it in django to be displayed in my templates what would be the next steps then ? -
I want to know,how does 'category' knows which model to access
template code- <a class="dropdown-item" href="{% url 'home' %}">All Products</a> {% for category in links %} <a class="dropdown-item" href="{{category.get_url}}">{{category}}</a> {% endfor %} context_processor.py def menu_links(request): links=Category.objects.all() return dict(links=links) Category Model- class Category (models.Model): name=models.CharField(max_length=250, unique=True) slug=models.SlugField(max_length=250, unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='category',blank=True) def get_url(self): return reverse('products_by_category',args=[self.slug]) def __str__(self): return self.name Product model- class Product(models.Model): name=models.CharField(max_length=250, unique=True) slug=models.SlugField(max_length=250, unique=True) description=models.TextField(blank=True) category=models.ForeignKey(Category, on_delete=models.CASCADE) price=models.DecimalField(max_digits=10,decimal_places=2) image=models.ImageField(upload_to='product',blank=True) stock=models.IntegerField() available=models.BooleanField(default=True) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_url(self): return reverse('product_detail',args=[self.category.slug,self.slug]) def __str__ (self): return self.name here, as you can see the def get_url(self) is in Category as well as Product model I just want to know how come category in {{category.get_url}} knows to access the method in Category and not in Product model -
Reuse existing Django rest framework serializer
I am currently using Django Rest Framework and I am looking for a way to reuse some attributes from an already defined Serializer. In order to explain, I am going to expose some of the serializers involved: Completed Serializer: class ProductSerializer(serializers.ModelSerializer): subscribed = serializers.SerializerMethodField() other_field = serializers.SerializerMethodField() class Meta: model = Product fields = [ 'id', 'name', 'subscribed', 'other_field', 'x', 'y', 'z' ] def get_subscribed(self, product: Product): return product.is_user_subscribed(self.context['request'].user) Simplified Serializer: class ProductSimplifiedSerializer(serializers.ModelSerializer): subscribed = serializers.SerializerMethodField() class Meta: model = Product fields = [ 'id', 'name', 'subscribed' ] def get_subscribed(self, product: Product): return product.is_user_subscribed(self.context['request'].user) As you can notice above, those serializers are almost the same, but one of them is a simplified version of the object because I don't want to retrieve unnecessary information in some parts. The problem here is that in this scenario we have a method serializer that will need to be maintained two times. Maybe in the future, I would want to add another field, and I will need to add it to both. So, how could be achieved a Based Serializer in which all the fields are included but I could reuse it and extract specific fields from it? I have already thought these options: … -
Django returns error but dosen't check for more Integrity errors afterwards
So a request that violates the check for postive_integer (e.g. positive_integer = -1), django will not check for errors against unique_together (e.g. record with same name and user already exist) and will only return the original error from the positive_integer. class Foo(models.Model): positive_integer = models.PositiveIntegerField() name = models.CharField(max_length=100) user = models.CharField(max_length=100) class Meta: unique_together = (('name', 'user',)) -
Project migration to django data
Can i migraine my project from jam.py to Django? Without any change in the code or rewriting it to suit the framework? Or do you prefer to create my project on Django in the first place -
How can i stored verification code that send from register page to confirm page?
There is registration form that has mobile number and password for register,when person inter the info and submit,verification code sent for him,i want to access the verification code that sent in register page,that i can to compare with code that person inter in in input. how can i access into verification code in the confirm page -
django: nginx + gunicorn: request.build_absolute_uri() function not accounting for the port
I have the following code running in production The Nginx config is as follows: # first we declare our upstream server, which is our Gunicorn application upstream hello_server { # docker will automatically resolve this to the correct address # because we use the same name as the service: "djangoapp" server webapp:8888; } # now we declare our main server server { listen 8558; server_name localhost; location / { # everything is passed to Gunicorn proxy_pass http://hello_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Nginx server has port forwarding: 8555:8558 And the gunicorn command running is gunicorn --bind :8888 basic_django.wsgi:application Now in my browser i open this url: http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email Now my code in one of my views is prev_url = request.META['HTTP_REFERER'] # EG: prev_url = http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email # we want to get the url from namespace . We use reverse. But this give relative url not the full url with domain login_form_email_url_reverse = reverse("login_register_password_namespace:user_login_via_otp_form_email") # EG: login_form_email_url_reverse = "/login_register_password/user_login_via_otp_form_email" # to get the full url we have to use do the below login_form_email_url_reverse_full = request.build_absolute_uri(login_form_email_url_reverse) # EG: login_form_email_url_reverse_full = "http://127.0.0.1/login_register_password/user_login_via_otp_form_email" I am execpting prev_url and login_form_email_url_reverse_full to be same but it differs prev_url domain is http://127.0.0.1:8555 whereas login_form_email_url_reverse_full … -
changing navbar icons to active with django-Javascript
I have made a navbar with bootstrap4 and I want to toggle the icon of current page to active. Currently, I am using <li class="nav-item"><a href="/" id="A" {% if request.path == "/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Home</a></li> <li class="nav-item"><a href="/blog" id="B" {% if request.path == "/blog/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Blog</a></li> what I would like is a simpler way with use of url names that could activate a script like this: {% if request.path == '/' %} <script> document.getElementById("#A").classList.add('active'); if ( document.getElementById("#A").classList.contains('active') ) document.getElementById("#A").classList.toggle('active'); </script> {% elif request.path == '/blog/' %} <script> document.getElementById("#B").classList.add('active'); if ( document.getElementById("#B").classList.contains('active') ) document.getElementById("#B").classList.toggle('active'); </script> {% endif %} Could there be an easier way? Please suggest to highlight the active page icon on navbar to toggle styles. Thank you -
i want to move to my index page from anywhere in the app but got struck in the detailed generic view in Django
i am new to django and covered all the nooks and corners of it but i was struck at internal URL routing. i am completely succeeded in transforming my existing application into Django everything works fine but the issue is whenever i click on the logo i want to go back to my index page but that is not happening the path /index.html is adding in the last of my existing path what may be the reason. here is my URL.py file path('',views.home,name='home'), path('index.html',views.home,name='home'), path('easy.html',views.Easy.as_view(),name='title'), path('medium.html',views.Medium.as_view(),name='medium'), path('hard.html',views.Hard.as_view(),name='hard'), path('contribute.html',views.contribute,name='contribute'), path('contact.html',views.contact,name='contact'), path('about.html',views.about,name='about'), path('problems',views.problems,name='problems'), path('action',views.action,name='action'), path('detail.html',views.detail,name='detail'), path('detail.html/<slug:pk>/',views.DetailView.as_view(),name='detail') i can get back to any location in my when when i was on the navbar and normal application but the only problem arises when i entered into a detailed view which is a generic view. http://127.0.0.1:8000/detail.html/2/ this is how i entered a generic view which will display all the fields of record with PK=2. it's working fine. but now i want to get back index file by clicking on my logo then the link changes as follows. http://127.0.0.1:8000/detail.html/2/index.html i know my url.py file cannot identify this hence raising the 404 error. how to get rid of this? please help. by the way ,the below code … -
Using subdomain to set variable and display localized version of Django apps/sites
I have installed Django-modeltranslation, which creates additional fields to translate into additional language from a base field. The default language shown is base on the LANGUAGE_CODE in settings.py For example: LANGUAGE_CODE = 'de' will show the German version of the site. I want to use subdomain to set the variable for LANGUAGE_CODE and display to users to the appropriate language version of the site. For example: de.site.com subdomain 'de' will set the LANGUAGE_CODE to 'de' and show the website in German. vs. www.site.com subdomain 'www' will set the LANGUAGE_CODE to 'en_us' and show the website in American English. How do you do this? Is there a better implementation to get to the same point? -
CSS button won't change color
I'm trying to edit a template I've downloaded on the internet, by changing some colors. However, when I change the color in the css file, it doesn't change it on the website: HTML: <div class="user-panel"> <a href="https://example.com" target="_blank">Link</a> </div> CSS: .user-panel { float: right; font-weight: 500; background: #ffb320; padding: 8px 28px; border-radius: 30px; } This is how I import the .css file: <link rel="stylesheet" href="{% static 'css/style.css' %}"/> So what I did was changing #ffb320 to #cc0000 to have red instead of yellow, saved the file, and reloaded the page, but the color didn't change. Same goes for font size, etc... The only thing that did work was using style='font-size:20px' for the font size. What am I doing wrong here? -
Best way to increase post view count
I need to implement a way to increase view count for my posts when the post is viewed on the client side. For now, I won't be handling removing duplicate views by refreshing. If PATCH or PUT is sent to the server with the viewcount + 1 on client side, viewcount will be overridden if multiple users use my service. Is creating a new endpoint only for increasing the view count the best practice? If so, what would be the correct URI staying RESTful? (POST /post/count ?) -
How do I solve the problem in I mean them
enter image description here CrispyError at /accounts/login/ |as_crispy_field got passed an invalid or inexistent field -
Authorize user by sessionid axios
I am creating my e-commerce app(django-oscar api) and I would like to pass sessionid in my requests to authorize user. Everytime when i refresh my page i get a new user with no products in basket instead of adding products to my actual basket. Even withCredentials dont help. const session = axios.create({ withCredentials: true }); useEffect(() => { const data = { url: "http://127.0.0.1:8000/api/products/2/", quantity: 1, } console.log(data) session.post('http://127.0.0.1:8000/api/basket/add-product/', data) .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log(err) }) }, []); In Postman everything works fine and products are added to correct basket [ { "url": "http://127.0.0.1:8000/api/baskets/77/lines/26/", "product": "http://127.0.0.1:8000/api/products/2/", "quantity": 3, "attributes": [], "price_currency": "PLN", "price_excl_tax": "417.00", "price_incl_tax": "417.00", "price_incl_tax_excl_discounts": "417.00", "price_excl_tax_excl_discounts": "417.00", "is_tax_known": true, "warning": null, "basket": "http://127.0.0.1:8000/api/baskets/77/", "stockrecord": "http://127.0.0.1:8000/api/products/2/stockrecords/1/", "date_created": "2020-05-07T12:00:00.190733Z" } ] -
how to have database relationship with the active data. in django
i have some active and non active data's in EVENT models and active data has the VISITORS form to fill ..so far i have tried OnetoOne relationship but it didn't succeed ..i am getting both active and non active field in VISITORs model..thank you for your time. here is models.py class Event(models.Model): event_id = models.AutoField Event_Name = models.CharField(max_length=50) description = RichTextField() date_And_time = models.DateTimeField() location=models.CharField(max_length=50) slugs = models.SlugField(max_length= 200,default="") picture = models.ImageField(upload_to='wildlife/picture', default="") active = models.BooleanField(default=False) class Meta: ordering = ["date_And_time"] def __str__(self): return self.Event_Name class Eventvisitor(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, related_name="eventvistor",default="") name = models.CharField(max_length=50) email = models.CharField(max_length=70, default="") phone = models.CharField(max_length=20,default="") date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] def __str__(self): return self.email -
Django manager in lookup fields
I have a SoftDeletableModel named Offer: class Offer(SoftDeletableModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='offers') order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='offers') price = models.PositiveIntegerField() I am using below query to get all Orders that current user has an offer in it. Order.objects.filter(offers__user=request.user) but it counts deleted offers in lookup query. for example, if a user delete his offer from an order, this query returns that order too. an other example is something like this: Order.objects.filter(offers=48). offer 48 is removed but i get result from this query too. does django use default manger for lookup fields? -
How to disable "HTML" tab in DRF Browsable API but keep "Raw" tab available
When using more complicated representation schemas (e.g. nested objects and lists), the "HTML" form part of the Browsable API in Django REST Framework becomes mostly unusable. How can I disable it while still keeping the rest of the Browsable API available, including the ability to POST/PUT/PATCH data using the other "Raw" tab? -
how to pass a QuerySet instance to serializer?
I'm using raw sql (using orm is working) for fetching products and i'm getting this error Got AttributeError when attempting to get a value for field `name` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance. Original exception text was: 'tuple' object has no attribute 'name'. This is the get function: def get(self, request, store_id, format=None): with connection.cursor() as cursor: user = request.user check_auth = get_object_or_404( Store, id=store_id, owner_id=user.id) if check_auth != None: connection.cursor() cursor.execute('SELECT * FROM products') products = cursor.fetchall() serializer = ProductSerializer(products, many=True) return Response(serializer.data) raise Http404 and here's the serializer class: class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) category = CategorySerializer() class Meta: model = Product fields = ['id', 'store_id', 'name', 'summary', 'description', 'category', 'main_image', 'price', 'offer_price', 'cost', 'available_quantity'] -
Google Cloud PubSub - How to send multiple arguments to the Cloud Function
I have been using Google Cloud PubSub to trigger Google Cloud Functions. Until this point I have been using a single argument "uuid", now I need to send also development/production flag. Here below is the publisher in Google App Engine/Django: publisher = pubsub_v1.PublisherClient() topic_name = 'projects/project/topics/cloudfunction_topic' message_to_publish = video.uuid publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='') Here below is the subscriber section in GCF: if os.getenv('GCF', None): uuid = base64.b64decode(event['data']).decode('utf-8') How should I change this so there can be multiple arguments (video.uuid, production/development) in the message ?