Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can a django app in development be used directly onto production
Being a newbie to django and python, i managed to create a small project. I understand this way is the development phase. If i wish to put this work from development phase into production, would Django's inbuilt server capable enough to handle the requests? Is it not mandatory to keep development and production separate? -
Django heroku app still presenting SMTPauthentication error yet gmail access to less secure apps is on
I made sure my gmail credentials to use for smtp are correct and allow access to less secure apps is turned on but I am still facing SMTPauthentication error. on doing some research on other similar questions asked I came across this: but how do I visit the DisplayUnlockCaptcha URL shown in the screeshot above from my Heroku app IP so that gmail can recognize it and stop blocking it ? -
Django Form ignores translation and falls back to default
I have recently introduced translation (i18n) to my django app. It works fine for all templates and error messages. Not for forms unfortunately. It always falls back to English, even if the rest of the page is shown in German. settings.py: LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True forms.py: from django import forms from django.utils.translation import gettext as _ from django.conf import settings from django.core.validators import DecimalValidator, MaxLengthValidator, EmailValidator, MinLengthValidator class AccountCompanyNameForm(forms.ModelForm): # adding some default validators phone = forms.CharField(validators=[MinLengthValidator(10)], error_messages={'invalid': _("Bitte geben Sie eine gültige Rufnummer an.")}) name = forms.CharField(label=_("Vorname Nachname"), validators=[MinLengthValidator(3)], error_messages={'invalid': _("Bitte geben Sie Ihren Vor- und Nachnamen ein.")}) company = forms.CharField(label=_("Firma"), validators=[MinLengthValidator(3)], error_messages={'invalid': _("Bitte geben Sie den Namen Ihrer Firma an.")}) birthdate = forms.DateField(label=_("Geburtsdatum"), error_messages={'invalid': _("Bitte geben Sie das Datum im Format 01.01.1990 ein.")}) terms = forms.BooleanField() Template code: {% load i18n %} {% load widget_tweaks %} ... {% render_field form.company placeholder=form.company.label class+="form-control" %} ... {{ form.company.label }} Even the form.company.label is in English. German translation is there and correct. Any help is appreciated. -
DJANGO use of static files in combination with paths references
I've posted something similar earlier without being able to find a suitable solution. One of the things I am struggling with is the ability to serve static path / file references within DJANGO html templates. Hopefully, by posting another question I will be able to understand how this works. Done quite some research and read through the DJANGO documentation without being able to find something covering my scenario. Here we go: Within my model I use a path reference field class Product_images(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True) path_to_image = models.CharField(max_length=150,null=True, blank=True) name = models.CharField(max_length=50,unique=False,blank=True) class Meta: verbose_name = 'Product Image' verbose_name_plural = 'Product Images' def __str__(self): return '{} - {} - {}'.format(self.pk, self.product, self.name) The value of this field is set to (example): static\images\Product\PowerBI\Receivables\Receivables 6.png The files are physically stored within the app Main/static/.... My setting file contains: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'Main/') MEDIA_URL = '/Main/' Then I have two templates within the app where I want to serve these images. One page uses a custom context processor in the following way: {{ product_section }} Which returns html including: html_value += u'<img class="d-block w-100" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.path_to_image,productimages_obj.name) This context processor tag is … -
Django channels: Save messages to database
I'm a newbie to channels and I made a chatroom application by following their official documentation. Now I'm trying to save the chat messages. All I know is I can create a model but Idk how to save it from the consumers.py into my database. I added username along with the message. A little help would be appreciated. My Consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): username = self.scope["user"].first_name name = self.scope['user'].username text_data_json = json.loads(text_data) message = text_data_json['message'] message = (username + '(' + name + ')' + ':\n' + message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): username = self.scope["user"].username message = event['message'] name = self.scope["user"].username # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, "username": username, "name": name })) My model to save the msgs: class Message(models.Model): author = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) context … -
Deployment Django Ideas
I developed an Social Media app using Django. I want a good way to deploy it so that it would work well no matter of number of the users using it, or the media uploaded. What's an good way do deploy it ? -
how do i edit other users profile on django
i have two separate users, i want some users to be able to modify other users profile. The problem i am facing now is how to get the users id. i have a 2 views involved in this. The profile view, the edit profile view. i tried to wrap the entire profile html in a form, i am not sure that will work. most of the examples only show how to edit current(logged in) user's profile. the link to a specific users profile (http://127.0.0.1:8000/dashboard/profile/dfrtgy-ehehh/16) the profile page has a link to the edit profile page. profile html <li> <a href="{% url 'editprofile' %}"><img class="nav-items" src="{% static 'images/lab.svg'%}" alt=""><span>Edit profile</span> </a> </li> views.py def edit_profile(request): if request.method == 'POST': profile = Profile.objects.get(pk=pk) form = EditProfileForm(request.POST, instance=request.user.profile) if form.is_valid(): form.save() return redirect(f'/dashboard/profile/{request.user.profile.slug}/{request.user.pk}') else: form = EditProfileForm(instance=request.user.profile) args = {'form': form} return render(request, 'core/editprofile.html', args) def profile(request, slug, pk): profil = Profile.objects.get(slug=slug) profile = Profile.objects.get(pk=pk) context = {'profile': profile, 'profil': profil} return render(request, 'dashboard/profile.html', context) urls.py urlpatterns = [ path('', dashboard, name='dashboard'), path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk'), path('edit_profile/', edit_profile, name='editprofile'), -
how to improve the rendering time of a PDF file?
I have a django web platform hosted on digital ocean, the platform works fine, but rendering large pdf files (average 100MB) takes a long time (average 1:30 min) These are the resources in digital ocean: -2 vCPUs 4GB/80GB Disk How can we improve rendering time? This is how it looks when it takes time to render the pdf (disable the main menu of the pdf to avoid downloads) -
Heroku throughput extremely high for no reason
I have developed a very basic site for a hosting an online cryptic hunt. Used Django and deployed it on heroku. It went live a couple days ago and just recently it went down and the logs mentioned an h11 error - "backlogs too deep". I checked the metrics and noticed a massive spike in the throughput. It read that the requests were exceeding 200k. Why is this happening? I've tried upscaling the dynos but it's going to get really expensive. We barely have 30-40 users but the metrics show that we're getting over a million requests in a day. The site just won't come out of the application error. -
Django - Can I delete apps static files after running collectstatic
From this answer, collectstatic is a ready-made script that prepares this directory for you, so that you can connect it directly to your deployment script. After running the collectstatic command, all static files in my apps are copied to a static folder in the root of my project. Can I delete the static folder in my apps? Since they are copied already. I kind of felt like it's just duplicating and costing me file size or am I missing something? I deleted the static folder in my apps but it does not work anymore. Why duplicating my static files then or can I delete them after going live? -
Docker running manage.py results in segmentation fault
I am running Django in a docker on a raspberry pi 4b with 8gb ram. When docker runs my startup script that includes some commands with python3 manage.py ... Django crashes with a segmentation fault AFTER executing the command successfully. The simplest way of recreating this behaviour is: Log into docker shell: docker exec -it django_backend /bin/bash Go into venv and then run: python3 manage.py This lists all the options for manage.py as expected and then immediately after results in a segfault. Output: Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser ... Segmentation fault (core dumped) Memory is definitely not the issue, less than 20% of the available memory is in use. I tried multiple resets of the whole system. I also tried this on two other machines with 8GB ram and there I don't get a segfault. Any ideas what could be the reason for this or how I could test for possible reasons? -
Django DetailView queryset returns an empty list
DetailView queryset returns on full name which I suspect is coming from the model's __str__ method. class EmpDetail(DetailView): template_name = 'users/emp_detail.html' model = Employee context_object_name = 'employee' I tried this and it gets me what I need but the id is hard coded in, I don't have access to kwargs: def get_object(self, queryset=None): employee = Employee.objects.filter(user=self.request.user, id="1").values('full_name', 'val2', 'val3', ... ) return employee Then I tried this but it returns an empty list. def get_context_data(self, **kwargs): context = super(EmpDetail, self).get_context_data(**kwargs) pk_= self.kwargs.get("id") context['employee'] = Employee.objects.filter(pk=pk_).values('full_name', 'val2', 'val3', ... ) return context How do I make a query in DetailView and pass it to template? -
how to override error_message in model or model form?
Sorry for my English. Unfortunately, I can't find a solution on the forum and in google. I ask you to help me figure out how you can override error_mesage in ModelForm or Model. It is necessary that instead of the standard message during validation, it shows the message that I define. I constantly get a message instead of mine "Please fill out this field". Don't be too harsh, I'm a beginner. Please, if possible, explain in detail and with an example. Thanks! Below is the code that I used. Form class PersonForm(ModelForm): class Meta: model = Person fields = ('name', 'mood') error_messages = {'name': {'invalid': 'Мое сообщение об ошибке', 'blank': 'Мое сообщение ' 'об ошибке', 'null': 'Мое сообщение об ошибке'}} Views def exp_index(request): if request.method == 'POST': pForm = PersonForm(request.POST) if pForm.is_valid(): pForm.save() persons = Person.objects.all() pForm = PersonForm() add_message = 'Можете добавить еще одну запись!' context= {'person': persons, 'form': pForm, 'add_message': add_message} return render(request, 'exp/exp_index.html', context) else: persons = Person.objects.all() error_message = 'Неверно указали данные, попробуйте еще раз!' context= {'person': persons, 'form': pForm, 'error_message': error_message} return render(request, 'exp/exp_index.html', context) else: pForm = PersonForm() person = Person.objects.all() context= {'person': person, 'form': pForm} return render(request, 'exp/exp_index.html', context) Model class Person(models.Model): l=[[None, … -
how create a view class include all function in django view
For example i have a admin app in a django project. I have 2 view function in views.py like as views.py from django.shortcuts import render, redirect from .models import Manager def admin_home(request): manager = 'manager' context ={ 'manager':manager, } return render(request, 'home/index.html', context) def admin_show(request): manager = Manager.objects.all() context ={ 'manager':manager, } return render(request, 'home/index.html', context) But i want to write both function in a class. like as from django.shortcuts import render, redirect from .models import Manager from django.views import View class AdminPart(View): def admin_home(request): manager = 'manager' context ={ 'manager':manager, } return render(request, 'home/index.html', context) def admin_show(request): manager = Manager.objects.all() context ={ 'manager':manager, } return render(request, 'home/index.html', context) Isn't it possible in django like as python class. please help me.... -
How to determine particular page types for a wagtail default search?
The regular wagtail search, included by default, searches over all pages of the project. How can i determine particular Pages for the search indexing? -
How to get total count of many to many field to a Django model?
This is a Blog model, how do I get the total count of likes from overall blog objects? class Blog(models.Model): title = models.CharField(max_length=160) ... likes = models.ManyToManyField( User, related_name='likes', blank=True, default=None) In the template, I can use user.likes.count and it will return total like count of a single user but how I do I get total like count from all users. Thank You -
Removing Django notification by disconnecting signal in django-notifications-hq
I am intending to remove a notification in the django-notifications-hq package by disconnecting the signal in my views after a signal is created: As an example: def view1: notify.send(sender=user, recipient=other_user, verb=message, target=object) return redirect('app:page') def view2: notify.disconnect(sender=user, reciever=other_user) return redirect('app:page2') user and other_user are the same users in this example This will disconnect all signals between user and other_user, what I intend to do is to only disconnect the signal created between those users for that specific object. I have already looked into the source code and I cannot find how I can manage to do such a thing. For your reference, the GitHub link is: https://github.com/django-notifications/django-notifications Also this is the Signals file in that package: ''' Django notifications signal file ''' # -*- coding: utf-8 -*- from django.dispatch import Signal notify = Signal(providing_args=[ # pylint: disable=invalid-name 'recipient', 'actor', 'verb', 'action_object', 'target', 'description', 'timestamp', 'level' ]) -
Select2 passing only one select to the form in Django
I'm using Select2 for a multiple select for tags. I'm using Taggit for the tags. The problem is that if a user chooses more than one tag, then just one is passed to the form. My select HTML: <select class="custom-select js-example-basic-multiple form-control " id="select-tags" name="usertags" multiple="multiple"> {% for tag in userTags %} <option value="{{ tag }}" data-id="{{ tag.color }}" class="options">{{ tag }}</option> {% endfor %} </select> My form: class FileUploadForm(forms.ModelForm): class Meta: model = Uploaded fields = ( 'name', 'file', 'usertags', ) Views.py if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user user = request.user form.save() -
django pagination error: AttributeError: 'WSGIRequest' object has no attribute 'Get'
I am having a hard time with django pagination. Can someone help me out with this? This view is returning an error: def view_homePage(request, user): if user == 'all': posts = Post.objects.order_by("-timestamp").all() paginator = Paginator(posts, 2) ERROR ---> page_number = request.Get.get('page') or 1 page_obj = paginator.get_page(page_number) return JsonResponse([post.serialize() for post in page_obj], safe=False) The error I am getting is: AttributeError: 'WSGIRequest' object has no attribute 'Get' If I remove the line and just set page_number = 1 for testing I have a new set of issues. How do I actually pass the page number to the view from the html page? I tried adding this for testing, but it does not work: <nav aria-label="..."> <ul class="pagination"> <li class="page-item"><a class="page-link" href="?page=3">3</a> </li> </ul> </nav> On the above code I hard coded page 3 just for testing, but it does not get into the view. How do I go about this? The django documentation is lacking in this regard. -
How can i amake the user change his own image not just from admin
I am trying to find a way to let the user change his own image and I couldn't do it because I am new to Django and please if you can help me in a way that is the same as my flow of code so I don't get confused or if you can just explain Thank You, Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from accounts.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class EditProfileForm(UserChangeForm): template_name='/something/else' class Meta: model = User fields = ( 'email', 'first_name', 'last_name', ) Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfileManager(models.Manager): def get_queryset(self): return super(UserProfileManager, self).get_queryset().filter(city='London') class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='image/', blank=True) objects = models.Manager() london = UserProfileManager() def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) Profile.Html {% extends 'base.html' … -
Git bash does not show real time updates for python
My Git bash does not show real-time outputs for Python. For example, if I try to print "Loading", then make an HTTP request, and then print out something again, my git bash shows everything all at once. I was trying to start Django runserver, and here's what I got: Watching for file changes with StatReloader It kept showing this for some time, so I decided to re-run the command. When I pressed CTRL + C, I got this: Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 03, 2020 - 23:08:15 Django version 3.1.2, using settings 'first_django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. This means the server actually started, but the bash did not show anything. How do I fix this? -
How can I load my own/custom CSS - Django
I'm trying to load my own customized CSS in Django but with no success. The weird thing is that the main CSS (style.css) is loading correctly. Here is my base.html: <!-- Main Style CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- My Own Style CSS --> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> My settings: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR, ] My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('cart/', include('cart.urls')), path('payment/', include('payment.urls')), path('orders/', include('orders.urls')), # path('users/', include('django.contrib.auth.urls')), path('', include('django.contrib.auth.urls')), path('', include('account.urls')), path('', include('dma.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + \ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Any help? Thank you! -
Pagination in DetailView [Django]
I have Article and ArticleCategory in my model. Article has many categories. MODELS class ArticleCategory(Created): category_name = models.CharField(max_length=128) slug = models.SlugField(null=False, unique=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.category_name) return super().save(*args, **kwargs) def __str__(self): return self.category_name class Article(Created): title = models.CharField(max_length=120) author = models.ForeignKey(User, on_delete=models.CASCADE) snippet = models.TextField(null=False) # ustawić max_lenght body = RichTextField(null=False) category = models.ManyToManyField(ArticleCategory, related_name='articles') # TODO: ustawić on_delete image = models.ImageField(blank=True, null=True, upload_to='article_image/') slug = models.SlugField(null=False, unique=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def get_absolute_url(self): return reverse('news:article_detail', kwargs={'pk': self.pk, 'slug': self.slug}) Also I have Url to specific category with all Articles with this category: URL urlpatterns = [ path('show/<int:pk>/<slug:slug>', ArticleDetailView.as_view(), name='article_detail'), path('all/', AllArticlesListView.as_view(), name='all_articles_list'), path('category/<slug:slug>/', CategoryArticlesList.as_view(), name='category_articles_list'), ] In the VIEW i created class CategoryArticlesList(DetailView): template_name = 'news/category_articles_list.html' model = ArticleCategory And finally template CATEGORY_ARTICLES_LIST.HTML SPECIFIC CATEGORY: {{ articlecategory.category_name | upper }} AND ALL NEWS WITH THIS CATEGORY {% for article in articlecategory.articles.iterator reversed %} <h3>{{ article.title }}</h3> <br> {{ article.body | safe }} <br> {% endfor %} My question is... How can I make Pagination to all specific category articles in Views? If I use ListView in class CategoryArticlesList there will be big problem with … -
Include a manytomany field in django-geojson with leaflet
I'm loosely following the example about the mushrooms to use django-geojson with Leaflet. My example contains a model for a city and a list of buildings in that city (many to many field). I would like to list the names of all buildings in a given city. MODELS class Building(models.Model): name = models.CharField(max_length=256) class City(models.Model): name = models.CharField(max_length=256, default='') geom = PointField() buildings = models.ManyToManyField(Building) URLS urlpatterns = [ url(r'^data.geojson$', GeoJSONLayerView.as_view(model=MyModel, properties=('name', 'buildings')), name='data') ] TEMPLATE <script> var dataurl = '{% url "data" %}'; window.addEventListener("map:init", function (event) { var map = event.detail.map; // Download GeoJSON data with Ajax fetch(dataurl) .then(function(resp) { return resp.json(); }) .then(function(data) { L.geoJson(data, { onEachFeature: function onEachFeature(feature, layer) { var props = feature.properties; var content = `<p>${props.name}</p> <p>${props.buildings}</p>`; layer.bindPopup(content); }}).addTo(map); }); }); </script> How can I make sure that the data also contains the information from the buildings (e.g. the field name). Currently I only get a list with ids. One alternative is to add a property to the model that basically generates the html, but I would like to keep all the html in the template file. -
Select latest record for each hour
I have Balance model Each balance has b_date = models.DateTimeField() I parse balances every 5 mins but to user I want to show latest balance of each hour So for example if I have balances with #1 b_date="15:34", #2 b_date="15:55, #3 b_date="20:00" the output should be: #2 b_date="10.06.15 15:55 #3 b_date="11.07.15 20:00" As you can see we removed balance #1 because we need only latest balance from each hour. So far I've come to this: trunc_entries = balances.annotate(tx_hour=TruncHour('b_date')) Which sets all hours to 00:00 But I don't know how to group by this tx_hour and select latest