Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My heroku website looks empty and no html files are rendering
I was trying to deploy my django website to heroku. Basically I have done everything step by step and no errors in deploying as well. But there is nothing in my webpage just a side panel is showing nothing else. No navigation bars, no buttons, no html renderings ... nothing. But when I viewed the source code the html codes are there. I can access different urls as well but nothing renders in the webpage its weird really. The website works perfectly in localhost but not in heroku. I need a fix for this, thanks. Here is how the webpage looks right now, enter image description here -
Edit Session Variable in Javascript/JQuery
I have a session variable in my Django views: request.session['count'] = 0 I can access this variable in Javascript and log it to the console easily, but I'm wondering what the best way is to pass an updated version of the variable back to the views? I'd ideally like to edit the value in the Javascript of the HTML template and then have the updated value passed back to the Django view so that it could be called something like so: count=request.body['count'] print(count) I am able to pass the variable via the URL parameters but I am looking for a way to pass the value without modifying the URL if possible. Thanks in advance! -
Can't apply migrations in Django SQLlite memory database
I'm writing some tests, and I want to be able to run django server with my test settings (that's why I'm using in-memory database). It seems to be working, no errors reported when running. But migrations are not applied, I can't perform any action on the database, because model tables do not exist. when I run python manage.py migrate, all my migrations get applied (I see these Applying migrations... OK messages), but it has no effect. When I run python manage.py showmigrations, none of the migrations are applied (I see [ ] 0001_initial etc., without the X). When I go to django shell, I can't perform any action, because table does not exist. Any idea what might be the reason? It works fine with normal, postgres database. My settings: DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'TEST_NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } -
Image not uploading in Django Model
I am able to update the image of each user's profile picture. But not through the code. Though it doesn't give me any error. u_form = For changing the username. p_form = For changing the picture in their profile. NOTE: Profile has one to one relation with the Profile model. settings.py file section: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' models.py for Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpeg', upload_to='profile_pics') status = models.TextField(max_length='200') def __str__(self): return self.user.username forms.py for the same: class ProfileUpdate(forms.ModelForm): class Meta: model = Profile fields = ['image',] Main views.py file: . . from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm as uc from django.contrib.auth.forms import AuthenticationForm as af . . @login_required(login_url='/login') def update_profile(request): user = request.user if request.method == 'POST': u_form = UserUpdate(request.POST, instance=user) p_form = ProfileUpdate(request.POST, request.FILES, instance=user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'The profile has been updated.') return redirect('/profile') else: #instance: to get pre-filled data of user u_form = UserUpdate(instance=user) p_form = ProfileUpdate(instance=user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'update_profile.html', context) HTML form "update_profile.html": <form action="{% url 'update_profile' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form … -
Is there a way to pass the value of a model field as a parameter to models.ImageField(storage=function) within same Model
class StorageModel(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="profile", null=False) file_meta = models.ImageField(storage=UserDataStorage(profile=user), blank=False, null=False) class UserDataStorage(S3Boto3Storage): location = common.AWS_LOCATION_TEST file_overwrite = False def __init__(self, *args, **kwargs): for k, v in kwargs.items(): print("omg") print(v) super(UserDataStorage, self).__init__(*args, **kwargs) How to pass the field user as an argument to the object UserDataStorage? The problem here is, field user gets passed down to UserDataStorage but as a type <django.db.models.fields.related.ForeignKey>. I want a Profile instance here. Is this achieveable in Django? -
Why is it not getting paginated?
I'm trying to develop a website, where I wrote a function based view, and now want to add pagination.I'm following the django documentation, but it's just not coming together. Can anyone help me please? my views.py: from django.shortcuts import render, Http404 from django.http import HttpResponse from .models import Product from django.core.paginator import Paginator def home(request): products = Product.objects.all() paginator = Paginator(products, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'index.html', {'products': products}) -
Auto height paper Reportlab Python (case study about ribbon paper for printing shopping receipts)
How to make height measurements automatically based on content (shopping lists and prices) that will be printed on ribbon paper with a width of 110mm (currently I use that size paper to print - using thermal printer - shopping receipts). The following is a sample code snippet that I have: class TOPDFBarcodeThermal(TOPDF): width = 110 * mm limit = 110 * mm # auto height in here def set_pdf(self): self.pdf = SimpleDocTemplate( self.response, title=self.title, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0, pagesize=(self.width, self.limit) ) On the ribbon paper, I want to make it have a dynamic height that matches the list of items purchased. Are there other easier ways or what? Thank you -
django-cms Documentation: django.urls.exceptions.NoReverseMatch: 'polls' is not a registered namespace
Description Using the tutorial found here: http://docs.django-cms.org/en/latest/introduction/05-apphooks.html. Up to step 5, there has not been any major issue. However, when completing the steps in step 5, the following error appears: django.urls.exceptions.NoReverseMatch: 'polls' is not a registered namespace Screenshot available here: https://imgur.com/6i0hnTG. This is after completing step 5.1.3 Restart the runserver. Steps to reproduce Followed tutorial up to step 5.1.3. Expected behaviour Should not cause 500. Actual behaviour Causes 500. Additional information Any page with the following causes the 500 error to be raised: <form action="{% url 'polls:vote' instance.poll.id %}" method="post"> However, I can also add back to urls.py the following, which fixes the error (although I believe this is not the purpose of the documentation tutorial): url(r'^', include('polls.urls', namespace="polls")), Also have ran into a few other issues in part 4 and part 8 of tutorial. In part 4, there is an on_delete error which is fixed by adding the following argument to models.ForeignKey function call: poll = models.ForeignKey(Poll, on_delete=models.CASCADE) Environment: Python version: 3.7.6 (tutorial recommends 3.6) Django version: 2.2.11 django CMS version: 3.7.1 -
Why can't Django model object be added to a list?
I'm trying to add an instance of a model in Django to a list and get these results (from Shell): Import the model and instantiate an object >>> from base.models import Service >>> s = Service.objects.first() Check the type of the object >>> type(s) <class 'base.models.Service'> Instantiate the list >>> mylist = [] Try to add the model object to the list >>> mylist += s Error Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'Service' object is not iterable Why exactly can I not add a model instance to the list? -
Failed to load resource: the server responded with a status of 403 (Forbidden)?
i am posting javascript localstorage object to backend(django). I am passing it through ajax. this is the code in frontend. function checkout_(){ console.log("checkout"); for(v in list1){ object=Object.values(localStorage)[v]; object = JSON.parse(object) } //ajax here console.log(object.length); $.ajax({ url: '{% url "chout" %}', data: { 'object': object }, method: "POST", dataType: 'json', success: function (data) { alert("success"); } }); i have given this function to a button via onclick. <button class="bg-danger text-white " onclick="checkout_()">Go To Checkout Counter</button> when i click on this button this error "Failed to load resource: the server responded with a status of 403 (Forbidden)" happens. in the views.py this is the code. views.py def checkoutnow(request): return render(request, "mart/checkout.html") I hope this detail is enough to explain the problem..Thankyou -
Django Rest join models on multiple field
I have two models as below. These models store budget sales data and actual sales data for each project by each month. # To test join on multiple keys class ActualSales(models.Model): time_id = models.CharField(max_length=8) project = models.CharField(max_length=100) actual_sales = models.DecimalField(max_digits=20, decimal_places=3) adjustment = models.DecimalField(max_digits=20, decimal_places=3) class BudgetSales(models.Model): time_id = models.CharField(max_length=8) project = models.CharField(max_length=100) budget_sales = models.DecimalField(max_digits=20, decimal_places=3) And the data will somewhat looks like this. Model A | time_id | project | sales | adjustment | +---------+-----------+-------+------------+ | 2019JAN | Project A | 1000 | 10 | | 2019JAN | Project B | 2500 | 5 | | 2019FEB | Project A | 1100 | 0 | | 2019FEB | Project B | 2400 | -10 | +---------+-----------+-------+------------+ Model B | time_id | project | budget | +---------+-----------+--------+ | 2019JAN | Project A | 1100 | | 2019JAN | Project B | 2400 | | 2019FEB | Project A | 1000 | | 2019FEB | Project B | 2500 | +---------+-----------+--------+ And I'm looking to produce an array of objects with each object represent each project's result each month, similarly to the way we join 2 tables with sql. However, I'm unsure how to write the serialiser and API Viewset … -
Set default image to CloudinaryField in Model
I have recently started using Cloudinary for media storage. I have a Profile model with image and cover image fields Without Cloudinary Before changing to cloudinary media storage the model looked like this: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) # setup without Cloudinary image = models.ImageField(default='profile_image/default.jpg', upload_to='profile_image', blank=False) cover_image = models.ImageField(default='cover_image/default.jpg', upload_to='cover_image', blank=False) It allowed me to set default image for both fields. With Cloudinary Now, after adding Cloudinary, it looks like this: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) # setup with Cloudinary image = CloudinaryField('image') cover_image = CloudinaryField('cover_image') I want to be able to set default images for both fields. Here are relevant libraries' versions Django==2.1.5 cloudinary==1.17.0 django-cloudinary-storage==0.2.3 olefile==0.46 cloudinary-cli==0.3.4 -
when i first ran my django project on local host 127.0.0.1:8000 it opened properly but now after adding product it shows 127.0.0.1 refused to connect
so this is the code and something i found weird is that my db.sqlite3 has a '?' (question mark) icon but the tutorial i am following has a white paper icon when i ran 127.0.0.1:8000 for first time it showed me my django local host but now it says this site cant be reached. i tried changing local host in settings.py to 127.0.0.1 #view from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello world! ') def new(request): return HttpResponse('New products ') #urls from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] -
How to display ellipsis to user
I'm a Django beginner. I have posts of users I follow and those who follows me,and I want to display different ellipsis ontop of other users post and not mine. For example if user A is friend user B, I want an ellipsis to be displayed only in user B post. What i tried doesn't give me what I wanted: {% if post.user == request.user %} <i fas fa-ellipsis></i> {% endif %} def home(request) all_images = Image objects.filter( Q(imageuploader_profile=request.user)| Q(imageuploader_profile__from_user__to_user=request.user)| Q(imageuploader_profile__to_user__from_user=request.user)) context = {'all_images': all_images } {% for post in all_images %} .... my codes here..... <i class="fas fa-ellipsis"></i> {% endfor %} -
Django: how to send one time messages like messages framework using rest api
I know in DJango using django.contrib.messages we can show messages Eg in the view of Login: from django.contrib import messages if form.is_valid(): ... messages.success(request, 'Login Successful') return redirect('Home Page') In the template of Home Page we can show the messages: {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} Because my Rest API will not be using any cookies or session. Is there any similar thing when i am working with rest api. -
how to implement database transactions mannulally in django?
I am new to django and i want to implement database transactions manually?is there anyway we can implement django transactions on specific models only? i have choice model on which i want to handle each user's transaction manually. models.py class choice_filling(models.Model): stud_id = models.ForeignKey(student, on_delete=models.CASCADE) clg_id = models.ManyToManyField(college) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() -
Is it safe to enable cors for DRF using TokenAuthentication?
I have a Django web app which serves a REST API (via Django Rest Framework) for users to make them able to retrieve some data from my website. I use TokenAuthentication method that requires you to set a Authorization header with the given token, then requests are accepted. Today I figured out that while my users can retrieve data by using Python requests library or httpie HTTP client, they can't retrieve data with their Javascript code (which's using fetch() method of Javascript). They see this error: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..." So I think I should enable CORS for my API then to accept requests from any web server of my users? I still want my users to authenticate with TokenAuthentication. So if I enable CORS, is it safe for my api and web app? Is there anything I should consider before doing this? -
Django, login page empty
I have the following login page, based on the Django authentication. The URL knows where to look for the template because if I will delete the accounts/login page it will raise an error and the Django default logout page appears. So the right template Is connected to the right path but the URL: http://127.0.0.1:8000/accounts/login/ Is a blank page. urls.py from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('landingpage.urls')), Login.html {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <div id="content-container" class="container p-none"> <div class="lgn-container col-lg-8"> <form id="login-form" method="post" action="{% url 'django.contrib.auth.views.login' %}"> {% csrf_token %} <table class="table"> <tr> <td><label for="id_username">Username</label></td> <td><input id="id_username" name="username" type="text" class="form-control"></td> </tr> <tr> <td><label for="id_password">Password</label></td> <td><input id="id_password" name="password" type="password" class="form-control"></td> </tr> </table> {% if form.errors %} <p class=" label label-danger"> Your username and password didn't match. Please try again. </p> {% endif %} <input type="submit" value="Login" class="btn btn-primary pull-right"/> <input type="hidden" name="next" value="{{ next }}"/> </form> </div> </div> {% endblock content %} If I take out/ delete login.html from templates/registration directory, I get the following error: TemplateDoesNotExist at /accounts/login/ registration/login.html -
Django template and Math expression for dynamic content
How do you set dynamic content passed from view to template to use mathjax or Latex. To be more precise in the terminal if 5*sqrt(2) would be displayed as 2√2 by pprint function. But in the django template it outputs as 2*sqrt(2) and not 2√2? -
Q: django-simple-menu - menu doesn't load
my django-simple-menu doesn't work. My code very closely resembles the example from the doku https://django-simple-menu.readthedocs.io/en/latest/usage.html#usage-example. The page loads without the menu links and I get no errors messages. Would be grateful for any ideas on how to solve this. Django: 3.0.1 Python: 3.7.5 nav.html <nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> {% for item in menu %} <li class="nav-item active"> <a class="nav-link" href="{{ item.url }}">{{ item.title }} <span class="sr-only">(current)</span></a> </li> {% endfor %} </ul> </div> </nav> base.html {% load menu %} <!DOCTYPE html> <html> <head> <title>Home</title> ... {% load static %} <link rel="stylesheet" type="text/css" href="{% static '/css/base.css' %}"> </head> <body> {% if user.is_authenticated %} <div class="d-flex bg-dark header " > <div class="p-2 flex-grow-1 bg-dark "> </div> <div class="p-2 bg-dark ">User: {{ user.username }} </div> <div class="p-2 bg-dark"><a href="{% url 'logout' %}">Logout</a></div> </div> {% generate_menu %} {% with menu=menus.main %}{% include 'nav.html' %}{% endwith %} {% else %} .... {% endif %} <main> ... </main> </body> </html> setttings.py """ Django settings for nsap project. Generated by 'django-admin startproject' using Django 3.0.1. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the … -
When accessing data (DateTimeField) from the django model, it always return None
I hava a table like this one: class PostDetail(models.Model): topic_id = models.IntegerField() post_user_id = models.IntegerField() content = models.TextField() date = models.DateTimeField(default=timezone.now) class Meta: ordering = ("-date",) but when I access data in this way: main_reply = PostDetail.objects.filter(topic_id=id) print(main_reply[0].date) It always return None, I am really confuse ps: When I access it in SQL, it is alright. -
How to fix Order matching query doesn't exist in Django?
HViews is as follows def deleteorder(request, pk): order = Order.object.get(id=pk) if request.method == 'POST': order.delete() return redirect() context = {'item':order} return render(request,'accounts/delet.html', context) And Urls.py is as path('delete_order//', views.deleteorder, name= 'delete_order') -
Django: Trying to update an object based on selection by a checkbox in a list display
In the template I am displaying a list of objects in a table. Since its a list I did not use a form. I then added checkboxes to approve each entry (as shown below) The problem is that now I cannot figure out how to iterate over the checkboxes. template.html <form method="post" > {% csrf_token %} {% for row in row_list %} <tr> <td><input type="checkbox" name="result" value=""/></td> <input type="hidden" name="task_id" value="{{ row.id }}"/> <td>{{ row.id }}</td> <td>{{ row.name }}</td> </tr> {% endfor %} <tr> <td colspan="5"> <button type="approve">Approve</button> </td> </tr> views.py def review_results(request, batch_id): batch = get_object_or_404(Batch, pk=batch_id) if request.method == 'POST': # I have tried the following print("Result is ", request.POST.getlist('result')) print("Result is ", request.POST.getlist('task_id')) print("Result is ", request.POST.lists()) request.POST.getlist('result')) returns the value of checkboxes which are checked (array size is 0 if nothing checked). request.POST.getlist('task_id')) returns the list of ids as originally passed (fine). But both lists are out of sync. I cannot use the array from 'result' and perform a save on the appropriate 'task_id' Any ideas on how should i fix this ? Thank you in advance. -
Using Django, How can I delete a file right after downloaded without refreshing the page?
I have the next link to download a file that was generated before rendering a view: <a href="{% static download_path %}" download> Download File </a> How can I delete the file right after the user clicks on that link but without leaving the page? -
Django Forms CheckboxInput on Y/N String field in existing database
I'm relatively new to Django, and I'm making a form which I'm connecting to a existing MySQL database. What I'm trying to do is create a maintenance page for countries. One of the fields in my database is eu_member_state. What I'm trying to do here is create a checkbox for this field, so I can uncheck it for the United Kingdom which recently got out of the EU. class CountryForm(forms.ModelForm): class Meta(): model = Countries fields = '__all__' widgets = { 'eu_member_state': forms.CheckboxInput() } The checkbox does appear on my form, but how can I make this talk to my database? How can this checkbox only be checked when the database value is 'Y', and how do I write this back to my database on save, so 'Y' when checked and 'N' when unchecked?