Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix ProfileNotFoundError in Django
Basically, I'm creating an app and currently I'm testing out an "Edit Profile" feature. For me (the admin) I manually added myself to the Profile model using the admin page. However, when I tried it on my test account, it didn't work. I know what the problem is (I didn't add him to the model) but I was wondering how I could fix it. Here's my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() Here's my views.py: @login_required def profile(request): user_form = UpdateUser() profile_form = UpdateProfile() if request.method == 'POST': user_form = UpdateUser(request.POST, instance = request.user) profile_form = UpdateProfile(request.POST, request.FILES, instance = request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('profile') else: user_form = UpdateUser(instance = request.user) profile_form = UpdateProfile(instance = request.user.profile) context = { 'user_form' : user_form, 'profile_form' : profile_form } My signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender = User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And finally, my apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = … -
Django adding fields in a form statically
Good day, I am trying to make a Django form where I could add fields statically (the concept is described in the figure below). I want to have a form that would have a button "new". The button "new" should redirect to another page where I could fill the data such as from, to, and amount. Once I press submit it should go back to the form where the filled data should be visible in the form (as amount 1, amount 2 and etc.). Could somebody lead me on the right path how to start? P.S. I cannot use javascript -
from an id, how to get a path for different pages in django
I am creating a web page,it is for a restaurant. there is an image slide show. all the thing of slide show dynamic..load from the database. My problem is.. there is a button of the each slid to go to different pages. as an example one slide for wine section another is for menu another for special plates. another for another page so on...my html template is this [enter link description here][1] [1]: https://colorlib.com/wp/template/eatery/ how can i give the path to the each different pages. my urls.py urlpatterns = [ path('', home, name='home' ), ] my views.py def home(request): image_gallery = Gallery.objects.all() context = {'galleries':image_gallery} return render(request, 'restaurant/index.html', context) my html template with for loop <section class="home-slider owl-carousel"> {% for gallery in galleries %} <div class="slider-item" style="background-image:url('{{gallery.image.url}}')"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>{{gallery.image_title}}</h1> <p class="mb-5"> {{gallery.image_description}} </p> <p> <a href="{% url'' id= gallery.id %}" class="btn btn-white btn-outline-white">{{gallery.image_button}}</a> </p> </div> </div> </div> </div> {% endfor %} </section> My models.py class Gallery(models.Model): image = models.ImageField(null=True, blank=True, ) image_title = models.CharField(blank=True, null=True, max_length=200) image_description = models.TextField() image_button = models.CharField(blank=True, null=True, max_length=20) -
How to stop python development server from terminal?
I am writing a my_migration_script.py in the root directory of my django project to remove all the migration files from different apps of my django project. It is like this: import os import shutil migration_folders_names = [ '/app1/migrations/', '/app2/migrations/', '/app3/migrations/', '/app4/migrations/', '/app5/migrations/', '/app6/migrations/', '/app7/migrations/', ] cwd = os.getcwd() migration_folder_paths = [cwd + migration_folder_name for migration_folder_name in migration_folders_names] [shutil.rmtree(migration_folder_path, ignore_errors=False, onerror=None) for migration_folder_path in migration_folder_paths] [os.mkdir(migration_folder_path) for migration_folder_path in migration_folder_paths] [open(migration_folder_path + "0001_initial.py", "x") for migration_folder_path in migration_folder_paths] It works fine. I then want to do the following: 1) Stop runserver: I have a tab for running python manage.py runserver in my Pycharm IDE. What I normally do is that I go to the abovementioned terminal tab and hit Ctrl+C . However, I now want to automate it by adding a piece of code to my_migration_script.py . What should I add to my_migration_script.py ? 2) I have a tab for running python manage.py shell in my Pycharm IDE. What I normally do is that I go to the abovementioned terminal tab type and enter exit() . However, I now want to automate it by adding a piece of code to my_migration_script.py . What should I add to my_migration_script.py ? 3) I … -
How to insert data into a database every time I click Send from HTML button
I have an SMS function on my Django app, but I want to happen is record the message and timestamp each time I send a message. I need to store the value inside sms_message on another table every time I click send sms. The entry on the other table will be like this: id: 1 Description: As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation Timestamp: XXXXX Help, how to do it? Thanks! @views.py def send_sms(request): aws_access_key_id = "XXXXXXXXXXXX" aws_secret_access_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" aws_region_name = "us-east-1" z = Rainfall.objects.latest('timestamp', 'level') sender_id = "Test" sms_message = f'As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation' client = boto3.client( "sns", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region_name ) topic = client.create_topic(Name="notifications") topic_arn = topic['TopicArn'] # get its Amazon Resource Name numbers = Mobile.objects.all() for i in numbers: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=i.mobile_number ) response = client.publish( Message=sms_message, TopicArn=topic_arn, MessageAttributes={ 'string': { 'DataType': 'String', 'StringValue': 'String', }, 'AWS.SNS.SMS.SenderID': { 'DataType': 'String', 'StringValue': sender_id } } ) messages.info(request, 'SMS sent successfully!') return HttpResponseRedirect('/advisory/') @sendsms.html {% block content %} {% if messages %} {% for message in messages %} {% if message.tags %} <script>alert("{{ message }}")</script> {% endif %} {% endfor … -
DRF , invalid model refrence
I'm restructuring my API and I've made a models folder inside the app. now when I'm trying to fix the AUTH_USER_MODEL I get the following error: ValueError: Invalid model reference 'api.models.user'. String model references must be of the form 'app_label.ModelName'. my structure: ├── api │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models │ │ ├── __init__.py │ │ ├── messages.py │ │ └── user.py # rest of app and my settings: AUTH_USER_MODEL = 'api.models.user' -
using django messages while redirecting by javascript function
The project has two standart title and entry models. The deletion of entries is handled by ajax. Ajax: function ajax_delete(id){ $.ajax({ url: '/ajax/delete/', type: "get", data: { 'id': id, }, dataType: 'json', success: function (data) { if(data.nono){ window.location.replace("http://192.168.1.22:8000/mainpage/"); } else{ $("#overlay3").css("display","none"); $( "#article" + id ).remove(); $('body').css('overflow', 'scroll'); }}, error: function (result) { alert('nope'); } }); }; View: def delete(request): id= request.GET.get('id', None) if Entry.objects.filter(id= id).exists(): entry= Entry.objects.get(id= id) if entry.user == request.user or request.user.is_staff: entry.delete() if not Entry.objects.filter(title=entry.title).count(): Title.objects.get(title=entry.title).delete() data={"nono":1} return JsonResponse(data) data={"success":True} else: data={"success":False} else: data={"success":False} return JsonResponse(data) The function also deletes the entry if the title has no other entries. In that case, to prevent users from seeing an empty page the users are redirecting to the mainpage by ajax success. When that happens I want to inform the users about the deletion of the title by flashing a custom django info message (I have a badass fadeout animation for django info messages). So I wonder if there is any way of using djago messages after redirecting by ajax. -
How to make a filtered summary in django template involving two models linked with foreign key?
I am currently learning django and below is the current setup: models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=200, null=True, choices=STATUS, default="Pending") def __str__(self): return self.product.name views.py def home(request): orders = Order.objects.all().order_by('-date_created') customers = Customer.objects.all() c_pending = orders.filter(status='Pending').all() context = { 'orders': orders, 'customers': customers, 'c_pending': c_pending, } return render(request, 'home.html', context) home.html {% for customer in customers %} <tr> <td>{{customer.name}}</td> <td>{{customer.phone}}</td> <td>{{customer.order_set.count}}</td> <td>{{c_pending.count}}</td> </tr> {% endfor %} One to third column work flawlessly, except fourth column. The problem is I wish to display in fourth column the no. of orders which is under pending status for each customer but it indeed shows up the total no. of pending orders as a whole. What steps I am missing in order for django template properly extract the no. of orders for each customer under pending status. Any help is highly appreciated. Thanks. -
Passing user input from one template to multiple other templates
I am learning Django and looking to build out a site that would take input from a user one page1. Then it will pass that information over to page2. Then both page1 and page2 user input would get passed to page3 and processing will happen. Very similar to like a sign up form. The first page is some information, then the second page is some more information, then the third page will complete the signup. Right now I return data from one page to another like this: return render(request, 'per/per.html', context) And then on that page I have access to all the data in the context variable. But wanted to know how to move it to another page. -
MySQL handling large queries
I'm using MySQL + Django and I'm downloading and updating data in my database. I have a few large queries which they sometimes fail -> "MySQL server has gone away" The query is such SELECT * FROM XYZ_table WHERE id IN (list with about 10-40K values) What are my possibilities here? Should I split the query and then concatenate the separate lists? Or is there a MySQL config value I can increase? I have max_packet_size set at 512M -
Django doesn't recive pre save signal
I'm writing DRF appliaction and I have problem which I can't understand. I'm trying to send request when my model changes. Here is my model: class Sensors(models.Model): CATEGORIES = [ ('temperature', 'temperature'), ('humidity', 'humidity'), ] id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') name = models.CharField(max_length=30, unique=True) category = models.CharField(max_length=15, choices=CATEGORIES) battery_level = models.IntegerField(blank=True, null=True) notifications = models.BooleanField(default=True) is_active = models.BooleanField(default=True) frequency = models.IntegerField(default=300) ip_address = models.GenericIPAddressField(blank=True, null=True) class Meta: verbose_name = "Sensor" verbose_name_plural = "Sensors" def __str__(self): return str(self.id) And here is my signal.py: from django.db.models.signals import pre_save from django.dispatch import receiver from sensors.models import Sensors import requests @receiver(pre_save, sender=Sensors) def do_something_if_changed(sender, instance, **kwargs): try: sensor = Sensors.objects.get(pk=instance.pk) except Sensors.DoesNotExist: pass # Object is new, so field hasn't technically changed, but you may want to do something else here. else: if not sensor.frequency == instance.frequency: # Field has changed # do something data_for_sensor = { 'id': sensor.id, 'frequency': instance.frequency } response = requests.post('http://192.168.1.21:8000/receive', data=data_for_sensor) response.raise_for_status() Generally post is not sending and I cannot find why -
How to implement a custom search remote data for each column on material-tale in React
I was wondering if it is possible to implement a custom search row for each column in my material-table data in React ? I would like to have a function which calls my Django Rest api's search function with the data submitted in my search filter in material-table and then display only the matched data. Based on the material-table docs I tried to implement customFilterAndSearch and pass the term to a custom method which calls my Rest api with the search term but the customFilterAndSearch access the method multiple times. Actually I get to a point where there axios get method get called by the number of rows items I have in my table. Here is the custom customFilterAndSearch call: customFilterAndSearch: (term, rowData) => this.getDataFilterNomService(term, rowData) }, Here is my custom method I used: async getDataFilterNomService(term, rowData){ console.log("TermDinFilter", term) //console.log("rowDataDinFilter", rowData) try{ let response = await axiosInstance.get('get/servicecatalog/filterNomService/', { params: { "nom_service":term } }); console.log("Response la Filtru NomService", response) } catch(error){ console.log("Error: ", JSON.stringify(error, null, 4)); throw error; } } And here is how django gets called when I try to search for a name like : "Viorel" backend_1 | [11/Jun/2020 16:49:02] "GET /api/get/servicecatalog/filterNomService/?nom_service=Viorel HTTP/1.1" 200 968 backend_1 | [11/Jun/2020 16:49:03] … -
Integration of a second application into Django project
I have two separate working Django projects. Both consist of one application. Both have own data base. Now I am trying to join them. I took the first project as the base, copy+paste the folder with the second application on the same level with first one. I have added ane integration record into main file urls.py path('rsf/', include('rsf.urls')), and a record into INSTALLED_APPS. Then at start, the second application raised errors, because its old database was not reacheable. I have commented nearly everything in the second application and left its models.py file only. Then I tried to make migrations. Django does not see the new models, belonging to the second app, which must be created from the new models.py file and says that there is nothing to migrate. No mistakes here are raised. Please help. Thank you. ael - is the first app. rsf - is the second app from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.contrib.sitemaps.views import sitemap from ael.sitemaps import StaticViewSitemap, CrossRefTableSitemap from ael import views as ael_views from django.contrib.sitemaps import views as sitemaps_views from django.views.decorators.cache import cache_page sitemaps = { 'static': StaticViewSitemap, 'crossreftable': CrossRefTableSitemap, } urlpatterns = [ path('admin/', admin.site.urls), … -
Django Check for duplicates with 2 model fields
I have a model that looks like this: class UssdCode(models.Model): title = models.CharField(max_length=100) code = models.CharField(max_length=100) product = models.CharField(max_length=100) How can I get the admin to alert me and reject my entry when I try to add a new object that has the same 'code' and 'product' as an object already in the database. -
How to connect your data base to your pycharm html files
I am wondering on to how to connect my pycharm html file to a database and display it on the html webpage for the material I have been using online have not been working towards the connection on the database to the html? any supplementary material that can be provided will help as well. -
Include chatbox in all views Django
I have created a chat in Django using django-private-chat package which uses Websockets. I want to have a chat that is displayed in every page of the website allowing client asking questions to staff members. My problem is that I have created a chat button in the base.html in order to be able to chat in every views. So I include the view users_list.html (view where we have all the users) and when I click on chat with someone, my dialog page (which is the chat page) appears but it is empty. I wanted to use the context_processor.py like I used it for user_list.html to have all the users but I don't understand how to do it for this. In base.html {% if user.is_authenticated %} {% block chat %} <div id="notification-btn" class="notification-button"> <button class="button-base" onclick="displayChooseUser()"> <i class="fas fa-comment icon-chat"></i> </button> </div> <div id="chooseUser"> {% include "../django_private_chat/user_list.html" %} </div> {% endblock %} {% endif %} In the user_list.html {% for user in users %} {% if user != request.user %} <div class="chat_list active_chat"> <div class="chat_people"> <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil" class="avatar"> </div> <div class="chat_ib"> <h5> <p onclick="chatShow()"> Chat with {{user}}</span> <div class="test" style="display:none;"> {% url 'dialogs_detail' user as dialogs %} {% … -
I want to load the default image of the user in if the user has not uploaded the pic. But its not showing the default pic of the user
I want load the default pic of the user but its not showing any image and after submiting the pic its showing RelatedObjectDoesNotExist. User has no attribute userprofile. models.py from django.db import models from django.contrib.auth.models import User class userprofile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import userprofile class ProfileUpdateForm(forms.ModelForm): class Meta: model = userprofile fields = ['profilepic',] views.py @login_required def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile) if p_form.is_valid(): p_form.save() return render(request,'profile.html') else: p_form = ProfileUpdateForm(instance=request.user.user) context = { 'p_form': p_form } return render(request,'profile.html',context) profile.html <form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" > {% csrf_token %} <img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}"> {{ p_form|crispy }} <br> <input id="file-input" style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload"> </form> -
Django import export edit queryset before export
I'm trying to calculate the pending amount via models and export result in the csv. But the csv shows an empty coloumn for amountpending ''''class FinancePendingResource(resources.ModelResource): invoiceNumber = Field(attribute='invoiceNumber', column_name='Invoice Number') student = Field(attribute='student', column_name='Student') Schedule = Field(attribute='Schedule', column_name='Schedule') TotalAmount = Field(attribute='TotalAmount', column_name='Total Value(PKR ₨)') issueDate = Field(attribute='issueDate', column_name='Issue Date') dueDate = Field(attribute='dueDate', column_name='Due Date') amountPaid = Field(attribute='amountPaid', column_name='Amount Paid (PKR ₨)') class Meta: model = FinancePending import_id_fields = ('invoiceNumber',) fields = ('invoiceNumber', 'student', 'amountPaid', 'issueDate', 'dueDate', 'Schedule', 'TotalAmount', 'AmountPending',) exclude = ('id',) skip_unchanged = True report_skipped = True def before_export(self, queryset, *args, **kwargs): amount_paid = FinancePending.objects.values_list('amountPaid', flat=True) amount_paid = list(amount_paid) total_amount = FinancePending.objects.values_list('TotalAmount', flat=True) total_amount = list(total_amount) # total - paid TotalFee = [float(s.replace(',', '')) for s in total_amount] AmountPaid = [float(s.replace(',', '')) for s in amount_paid] def Diff(li1, li2): return (list(set(li1) - set(li2))) amount_pending = Diff(TotalFee, AmountPaid) finance_pending = FinancePending() i = 1 while i <= len(amount_pending): FinancePending.objects.filter(invoiceNumber=i).update(AmountPending=str(amount_pending[i])) i = i + 1 queryset.refresh_from_db() -
Update Location.PointField in real time whenever the latitude or longitude values are changed
I looked at Romas post (GeoDjango: Can't save a model with PointField(), Error: SpatialProxy (POINT) with value of type: <class 'users.models.Point'>) and copied his idea. I calculate Location by doing self.Location = Point(self.Longitude, self.Latitude). The problem with this approach is that the location is only updated when I click save (at the moment I am modifying the table via the admin page and not the front end). Is there a way of getting the Location value to be updated in real time? class Property(models.Model): id = models.AutoField(primary_key=True) User = models.ForeignKey(User, on_delete=models.CASCADE) Latitude = models.FloatField(blank=True, null=True, verbose_name='Latitude', default="00.0000000") Longitude = models.FloatField(blank=True, null=True, verbose_name='Longitude', default="00.0000000") Location = models.PointField(blank = True, null=True, srid=4326) City = models.CharField(max_length=50, default="") Street = models.CharField(max_length=60, default="") PostCode = models.CharField(max_length=60, default="") Residential = models.CharField(choices=NO_OF_HRS, max_length=60, default='1') def save(self, *args, **kwargs): self.Location = Point(self.Longitude, self.Latitude) super(Property, self).save(*args, **kwargs) -
Convert file extension to lowercase on upload wagtail
i have a problem while uploading images to wagtail admin panel. The issue is that if i upload a file with a capitalized extension like .JPG the file brakes. Is there a way of converting the format to lowercase on upload? -
Building a Django App without Default Auth and User and Use Admin
I am working on a application (Using Django and Django Rest Framewok) with has 3 services User Management Service Notification Service Payments Service Since i am handling User and Authentication in User Management Service itself (Using Token Based Authentication), so i don't need the default Authentication and User provided by django in other two services. In Notification service i have added a Custom Middle-ware which validates the token from User Management Service. How can i get rid of default User and Auth but still use the django Admin interface? I tried removing auth middle ware but getting error that admin requires that (for obvious reason). -
Fetch AWS lambda generated thumbnail in django template
I am trying to make a gallery page in django where thumbnails of images are dislayed but by clicking it the full size image open. For this purpose, I have an Image model with a ImageField where the full size image is stored: models.py class Image(models.Model): title = models.CharField(max_length=200) date = models.DateField(default=datetime.now) image = models.ImageField(upload_to='gallery_images/') When the file is uploaded to s3, it triggers a lambda function that create a thumbnail and save it in a subdirectory gallery_images/thumbnails/. My question is how can I fetch the thumbnail to display it in the template? The exact location in s3 is known but I need to get a URL that, I think, contains a unique id for s3 to authenticate me. -
Django - HELP!! Media images won't appear on the template screen
I need help with making images uploaded by users to appear on templates. I've been doing every solutions that I could find, but they all left me with nothing but broken images on the screen. The framework I'm currently using is Django and here are the codes consisting the program. I can upload other codes as well if requested. 'avatar' is the name for the profile image. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') views.py def signup(request): if request.user.is_authenticated: return redirect('movies:home') if request.method == 'POST': form = CustomUserCreationForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('movies:home') else: form = CustomUserCreationForm() context = { 'form':form, } return render(request,'accounts/forms.html',context) models.py class User(AbstractUser): nickname = models.CharField(max_length=30, unique=True, error_messages={'unique':"Sorry! This nickname is already in use TT"}) email = models.EmailField(verbose_name='email',max_length=255, unique=True, error_messages={'unique':"This email is already in use XD"}) description = models.CharField(max_length=40, blank=True) avatar = models.ImageField(upload_to = 'images', blank=True) profile.html => this is the template where users can see their own profiles as well as others' If a user had not uploaded any images to be set as their profile image, an image file that I had prepared in a static folder is set as their default image {% extends 'base.html' %} {% load static %} {% … -
Persistent Django's postresql database in Docker
I am learning Django by trying to create the polling app described on the Django's website. At the same time, I am using Docker for the first time and I have encountered problems trying to make PostgreSQL database, used by this app, persistent. According to the tips on using Docker with Django, found on the Docker website, I am running two services with docker-compose: one handling the database and the other the app itself (at least that's how I understand it). I have tried mounting a volume at the /var/lib directory inside the database container, where I found PostgreSQL directory. Although this directory became persistent, which I checked by creating some dummy files, migrations done via the web service are being erased every time I restart those containers. Below are my docker-copmpose.yml file and Django's settings.py. What should I do to make this database persistent? #docker-compose.yml version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - .:/code - .:/var/lib web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db #(...) # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': … -
Django refresh_from_db in transaction
I'm dealing with django legacy project, there is some usage of refresh_from_db method, inside of atomic transaction clause: with transaction.atomic(): self.refresh_from_db() The question is - will the refresh_from_db take existing values in DB? i.e ignoring the transaction and updating the instance? If so its kind of dangerous doing this kind of move