Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Not Found: /calendar/{'% static 'cal/css/styles.css' %}
I'm trying to make event calendar using django. 404 Not Found error messages appears I tried to switch the file directory and check spelling error but It doesn't work at all To figure it out I've been searching for several hours still stuck in the problem can anybody help me ? Here is base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css"> <link rel="stylesheet" type="text/css" href="{'% static 'cal/css/styles.css' %}"> <title>Django Calendar App</title> </head> <body> {'% block content %} {'% endblock %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {'% block script %} {'% endblock %} </body> </html> display appears when I run server error message I found from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6l5=#1_ur(n*=ctu)*yh3_m62oq%jkpt(+i66s#u@el)xb57*#' # SECURITY WARNING: don't run with debug turned on … -
Customize Django Default Login Form
I'm creating a login page using Django auth and struggling to understand how to customize the form fields generated by the form.as_p method. login.html <form method="post"> {% csrf_token %} {{ form.as_p }} <div class="text-center mt-3"> <button class="btn btn-lg btn-primary" type="submit">Log In</button> </div> </form> I'm looking for the rendered HTML to be: <div class="mb-3"> <label>Email</label> <input class="form-control form-control-lg" type="email" name="email" placeholder="Enter your email"/> </div> <div class="mb-3"> <label>Password</label> <input class="form-control form-control-lg" type="password" name="password" placeholder="Enter your password"/> <small> <a href="/forgot-password">Forgot password?</a> </small> </div> -
What is the best and future proof language to write a web app today?
Is Django better than Flask and Php nowadays? If not, what front and back end combo should I use? The goal is to make a forum site like reddit -
Multiple lines for TabularInline fields
I'd like to see the child model in the admin page in tabularinline format. The problem is that I have 10 entries in the child model and it goes out of the page if I just use class ChildClassInline(admin.TabularInline): model = MyChildClass I don't want to use the StackedInline because the display format is not as clean as TabularInline. Could you please help me out with this? -
Django copy value from one field to another
Please tell me how can I copy value from one field to another. Please look on this example: class MyImage(models.Model): name = models.CharField(max_length=128, blank=False) width = models.PositiveIntegerField(blank=False) ---> height = models.PositiveIntegerField(blank=False) ---> new_image = ProcessedImageField(processors=[ResizeToFill(500, 500)], <--- format='JPEG', options={'quality': 60}) I have to to swap first 500 into value from variable width and and second 500 into variable height. Thanks in advance! :) -
Django: make list_display different from the actual variable
So I have a django model called clown: And I make the list of attributes show up in Django admin like this: How do I make it so that the list in the Django Admin UI is different from the actual variable? Like let's say the variable is identification and I want it to show up as id in the administration. -
Filter fields queryset in Django ModelChoiceField with external reference keys
The Trim inherited the Car and the TrimType, and the TrimType inherited the Car. When creating Trim on a specific Car detail page, I want to filter the queryset of trimType field by the id of the Car. I referred to How to use the request in a ModelForm in Django. My templates/brand/trim_update.html is: # trim_update.html {% extends 'base.html' %} {% block content %} <div class="container"> <h5 class="my-3 border-bottom pb-2">New Trim</h5> <form method="post" class="post-form my-3" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Save</button> </form> </div> {% endblock %} and brand/models.py is: # models.py class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) image = models.ImageField(default=None, null=True, upload_to='car/%Y/%m/%d/') order = models.IntegerField(default=0) def __str__(self): return self.name class TrimType(models.Model): car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True) typeName = models.CharField(max_length=50, blank=False, ull=False) def __str__(self): return self.typeName class Trim(models.Model): id = models.AutoField(primary_key=True) order = models.IntegerField(default=0) trimType = models.ForeignKey(TrimType, on_delete=models.SET_NULL, null=True, blank=True) car = models.ForeignKey('Car', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=256, default='') price = models.IntegerField(default=0) image = models.ImageField(default=None, blank=True, null=True, upload_to='trim/%Y/%m/%d/') def __str__(self): if self is not None and self.car is not None: return self.car.name +'-'+self.name else: return '' and brand/views/base_views.py is: # base_views.py def trim_create(request, car_id): if request.method == 'POST': car = get_object_or_404(Car, … -
Django project with PostgreSQL bootstrap gets AssertionError: database connection isn't set to UTC
I am following the notes left by the previous engineer to set up the application on a test virtual machine, and it is a Django project using the PostgreSQL database. At the step of bootstrap, I called command python manage.py bootstrap, and the system gets an error saying AssertionError: database connection isn't set to UTC. Any pointers will be highly appreciated, and please let me know if you need more details. Screenshot of the command line: (python) [application@host api]$ python manage.py bootstrap Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/data/application/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/data/application/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data/application/python/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/data/application/python/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/data/application/api/applicationbenefitsapp/management/commands/bootstrap.py", line 183, in handle populate_response_statuses() File "/data/application/api/applicationbenefitsapp/management/commands/bootstrap.py", line 51, in populate_response_statuses etransfer_type = Lookup.objects.filter(desc=transfer_type).first() File "/data/application/python/lib/python3.8/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File "/data/application/python/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/data/application/python/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/data/application/python/lib/python3.8/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/data/application/python/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1133, in execute_sql return list(result) File "/data/application/python/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1512, in cursor_iter for rows in iter((lambda: … -
Adding a form to formset's child elements
I have a Message form, with basic fields: class MessageForm(forms.ModelForm): class Meta: model = Message fields = [ 'message_introduction', 'recipient', 'sender' ] labels = { 'message_introduction': 'message_introduction', 'recipient':'recipient', 'sender':'sender', } Each message can contain multiple question by formset: class Message_questionForm(forms.ModelForm): class Meta: model = Message_question fields = ['message_question', 'recipient', 'sender' ] widgets = { 'message_question': forms.Textarea(attrs={'class': 'formset-field', 'rows': 4}), } So far it all works well, i am able to call the form in the view and save both models with no problem. I am now looking, in the detail view of each message, to display each question related to the message (that is done), but i would like to also add a way for the recipient to answer the question. I have created my model: class Question_answer(models.Model): message_question = models.ForeignKey(Message_question, related_name="question_answers", on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) question_answer = models.TextField() recipient = models.CharField(blank=True, null=True, max_length=255) sender = models.CharField(blank=True, null=True, max_length=255) def __str__(self): return self.question_answer class Meta: db_table = 'question_answers' But from here I am not sure how to proceed in the viewz.py and in the actual template. Would someone know a way to put an answer field in front of each question please ? -
Is there a way to verify google play purchases without oauth2?
I've been building a flutter app that communicates with a Django rest API server. Recently I added a subscription service into the app and I have the ability to perform the purchases on both platforms and able to verify them server-side for the Apple AppStore. However, I am having a bit of trouble trying to do the same with the play store API's. I want to know if there is a way to use this endpoint without Oauth2? I don't have /need sign in with google in the app and I would like to avoid it if possible.I've tried using some of the solutions from this post but I think they may be out dated since they are from 2018. -
How to implement python code in an HTML file in Django
I have written a python file using selenium that scrapes news headlines. Now I would like those headlines to be displayed on a website in Django. Hence I was wondering how to implement this into the corresponding HTML file? Thanks in advance! -
Why would a website want to prevent user to cache?
I found this question in StackOverFlow and I can't understand the reason of not caching. I am very new to web programming so i would be glad if someone can answer me this. -
Django Elasticsearch, icontains and multiple words: smart searching
I wrote something like that. reg = f".*{query}.*" return ProductDocument.search().filter( Q("regexp", title=reg) | Q("regexp", slug=reg) ).to_queryset() 1 problem. It can't search for multiple words: 'macbook pro'. after inserting the space symbol it doesnt return anything 2 problem. How I can improve the searching, now i can write only "icontaints" queries, but I need to search for "redt fox" and get "red foxes" for example. Documents: @registry.register_document class ProductDocument(Document): class Index: name = 'products' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product fields = ['title', 'slug'] -
Google oAuth 2.0 API Authentication Error: Error 400 - redirect_uri_mismatch (does not comply with policy) DJANGO APP
I am trying to get my google authentication working on a Django app that is requesting Gmail and Calendar data. I have set up the oAuth API in the Google developer console and linked it with my project, and I've triple-checked that my redirect URI perfectly matches that in the code (No errors with HTTP vs. HTTPS nor any inconsistencies with the slashes). I made sure that my key, secret key, ClientID, and Client Secret are all configured and identical in my Django app's admin page. I have followed many youtube tutorials and searched other questions on stack overflow but Authentication is still not working. I am getting an Error 400: redirect_uri_mismatch. Even though I have checked many times to confirm that they are the same. From all the tutorials, I have learned that there are two main origins for this error: Server sided (can be fixed in the cloud hosting developer console) Client sided (can be fixed by altering the code) Both of these errors have their own individualized messages saying what type of mismatch it is. Mine, however, says this: You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. \n\nIf you're … -
I had "login() missing 1 required positional argument: 'user'" error and its not actually missing
I checked every login func but im still having that error. I'll leave my codes below My views.py codes: def loginUser(request): form = LoginForm(request.POST or None) context = { "form":form } if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is None: messages.warning(request, "Kullanıcı Adı veya Parola Bilgileriniz Hatalı!") return render(request, "login.html", context) login(user) return redirect("index") return render(request, "login.html", context) My urls.py codes: urlpatterns = [ path('register/', register, name= "register"), path('login/', loginUser, name= "loginUser"), path('logout/', logoutUser, name="logoutUser"), ] I can't see a problem about coding all that references are matching. I restarted the server many times and it didn't solve. I can't understand that. -
Django rest framework user registration : Update django user database after the email verification is done
I am trying to register the user by sending an OTP to their mail. Consider the following usual: the user posts a request for registration with an email, password. (email mapped to the username of Django). Django creates the user and the user gets the OTP for verification. If the user verifies, an 'is_verified' field will be set to true. Now, If the user doesn't verify himself with the OTP, I can't get around the following issues. Please suggest a workaround. ---> Any other user can now not use the same email for registration, as email already exists in the database. I want the user to be updated in the database only after the user has successfully verified the otp. -
How to make a Vanilla JS XMLHttpRequest (Wordpress site)
I'm new to wordpress and I'm trying to convert a Django project to wordpress. I have a script.js file that has the XMLHttpRequest function saveInfo() { let request = new XMLHttpRequest(); request.open('POST', '/save/'); let csrf = get_csrf(); request.setRequestHeader('X-CSRFToken', csrf); request.onreadystatechange = () => { if (request.readyState === 4 && request.status == 200) { console.log(JSON.parse(request.responseText)) } } request.send(JSON.stringify(datos)); } Then Django takes the data from that request, saves it to a database and send an email message also with that data: def saveToDB(request): if request.method == "POST": body = request.body.decode('utf-8') body = json.loads(body) client = Client( email=body['email'], edad=body['edad'], ) response = client.save() subject = 'Nueva suscripción a TuKeto' message = 'Email: ' + body['email'] + body['altura'] sendEmail = EmailMessage( subject, message, 'example@gmail.com', ['example@gmail.com'], reply_to=[body['email']], ) status = sendEmail.send() return HttpResponse("SAVED") I have found examples in jquery but they are incomplete and I don't know how to connect the ajax to the wordpress back end. An example of how to make this request with vanilla js and the configuration of the wordpress back end would be very useful. Thanks in advance. -
Using sessions and login() in Django
Session is a piece of info stored in database, can be file-based or cache, and login() stores the data('user id') in session(from Doc). So, Can i retrieve the info saved by login in session,just like doing it with sessions? If yes, then is there any way to override the login to retrieve it? . request.sessions['userid']=request.POST['userid] . user = authenticate(request, username=username, password=password) login(request,user) -
Counting number of object visits per day in django
I have a model like below class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField() Each time an object is viewed, the count attribute will increase by 1. My problem is how to find the number of times an object was hit per day. How can I achieve this. The Stamping is another model with created_at and updated_at -
Django how to track each models fields when it was last updated? or is it possible to use autonow in boolean or char fields?
I have a model name CustomerProject and I want to track individually few fields when it was last updated. Right now I am using auto_now= True in datetime fields which can tell me when the whole model was last edited but I want to track individually few boolean fields such as when the work started? when the work delivered etc. here is my models.py class CustomerProject(models.Model): project_title = models.CharField(max_length=2000,blank=True,null=True) project_updated_at = models.DateTimeField(auto_now= True,blank=True,null=True) #I want to track separately those BooleanField project_started = models.BooleanField(default=True) wting_for_sample_work = models.BooleanField(default=False) sample_work_done = models.BooleanField(default=False) working_on_final_project = models.BooleanField(default=False) project_deliverd = models.BooleanField(default=False) project_closed = models.BooleanField(default=False) -
Nested List within Bootstrap 4
I have a table with the following information: Name | Address John | 6432 Newcastle Way Rob | 893 Lake Point St Rob | 1900 Harbor Lane Rob | 124 Marginal St I am trying to create a nested list... That is, to show two total rows (one for John, one for Rob) and within the row, have another list showing each distinct Address (so Rob has 3 lines within his row). This output is not giving me unique values and is not grouping them... any ideas how to tweak this or any walkthroughs I can find? Views.py from django.http import HttpResponse from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Book class BookList(ListView): queryset = Book.objects.all().distinct('name') HTML Try 1 <ul class="list-group"> {% for book in object_list %} <li style="margin-bottom: 25px;"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{ book.name }}</h5> <h6 class="card-subtitle mb-2 text-muted">{{ book.address }}</h6> <a href="{% url 'books_cbv:book_edit' book.id %}">Edit</a> <a href="{% url 'books_cbv:book_delete' book.id %}">Delete</a> </div> </div> </li> {% endfor %} </ul> HTML Try 2 <table> {% for book in object_list %} <li>{{ book.name }} <li> {{ book.address }} </li> </li> {% endfor %} </table> -
AttributeError: module 'student.models' has no attribute 'ManyToManyField'
I'm using the below models: models.py class Student(models.Model): name = models.CharField(max_length = 200) country = models.ManyToManyField(Country, null = True,blank=True) class Country(models.Model): title = models.CharField(max_length = 100, null = True) def __str__(self): return self.title admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } I get this error: AttributeError: module 'student.models' has no attribute 'ManyToManyField' -
How to use @font-face with production Django on Digital Ocean?
I can't seem to access my static fonts using @font-face CSS property with the font stored on digital ocean spaces. All my other static items work in the html section. For example, I can do: {% load static %} <div class = "statusImg"><img id = '{{machine.id}}simLight' src="{% static 'images/simLight_off.png' %}"></div> And this will work as expected, bringing in the image from digital ocean. I am not sure how to do this in <style> section though? I tried: <style> @font-face { font-family: PSSroboto; src: url("/static/fonts/roboto/Roboto-Regular.ttf") } </style> and: <style> @font-face { font-family: PSSroboto; src: url({% static '/static/fonts/roboto/Roboto-Regular.ttf' %}) } </style> and: <style> @font-face { font-family: PSSroboto; src: "{% static '/static/fonts/roboto/Roboto-Regular.ttf' %}" } </style> I even hardcoded the URL and made the font public, but this resulted in a CORS policy violation, and in general, probably isn't a great idea anyway. I am hoping it is something small I am missing? Thanks! -
DJango forms: A dynamic integer model choice field always fails form.has_changed()
So I have a list of items, with an integer associated with each values: e.g. CAKE = 1 CHOC = 2 CHIPS = 3 A model with a field foo uses these values as its field, so the model's field is an integer field. This choice selection is not fixed, its dynamic at the point of render. In order to get create a dynamic choice field for an integer field, after much trial and error I eventually got the following solution: class FooForm(forms.ModelForm): def __init__(self, *args, foo_choices, **kwargs): super().__init__(*args, **kwargs) self.fields['foo'].choices = foo_choices def clean_foo(self): foo = int(self.cleaned_data['foo']) return foo class Meta: model = Foo field_classes = { 'foo': forms.ChoiceField, } widgets = { 'property_id': forms.Select(), } All is good, except when i call form.has_changed, the only field which incorrectly reports has changed is 'foo'. The default to_python for a choice field is: def to_python(self, value): """Return a string.""" if value in self.empty_values: return '' return str(value) As you can see the value is always a string. This is fine, because my clean then changes it to an int. However the problem with the has_changed method, is that it checks whether it has changed as follows: if field.has_changed(initial_value, data_value): Where … -
How to implement HATEOS-style links with Django REST framework's ModelViewSets?
I have this product model import uuid from django.db import models class Product(models.Model): """Product in the store.""" title = models.CharField(max_length=120) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=10) inventory = models.IntegerField(default=0) uuid = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): return f'{self.title}' and I defined a serializer for it from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['title', 'description', 'price', 'inventory', 'uuid'] and this is my view from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'uuid' To start the question, just keep in mind that this view is routed on /store/products/. Now, for example I can do GET http://localhost/store/products/ and it returns [ { "title": "Computer", "description": "", "price": "50.00", "inventory": 10, "uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2" } ] but I would like it to return something like [ { "href": "http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2" } ] and then have http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2 return { "title": "Computer", "description": "", "price": "50.00", "inventory": 10, "uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2" } as it already does. Is this possible using the build-in serialization, or how can I define one that does this? I've played around with the list_serializer_class property but I can't get anything working.