Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to redirect to certain page
I am using Django's built in auth to login. Every time I input 'http://127.0.0.1:8000/' it is redirected to 'http://127.0.0.1:8000/admin/login/?next=/admin/'. After successfully login I want to redirect to 'http://127.0.0.1:8000/index' again. Here is what I have done: in settings.py LOGIN_REDIRECT_URL = '/index' in urls.py urlpatterns = [path('index', views.index),] It doesn't work. I have tried many ways and I think this setting might be override by the '?next=/admin/' in 'http://127.0.0.1:8000/admin/login/?next=/admin/' So how can I really do it? -
Django Modal for User Login with AJAX doesn't POST sucessfully
Django 3 / AJAX / Jquery I'm trying to set up a login modal when the user clicks on a save button and isn't logged in yet. I'm following pretty much from here Django Modal For User Login/Register - Form Render Issue To set up a login modal on the homepage. My modal loads when it's supposed, and the login form renders. But I'm stuck after getting the POST 200 from the server but not login in. Nothing happens. I don't understand if I need a different URL for the POST. As far as I understand, I'm posting my form on the same home template, from Django default auth, so everything occurs on the 'home' view. But I might be mistaken here. I can login from the default /login/ page, which renders the default /registration/login.html template just fine. So there isn't a problem on the login per se. It must be something on the form posting. views.py: def home(request): wishlisted_list =[] produtos = Produto.objects.all() paginator = Paginator (produtos, 6) page = request.GET.get('page') signup_form = UserCreationForm() login_form = AuthenticationForm() if request.user.is_authenticated: wishlisted_list = list(Wishlist.objects.filter(user_id=request.user).values_list('produto_id',flat=True).order_by('produto_id')) try: produtos = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver 1st Page produtos … -
Django Field 'fk_a_view' has column name 'fk_a' that is used by another field
I have a these unmanaged django models: class Ticket(models.Model): fk_a = models.ForeignKey('FK_A', db_column='fk_a') fk_a_view = models.ForeignKey('FK_A_View', db_column='fk_a') class Meta: managed = False db_table = 'ticket' class FK_A(models.Model): ... class Meta: managed = False db_table = 'fk_a' class FK_A_View(models.Model): ... class Meta: managed = False db_table = 'view_fk_a' As you can see I have 2 FK point to the same column, and django is complaining I cannot have 2 fields point to the same column. How do I get around this? -
Django change IntegerField to DecimalField on inherited model
In Django I have 2 models that are inherited from an abstract base class. The base class has an IntegerField that I want to rename and change to DecimalField for some instances. There is a ForeignKey linking the 2 child models. I've read about model inheritance in docs, but there seems to be some constraints. What's the best way to change the IntegerField to DecimalField? class Parent(models.Model): intfield = models.IntegerField() class Meta: abstract=True class Child1(Parent): addedfield = models.CharField(max_length=20) class Child2(Parent): addedfield2 = models.DecimalField(max_digits=10, decimal_places=2) linked = models.ForeignKey(Child1, on_delete=models.CASCADE) class GrandChild1(Child1): # change intfield to decimal class GrandChild2(Child2): # change intfield to decimal # linked to GrandChild1 instead of Child1 -
Check if person's id exists in a function's dictionary
I have this code to check if a person exists given their id. If they do exist, it has to print the name and last name. If they don't exists, it has to print some error. The thing is, my code only prints the error even though I tried the code with a number I know corresponds to an existing person. How do I fix that? This is my view: from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from .forms import MonotributoForm from app.ws_sr_padron import get_persona class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): form = MonotributoForm(request.POST) try: cuit_r = int(request.POST.get('cuit', '-1')) # Get 'cuit' with default of -1 except ValueError: pass response= get_persona(cuit_r) if response is True: print(response["persona"]['name']) print(response['persona']['lastname']) else: print("cuit doesn't exist") if form.is_valid(): cuit = form.cleaned_data.get('cuit') email = form.cleaned_data.get('email') cuit.save() email.save() return HttpResponseRedirect('app/constancia-inscripcion.html') return render(request, 'app/constancia-inscripcion.html') -
How to fetch data from an api and display it in a detail page dynamically using id in django
I am trying to display dev.to articles on my website using their api and I have been able to do that but the problem is that I can't query the article by ID so that when someone clicks read more link, they are redirected to the detail page of the article where they can read the body of the article they have clicked the read more link. Here is my views.py page of the article page. def blog(request): API_KEY = 'My_Api_Key' url = 'https://dev.to/api/articles/me/published' headers = {'api-key': API_KEY} response = requests.get(url, headers=headers) articles = response.json() return render (request, "blog.html", {"articles": articles}) Here is my views.py page of the article detail page. def blogBody(request, blog): id = {'id'} API_KEY = 'My_Api_Key' url = 'https://dev.to/api/articles/me/published' headers = {'api-key': API_KEY} response = requests.get(url, headers=headers, params=id) blog = response.json() return render (request, "blogBody.html", {"blog": blog}) Here is is the urls.py urlpatterns = [ path("blog", blog, name="blog"), path("blog/<int:blog>", blogBody, name="article"), ] Here is the article template: {% for article in articles %} <div class="blog-item padd-15"> <div class="blog-item__inner"> <div class="blog-item__inner__img"> <img src="{{article.cover_image}}" alt=""> </div> <div class="blog-item__inner__info"> <h4 class="blog-title">{{article.title}}</h4> <p class="blog-desc">{{article.description}}</p> <p class="blog-tags"> <a href="{% url 'article' article.id %}">Read More...</a> </p> </div> </div> </div> {% endfor %} … -
How to annotate queryset if object in ManyToManyField
I am trying to build a small social network where users can like posts. I am using Django 3.1.7. I have defined my model for the post as follows: class Post(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=240, blank=False, default=None) user_like = models.ManyToManyField(User, blank=True, related_name='likes') def __str__(self): return f'{self.user.username} posted \"{self.content}\" on {self.date_published}' From my views.py I want to return the posts with an annotation of whether the current user has liked a given post. I am trying as follows: def index(request): posts = Post.objects.all().annotate( likes=Count('user_like')).order_by('-date_published') if request.user.is_authenticated: posts = Post.objects.all().annotate( likes=Count('user_like'), liked=request.user in 'user_like'.all).order_by('-date_published') paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { 'post_form': PostForm(), 'page_obj': page_obj }) But unfortunately, I can not make the query work. I assume that the part where I check if the user is in the relationship is wrong (liked=request.user in 'user_like'.all) as it is treating 'user_like' as str and not as the field in the Post. How should I annotate the posts to include whether the user has liked them or not based on the ManyToManyField between them? Thanks -
Creating a Dynamic Form in Django
i'm currently working on a project that would have a database of reports of a scam. In the report section of the website I have a form, but I want anyone to be able to add multiple profiles with a click of a button. For example: Nickname field: xyz Steam profile: x [ + ] <- button for adding more profiles, which when pressed would look something like this: Nickname field: xyz Steam profile: x Steam profile 2: y [ Delete ] [ + ] I was looking into FormSets and Inline Formsets, but nothing turned up that would match this specific need, aswell as did not answer the question regarding storing the results of the form. How would I go about creating the form for this? How would I store the multiple results of Steam profile to my object that has a steam_profile = models.CharField? My current model: class Scammer(models.Model): #Basic information for display steam_id_64 = models.CharField(max_length=17, default='00000000000000000') nickname = models.CharField(max_length=64, default='Nickname') steam_profile = models.CharField(max_length=512, default='https://www.steamcommunity.com') description = models.TextField(default='') proof = models.TextField(default='') #Date created var for ordering date_created = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return self.nickname def get_absolute_url(self): return reverse('dashboard-home') My view: class ScammerCreateView(CreateView): model = Scammer_Unapproved template_name='dashboard/report.html' fields = … -
Django User Table having two types with the same data
Im using django with rest-framework and Postgresql. In designing my models, I have an interesting use-case for the User model (the model used for authentication). In my application, a User can either be a customer, or an employee. They both log in and have different permissions. The catch is that sometimes an employee needs to create a User as a customer (as one of their customers), and that new User cannot log in. It is just to be able to track that particular employee's customers. So to clarify, there are two types of customers, those that can log in, and those who cannot. Other than authentication, they are stored with the same data. Is there a good way to implement this, potentially with class inheritance, to allow that separation between customers? or is the correct implementation to just create a User with no permissions to anything? The reason I would like them in the same table is because in the system they are treated the same. For example, if an Employee is doing a Project for a Customer, the Foreign key on that project table needs to be connected to a Customer (though it could be either type of Customer). -
Python cant loop over class?
Am trying to loop over a list in django forms to create a choice field form. That question and options from django import forms y=[[('2','2'),('3', '3')],[('5','5'),('4', '4')]] question = [ '1+1', '2+2'] class ContactForm(forms.Form): n=0 for i in question: i = forms.ChoiceField(widget = forms.RadioSelect, choices = y[n] ) n+=1 it only shows i. 4 5 instead of 1+1 2 3 2+2 5 4 -
How to pass input as argument of a function?
So I need my function to use user's input but when I try to configure it that way, it says the id is missing (the id is the number the person writes in the input). This is not working the way it's supposed to (the numbers are not passed to the get_person function): cuit_r = request.POST.get('cuit') This is the error: Error: Missing element idPersona (getPersona.idPersona) What am I doing wrong? This is my view: from django.shortcuts import render, HttpResponse import requests from django.views import View from .forms import MonotributoForm from app.ws_sr_padron import get_persona class ConstanciaInscripcion(View): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): if request: form = MonotributoForm(request.POST) cuit_r = request.POST.get('cuit') response=get_persona(cuit_r) if response is True: print(response["persona"]['nombre']) print(response['persona']['apellido']) else: print("cuit ingresado no existe") if form.is_valid(): cuit = form.cleaned_data.get('cuit') email = form.cleaned_data.get('email') cuit.save() email.save() return HttpResponseRedirect('app/constancia-inscripcion.html') else: pass return render(request, 'app/constancia-inscripcion.html') This is my form: from django import forms from .models import Monotributo class MonotributoForm(forms.ModelForm): class Meta: model = Monotributo fields = ['cuit','email'] -
Send extra parameter to django routes in include
It is some way to send extra parameters to all routes in a include ? I'm doing this and works: path('<str:lang>/auth/', include('apps.auth.routes'), {'lang': 'en'}, name='auth_routes') but I want to send lang string on that parameter, something like this: path('<str:lang>/auth/', include('apps.auth.routes'), {'lang': lang}, name='auth_routes') What do I have to do to fix that ? -
Heroku Static Files on Dyno
I am running a django application on Heroku, and currently using AWS S3 to serve my static files. We store our static files both in static folders per app, and also in a static/ folder at the root of the directory. The static/ folder at the root is about 40Mb large. Whenever we deploy our app to Heroku, the static files are included in the Heroku slug, so that heroku run python manage.py collectstatic --no-input can be run from the Dyno itself, which then copies any changed/new static files to our S3 bucket so that they can be served. The issue is after we go through this process, we now have a static/ folder on the Dyno which takes up about 40Mb of space, and is seemingly useless since our files are being served from our S3 bucket! Is there a better way to go about deploying our application, and collecting our static files to our S3 bucket but not copying the static files to Heroku? One way I was thinking was to add all static files to Heroku's .slugignore file, and then configure a way to upload static files to our S3 bucket without using Heroku at all. I'm … -
How do I reference a local media file in a Django template
I have set up my media root, media url etc. so the file will show up when I call http://127.0.0.1:8000/media/something/somewhere/my_pdf.pdf Now I want to show the same file within a template (i.e. the PDF in an object or embed tag plus some other stuff. I pass the path to the file (i.e. everything after 'media' in the view context, something like: def test_doc(request):` p = r'something/somewhere/my_pdf.pdf'` return render(request, 'documents/test.html', {'pdf':p}) So what do I have to put in my template? I tried <object data="{{ MEDIA_URL }}{{ pdf }}">something</object> and many many variations thereof. What am I doing wrong? -
Django Render To String for html email template not working
I am trying to send a stylized email to a new customer once they submit a payment on my website. I read somewhere to try the render to string method which I did. The email triggers correctly, the only problem is that it doesn't seem to be using the email template. It's a basic plain text email. Please see my code below. Any help on how to make this work would be great. notice_html = render_to_string('MY_app/email-template.html') subject = 'Your New Design Confirmation' from_email = settings.EMAIL_HOST_USER recipient_list = [request.POST.get('email')] message = "A curated message based on the design the customer purchased." send_mail(subject=subject, message=message, recipient_list=recipient_list, from_email=from_email, fail_silently=False) -
pre-display and post-edit follow-up methods in Django Generic Views
I need to alter or at least check the ranking values in a Player class whenever a list of those players is displayed using ListView. I also want to check the list whenever the availability status of a Player instance has changed (for example, a player may become unavailable, and so his ranking would would go to -1 or 999, and the ordering of all the other players would have to be changed). I would also have to reorder players whenever a player is deleted. I have basic CRUD views and templates already set up. I also know how to code the methods to do what I want. I'm guessing I have to override a number of methods that are not shown in standard tutorials, but I didn't find an obvious answer as to where in either the Django docs or the tutorials I have read. What can you override? before ListView is displayed? after a DeleteView "delete" button has been pressed? after an UpdateView "update" button has been pressed? -
How to check if an objects attribute is given?
I am trying to make a little website with django when I ran into a problem: I have a site where I want to look at a post in detail, but not every post has an image attribute - so I am getting an error when I try to display images, since some arent existent. So the solution would be to check if an image is given, but... How do I do that? I tried something like this but it did not work: </div> <p>{{ object.content }}</p> {% if object.image.url == True %} <!-- In no case an image is displayed --> <p> <img src="{{ object.image.url }}"> </p> {% endif %} </div> -
How to set up Varnish caching for GraphQL in Django
Here is my django-benchmark project in which I implemented simple REST API and GraphQL endpoints. In front of my application I put Varnish for caching. Caching works well for Rest HTTP endpoints and does not work for GraphQL here is my Varnish configuration. What am I doing wrong? vcl 4.1; # Default backend definition. Set this to point to your content server. backend default { .host = "0.0.0.0"; .port = "8080"; } sub vcl_hash { # For multi site configurations to not cache each other's content if (req.http.host) { hash_data(req.http.host); } else { hash_data(server.ip); } if (req.url ~ "/api/graphql") { call process_graphql_headers; } } sub process_graphql_headers { if (req.http.Store) { hash_data(req.http.Store); } if (req.http.Content-Currency) { hash_data(req.http.Content-Currency); } } sub vcl_recv { # Authenticated requests should not be cached by default if (req.http.Authorization ~ "^Bearer") { return (pass); } } sub vcl_backend_response { } sub vcl_deliver { } -
How can I optimize queries django
I have a function for getting a dictionary of country names as keys and their cities' names as values. Here is what i did which does not look to be the best way to do it. I am using debugging toolbar that shows 30 sql queries are made for getting this. How should i do it the right way? #models.py class City(models.Model): ci_id = models.AutoField(primary_key=True) ci_name = models.CharField(max_length=50, blank=True, null=True) country_co = models.ForeignKey('Country', on_delete=models.CASCADE, null=False) class Country(models.Model): co_id = models.AutoField(primary_key=True) co_name = models.CharField(max_length=50, blank=True, null=True) #views.py def get_country_city(): city_dict={} countries = Country.objects.all() for country in countries: c_list =[] cities = City.objects.filter(country_co__co_id=country.co_id) for city in cities: c_list.append(city.ci_name) city_dict[country.co_name] = c_list return city_dict -
Field 'id' expected a number but got 'bidding'
I'm building a html page from a model. Added to the page is a a form that somehow seems to interfere with the model I'm using to build the page. I get this error message: Exception Type: ValueError at /bidding Exception Value: Field 'id' expected a number but got 'bidding'. HTML (listing.html) {% extends "auctions/layout.html" %} {% block body %} <h3>{{listing.0.listingName}}</h3> <p><img class="listingImage" src="{{listing.0.listingImage}}"></p> <p>{{listing.0.listingDesc}}</p> <h5>Price: $ TODO</h5> {% if user.is_authenticated %} <form action="{% url 'bidding' %}" method="POST"> {% csrf_token %} <input type="number" name="amount" placeholder="Bid"> <input class="btn btn-primary" type="submit" value="Bid"> </form> {% endif %} <h5>Details</h5> <ul> <li>Listed by: {{listing.0.listingPoster}}</li> <li>Category: {{listing.0.listingCategory}}</li> </ul> <p>Comments:</p> <p>TODO</p> {% endblock %} Views.py def listing(request, listing): return render(request, "auctions/listing.html",{ "listing" : Listing.objects.filter(id=listing) }) def bidding(request): if request.method == "POST": bidAmount = int(request.POST["amount"]) ### logic comes here return HttpResponseRedirect(reverse("listing"), args=5 ) ### args is hardcoded for testing only models.py class Listing(models.Model): CATEGORIES = ( ('fashion','fashion'), ('electronics','electronics'), ('sports','sports'), ('home','home'), ('motors','motors'), ('art','art'), ('business','business'), ('media','media'), ('others','others') ) listingPoster = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Poster") listingName = models.CharField(max_length=128, verbose_name="Auction item") listingDesc = models.TextField(blank=True, verbose_name="Item description") listingActive = models.BooleanField(default=True, verbose_name="Active listing") listingImage = models.URLField(blank=True, verbose_name="Link to image") listingCategory = models.CharField(max_length=64, choices=CATEGORIES, default='others', verbose_name="Category") listingFirstBid = models.DecimalField(max_digits=8, decimal_places=2, default=1.0, verbose_name="Starting bid") listingCreated = models.DateTimeField(auto_now_add=True, … -
django server won't load post request
Django keeps loading website after I make a post request, nothing appears on server and website doesn't respond. It changed when I placed the form validation's place (I placed it inside an if) but I need it to work like that since I only want it to save the cuit_r if it exists. What's going on? my view: from django.shortcuts import render, HttpResponse import requests from django.views import View from .forms import MonotributoForm from app.wadron import get_persona class ConstanciaInscripcion(View): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): if request: form = MonotributoForm(request.POST) cuit_r = int(input()) response=get_persona(cuit_r) if response is True: print(response["persona"]['nombre']) print(response['persona']['apellido']) if form.is_valid(): cuit = form.cleaned_data.get('cuit') email = form.cleaned_data.get('email') cuit.save() email.save() return HttpResponseRedirect('app/constancia-inscripcion.html') else: print("cuit ingresado no existe") else: pass return render(request, 'app/constancia-inscripcion.html') -
Unable to show images on ckeditor
so am trying to add django-ckeditor into my django site. Everything is fine except for the part of uploading images or better saying embeding them. They only show up as a cross, do you know i have messed up? settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "main.apps.MainConfig", 'ckeditor', "ckeditor_uploader",] STATIC_ROOT = "/var/www/mysite/static/" STATIC_URL = "/static/" MEDIA_URL = "/media/" MEDIA_ROOT = '/var/www/mysite/media/' CKEDITOR_UPLOAD_PATH = "uploads/" urls.py from django.conf import settings from django.contrib import admin from django.views.static import serve from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static urlpatterns = [ path('',include("main.urls")), path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to perform translation from RAW SQL to django queryset
I am struggling with conversion to django query having raw sql I am new in django and any help will be appreciated There are simple models: Winemaker - target model Wine Post Winemaker has 1+ Wines Wine has 1+ Posts I know that it should be done with annotations but have no idea how to implement it. select w2.*, (select count(wp.id) from web_winemaker www inner join web_wine ww on www.id = ww.winemaker_id inner join web_post wp on ww.id = wp.wine_id where ww.status=20 and wp.status=20 and www.id = w2.id ) as wineposts_count, ( select count(w.id) from web_winemaker www1 inner join web_wine w on www1.id = w.winemaker_id where w.status=20 and www1.id = w2.id ) as wines_count from web_winemaker w2; -
What is a difference using 'def something(request)' and 'class something(CreateView) in Django views.py?
As above, what is the difference between handling views like def something(request): a = b.object.get() context = { 'a' : a, } return render(request, 'template.html', context) and class something(CreateView): model = Model template_name = 'template.html' When I see tutorials, some use first, and some use second option. Which one is useful where and why? -
DJONGO text search on a JSON field
I have a model that contains a JSONField "cust_details" which contains a key "DOB" and I want to search a substring of that field to check if the DOB contains the day and month of datetime.today(). I tried the following queries Cust.objects.filter(name = 'Albert', cust_details = {"DOB" :"/10-02/"}) Cust.objects.filter(name = 'Albert', cust_details__DOB__icontains = "10-02") throws Unsupported lookup 'DOB' for JSONField or join on the field not permitted. The nedis documentation says that I can use pymongo with the package, is there anyway to achieve this with pymongo like Cust.objects.mongo_find()[throws "Manager' object has no attribute 'mongo_find'"]. I must be doing something wrong. Please help.