Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to manually render each field of a form on a bootstrap template?
I've found this nice bootstrap template online and I want to use it as my template for updating a user profile, I have tried several methods I've found in here and also in youtube, but I still couldn't get it to work. Not only does the form isn't rendering, the updated profile is not being saved also when I click update. Could someone help me out what is the problem? and I do apologize in advance if I'm not making sense as english is my second langauge. here is my view for profile update, I did not create a form for it as I've read online that I do not need to create a form for it to work, just need the model. class TutorProfileUpdateView(UpdateView): model = User fields = ['first_name', 'last_name', 'email', 'phone number', 'current_address', 'image', 'bio'] template_name = 'account/tutor_dashboard.html' success_url = reverse_lazy('tutor-dashboard') def form_valid(self, form): fm = form.save(commit=False) fm.user = self.request.user fm.save() messages.success(self.request, f'Profile Updated!') return HttpResponseRedirect(self.get_success_url()) and here is some part of the template, I will not paste it all here as it is too long. <form method="POST"> {% csrf_token%} <div class="card h-100"> <div class="card-body"> <div class="row gutters"> <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12"> <h6 class="mb-2 text-primary">Personal … -
Django - Best practice for running (switching) dev/debug/product mode?
In my source (using Docker), there is a database and my django code. docker-compose.yml services: app: db: When I debug locally, I usually delete the database in Docker-compose to prevent it creating a new database locally. Then I change the settings in django source to connect to the database of the server settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 123.231.***, 'NAME': db***, 'USER': ****, 'PASSWORD': **** } } or When I develop a new feature, I would prefer to create a database locally to test things our rather than connect directly to the server database. Well, my question is that how to set things up so we can easily switch between dev/ prod/ debug mode. In my thought, it should be easy like commanding: python manage.py run dev-mode -
Serving media files in Django , gunicorn and nginx
I have deployed my Full Stack application using Django and React using nginx on AWS . All the files including static files are being served as expected but I am unable to serve media files present in the /home/user/backend/media/images/ directory . My directory structure looks as follows /home/user/backend/media/images/image1.jpg, /home/user/backend/media/images/image2.jpg etc. In development (manage.py runserver) mode I am able to access my files using http://localhost:8000/media/images/image1.jpg . here is my Nginx configuration file : server { listen 80; server_name xxxxxxxxx; root /home/user/frontend/build; index index.html; location / { root /home/user/frontend/build; try_files $uri /index.html; } location = /favicon.ico { access_log off; log_not_found off; } location /django_static/ { root /home/user/backend; } location /media/images/ { include /etc/nginx/mime.types; root /home/user/backend; } location /api/{ proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/user/backend/backend.sock; } } Here is my media settings in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/',include('api.urls'))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also when i try to access the files using http://server/media/images/image1.jpg the browser just times out and i get no response , so I nothing is logged in /var/log/nginx/error.log . This is my first deployment so any help is … -
DRF: how to mix model fields directly inside a serializer
Suppose I have class Model1(models.Model) first_name = models.CharField(_('first name'), max_length=150, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) class Model2(models.Model): location = models.TextField() phone = models.CharField(max_length=15) I want to create a serializer using these fields. This has nothing to do with the models or the POST transaction. Just i want to use the definition of the models class CombinedSerializer(serializer.ModelSerializer): class Meta: model = Model1 fields = ['first_name'] model = Model2 fields = ['location'] So that i dont have to define them again. -
Dango rest framework: mixing some fields of one model with another and make a serializer
I have the User model and UserProfile model. User model contains the following: email password first_name last_name and UserProfile model contains class UserProfile(models.Model): user = models.OneToOneField(on_delete=models.CASCADE, primary_key=True) photo = models.ImageField() location = models.TextField() phone = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to create an api endpoint where User can edit the following fields and save after login --> from User first_name last_name --> from Userprofile photo location phone In normal Django forms. I can use multiple forms and validate them and save. User will see them as one form. In serializers how can I do this -
Fixing a type error for xhtm2pdf in a Django Project
I am trying to generate a PDF for my Django Project. I have used pip install xhtml2pdf The PDF was generate with plain text but when I added style in the pdf.html I got this Exception Type: TypeError: '<' not supported between instances of 'int' and 'NoneType' Here is the views.py: def admin_order_pdf(request,info_id): info = get_object_or_404(Info, id=info_id) template_path = 'businessplan/pdf.html' context = {'info': info} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # response['Content-Disposition'] = 'attachment; filename="report.pdf"' response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Info.id) # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response Here is the pdf.html {% load static %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'css/report.css' %}" /> <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">--> <title>{{ info.businessName }}</title> <style> @charset "UTF-8"; @font-face { font-family: Fira Sans; font-weight: 400; src: url('/static/img/FiraSans-Regular.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: 400; src: url('/static/img/FiraSans-Italic.otf'); } @font-face { font-family: Fira Sans; font-weight: 300; src: url('/static/img/FiraSans-Light.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: … -
Django static files not showing
I hav gone through my settings.py file to look at my static file setting STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') but all my static files are nt showing when the page loads. Please what could be going on -
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)