Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign key constraint on drop even thou on_delete=CASCADE
I can't see what's wrong with this, class Agenda(models.Model): ... class AgendaResource(PolymorphicModel): agenda = models.ForeignKey( Agenda, related_name="resources", on_delete=models.CASCADE ) comment = models.TextField(null=True) class PreemptiveMeasureResource(AgendaResource): resource = models.ForeignKey( PreemptiveMeasure, on_delete=models.SET_NULL, null=True ) ... When I try to delete an agenda, i.e. Agenda.objects.get(pk=2).delete() I get this problem: update or delete on table "school_health_agendaresource" violates foreign key constraint "school_health_preemp_agendaresource_ptr_i_222e2e2c_fk_school_he" on table "school_health_preemptivemeasureresource" DETAIL: Key (id)=(2) is still referenced from table "school_health_preemptivemeasureresource" What is it I don't understand? I'm guessing it's something to do with the inheritance? -
How can I edit the content in the home page?
Working on a small project using Django 3.2 and I just added an edit button to the page, so the user can edit the content. I did that with forms and views by rendering the user to another page and edit the content, but I was thinking is there a way possible to edit the content by not rendering user to another page? For a better understanding of what I have done so far, will show the code below: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class todo(models.Model): content = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) user = models.ForeignKey(User, on_delete=CASCADE, null=True) def __str__(self): return self.content forms.py class UpdateContent(forms.ModelForm): class Meta: model = todo fields = ['content']' views.py contents = todo.objects.get(id=pk) form = UpdateContent(instance=contents) if request.method == 'POST': form = UpdateContent(request.POST, instance=contents) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'html/update.html', context) home.html table class="table table-dark table-hover table-bordered"> <thead> <tr id="tr-table"> <th id="text-left">#</th> <th id="text-center">ITEMS</th> <th id="text-right"><i class="material-icons">&#xe872;</i></th> <th id="text-right2"><i id="edit" class="material-icons">&#xe3c9;</i></th> </tr> </thead> <tbody> {% for all_item in all_items%} <tr> <th id="row" scope="row"> {{ forloop.counter }} </th> <td id="content">{{ all_item.content … -
Change the Django Admin App List and Restrict Users from accessing models
I am trying to create a system in django admin model where admin can see all apps in django admin index. Staff can see only restricted apps. I was able to change the app list index for different roles, but for restricted user they can access directly through url. model.py class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(('first name'), max_length=30, null=True) last_name = models.CharField(('last name'), max_length=30, null=True) date_of_birth = models.DateField(null=True) date_joined = models.DateTimeField(('date joined'), auto_now_add=True) # avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) phone = PhoneNumberField(null=True) country = CountryField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) is_consumer = models.BooleanField(default=True) # premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True,blank=True, unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the … -
How to handle high response time
There are two different services. One service -Django is getting the request from the front-end and then calling an API in the other service -Flask. But the response time of the Flask service is high and if the user navigates to another page that request will be canceled. Should it be a background task or a pub/sub pattern? If so, how to do it in the background and then tell the user here is your last result? -
HTTP Redirects Preventing Twilio From Sending Digits Parameter
I created a Django app which uses if/else statements in multiple views. The else statements contain response.redirect("/previous_view"). If the else statement is ran it generates 3XX HTTP codes and causes Twilio not to include the Digits parameter in the POST body which causes my "if" statements to fail. How do I fix this? Twilio is a well-behaved HTTP client, so when it receives an HTTP 301 or 302 redirect it will follow it to the specified URL. However, on the subsequent request the original parameters are not included. Occasionally you may see parameters such as Digits or RecordingUrl not arriving where you expect them. In this case, check to make sure the URL is not returning a redirect. As an example, when a request is made to the action URL, a Digits parameter is included in the POST request. If the action URL redirects to another URL, Twilio will follow the redirect and issue a GET request to the specified URL. This GET request will include the standard set of parameters included with every Twilio request, but will not include the additional Digits parameter. Common situations that may return unexpected redirects are: A server that automatically redirects all HTTP requests … -
Should I use AWS for my Redis Broker or Heroku (Django app using Celery)?
I'm a very beginner dev and I'm a bit confuse. Here's my situation: I have a Django web app running on a AWS EC2 server. I have a specific view function that renders results using Spotify API and some results take 30 seconds to be rendered. I've heard that Celery could help me create a loading bar system to let the clients know how the loading is going. I have to use a message broker and Redis seems to be a good one. All the tutorials I saw are using Heroku as a host, but I'm already using AWS. I didn't find any resources speaking about AWS + Redis in the case where Redis is used as a Broker with Celery in Django, but I know that Redis + AWS is something common for cache. Can I use AWS for this purpose? If yes, is it worth it compares to Heroku (which seems very simple)? Btw, cache seems to be a good solution for my long loading issue, so I might also use Redis for cache handling. -
multiple contexts in single html with Listview
I have 4 types of tickets to display on my dashboard Open,accept,complete and closed i have written the below template view to display all the contexts with one single view how do i write my html file in one single html that has same headers for all the data but differes in the table data i have implemented one but thats not working showing closed tickets in all the urls for open,accepted,completed etc or suggest me whether i have to change something within view Views.py class DeveloperTicketView(ListView): template_name = 'app/ticket_view.html' def get_context_data(self, **kwargs): context = super(DeveloperTicketView,self).get_context_data(**kwargs) context['open_tickets'] = Ticket.objects.filter(status = 'Opened') context['accepted_tickets'] = Ticket.objects.filter(status = 'Accepted',accepted_by = self.request.user) context['completed_tickets'] = Ticket.objects.filter(status = 'Completed',accepted_by = self.request.user) context['closed_tickets'] = Ticket.objects.filter(status = 'Closed',accepted_by = self.request.user) return context ticket_view.html {% extends 'app/base.html' %} {% block body %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Created</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for ticket in open_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title }}</td> <td>{{ ticket.ticket_description }}</td> <td><a href="{% url 'accept_tickets' pk=ticket.id %}">Accept</a> </tr> {% endfor %} </tbody></table> <tbody> {% for ticket in accepted_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title … -
Aggregation using relations and __last in Django
I need to find out how to filter the amount of new customers in a specific store, filtered by days. I tried a few aggregations, but none seemed to work. See code below # query all orders in a specific store by day (simplified) orders = Order.objects.filter(created_at_gte=today, created_at_lt=tomorrow, store=store) # filter all unique customers customers = [] for order in orders: if not order.customer in customers: customers.append(order.customer) # iterate all customers, looking for the oldest order for each one in that store and count as a new client if this oldest order is between the dates being looked up new_customers = 0 for customer in customers: oldest_order = customer.orders.filter(store=store).prefetch_related('store').last() is_new = (tomorrow > oldest_order.created_at > today) if is_new: new_customers += 1 print(new_customers) However, this code takes too long due to the iteration in: oldest_order = customer.orders.filter(store=store).prefetch_related('store').last() I believe something like the below would work, but "__last" doesn´t work here. Order.objects.filter(store=store, created_at__gte=today, created_at__lt=tomorrow).annotate(Count('customer__orders__last', distinct=True)) Thanks! -
How to display/see the default values in Admin for translated fields using Django's modeltranslation
I'm trying to translate some models in an existing project, and I'm learning how to do that using the modeltranslate extension. To experiment, I've added Spanish as an additional language to English and set English as a default in the settings.py: INSTALLED_APPS = [ ... 'modeltranslation', 'django.contrib.admin', 'debug_toolbar' ... ] gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('es', gettext('Spanish')), ) MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'en' MODELTRANSLATION_AUTO_POPULATE = True The model: class Equipment(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name admin.py: class EquipmentAdmin(TranslationAdmin): ordering = ('name',) translation.py: @register(Equipment) class EquipmentTranslationOptions(TranslationOptions): fields = ('name',) When trying to edit an Equipment object now in the dashboard, I see two empty text fields with the following names: But the original name field and its value are not shown. Even in the model's table now there are no names displayed at all as can be seen here: Questions: How can I see the original value of these translated fields? How do I keep seeing Equipment names in the overall model's view (the second screenshot)? -
How to add status to google registered accounts?
I have a registration with 2 categories of users. Before filling in the fields, I have to choose which category I want. If you fill in the fields (email, username, password, etc.) it is saved in the database all the information (even the status). If I choose a certain category of user and I want to register with the account Google, the account is registered but nothing is added to the status. The button that directs me to register looks like this: <a class="btn btn-primary" name = "status" href="{% url 'registerClient' %}" role="button" value = "Client">Client</a> Google registration button: <a href="{% provider_login_url 'google' %}" class="btn float-right login_btn" name='status' value= "Client" type = 'submit'>Login With Google</a> I also tried such a button: <button class="btn float-right login_btn" name='status' type="submit" value='Client'><i class="fas fa-user-plus"></i> Client </button> I also tried after registering with my google account to choose the status again (pressing a button depending on my choice), but nothing is saved in the database. in column status. Note that I use allauth (I installed everything and set it up properly). The only problem is that the status is not saved in db (and I really want that). Any ideas on how I could save … -
How can I translate DJANGO datatables?
For example, I have this footer menu that needs to be translated: -
How to detect that django is being called with "manage"
I have a django codebase, and on startup in apps.py I do some database operations. However, I need to not perform this if django has been started with the "manage" option. How can I detect this within apps.py? -
My app is not showing in Django admin panel
I have problem with Django admin panel. I have two apps: 'users' and 'advertisements'. App 'users' was installed before app 'advertisements'. Both apps are included in 'INSTALLED_APPS', but in admin panel showing only app 'users'. What problem can it be? Thanks a lot. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'users.apps.UsersConfig', 'advertisements.apps.AdvertisementsConfig', ] advertisementes/apps.py from django.apps import AppConfig class AdvertisementsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'advertisements' advertisements/admin.py from django.contrib import admin from .models import * class AdvertisingSpaceAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'description', 'slug', 'data', 'user') admin.site.register(AdvertisingSpace, AdvertisingSpaceAdmin) -
How to get value from Django view into Ajax success function
I have a django application where a user can upload a file on form submit. When the file is uploaded the program will get the column names from the csv file and display that in the Django Template This is my views def handle_new_file(request): if (request.method == 'POST'): form = NewFileForm(request.POST, request.FILES) if form.is_valid(): csv_file = request.FILES['csv_file'] fs = FileSystemStorage() file_name = fs.save(csv_file.name, csv_file) file_url = f"./media/file_uploads/{file_name}" print(file_name) print(file_url) cols = get_column_names(file_url) form.save() return HttpResponse(cols) While the above view is called successfully on form submit, I am not able to pass this cols data back to the template. Here is my Ajax code function upload(event) { event.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { alert(data); } }); return false; } $(function () { $('#new_form').submit(upload); }); What am I doing wrong? -
How to patch (or mock) Django’s ImageField form field’s properties?
I have a model which includes an ImageField (lets call it my_project.models.Profile) and a corresponding form (my_project.forms.ProfileForm). Let us say the name of the model’s field is picture. I am writing tests for the form and need to test the handling of the content_type property of the form's ImageField file underlying object, by my own project. For the life of me, I cannot work out where I would patch this property, to test the different scenarios. What I figured out: django.forms.fields.ImageField has a method to_python which transforms the uploaded binary data into an actual image file (https://github.com/django/django/blob/aec71aaa5b029640ce066fe5dc34f7a0050d50b2/django/forms/fields.py#L621). It uses PIL.Image to do so. Once the image is successfully opened by Pillow, the file object to be returned by to_python is assigned the content_type property, taken out of the PIL.Image.MIME dictionary (https://github.com/django/django/blob/aec71aaa5b029640ce066fe5dc34f7a0050d50b2/django/forms/fields.py#L653). What would be the correct path for mock.patch? -
Printing matplot graph in django?
Views.py:- from django.shortcuts import render, HttpResponse from tweetanalysis import tweety import matplotlib.pyplot as plt import pandas as pd import base64 from io import BytesIO # Create your views here. def index(request): return render(request, 'index-search.html') def result(request): if request.method == 'POST': query = request.POST.get('hashtage') df = tweety.Analyzer(query) plt.figure(figsize=(8, 6)) for i in range(0, df.shape[0]): plt.scatter(df.loc[i, 'Polarity'], df.loc[i, 'Subjectivity'], color='Blue') plt.title('Sentiment Analysis') plt.xlabel('Polarity') plt.ylabel('Subjectivity') buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() ans1 = base64.b64encode(image_png) ans1 = ans1.decode('utf-8') buffer.close() plt.title('Sentiment Analysis') plt.xlabel('Polarity') plt.ylabel('Subjectivity') df['Analysis'].value_counts().plot(kind='bar') buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() ans2 = base64.b64encode(image_png) ans2 = ans2.decode('utf-8') buffer.close() return render(request, 'result.html', {'chart': ans1, 'plot': ans2}) else: return HttpResponse("Error!") result.html:- {% extends 'base.html' %} {% block content %} {% if chart %} <img src="data:image/png;base64, {{chart|safe}}" /> {% endif %} <br /> {% if plot %} <img src="data:image/png;base64, {{plot|safe}}" /> {% endif %} {% endblock %} here df in dataframe. I am making a tweet sentiment analysis web app For that I want to print my matplot graphs in frontend as a result in django but error arises name 'posts' is not defined. Here in my code my sentiment analysis code return dataframe contains tweets polarity subjectivity. I want to show … -
Django looping through items not showing
Hi I am looping through items being passed through the context but nothing is showing. This is what I am passing: {"error":[],"result":{"USDT":"60000.00000000","CHZ":"13773.0349000000","ZRX":"0.0000000000","ZUSD":"67787.8285","DOT":"0.0000000000","COMP":"0.0000034600","ENJ":"257.6815000000","ADA":"2473.80445621","XXDG":"17006.92601155","ALGO":"32063.69514500","XXBT":"0.0000012880","SUSHI":"172.4585500000","SOL":"1133.3543869800","DASH":"0.5104491200","LINK":"144.2407000000","ATOM":"151.26763831","XXLM":"6926.27220000","XXRP":"0.00000000","XETH":"14.5877343640","TRX":"923.80015900","KNC":"0.0000000000","BAL":"0.0000000000","XLTC":"11.4923900000","KSM":"24.7142610000","SC":"0.0000000200","OCEAN":"652.6077000000","MATIC":"1838.9295772000","AAVE":"83.6218990800","ZGBP":"30622.0790","XZEC":"0.0000073100"}} And inside my template I have this: {% for k, v in api_reply.items %} <tr> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endfor %} I have no errors showing but it is not displaying, any help would be great thank you. -
Django- Duplicated queries in nested models querying with ManyToManyField
How do I get rid of the duplicated queries as in the screenshot? I have two models as following, class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name class Game(models.Model): name = models.CharField(max_length=50) genre = models.ManyToManyField(Genre, blank=True, related_name='games') def __str__(self): return self.name and have a serializer and views, class GameSerializer(serializers.ModelSerializer): class Meta: model = Game exclude = ['genre', ] class GenreGameSerializer(serializers.ModelSerializer): children = RecursiveField(many=True) games = GameSerializer(many=True,) class Meta: model = Genre fields = ['id', 'name', 'children', 'games'] class GamesByGenreAPI(APIView): queryset = Genre.objects.root_nodes() serializer_class = GenreGameSerializer def get(self, request, *args, **kwargs): ser = GenreGameSerializer(data=Genre.objects.root_nodes() .prefetch_related('children__children', 'games'), many=True) if ser.is_valid(): pass return Response(ser.data) so basically the model populated when serialized looks like this The result is what I am expecting but there are n duplicated queries for each of the genre. How can I fix it? Thanks.. here is a paste https://pastebin.com/xfRdBaF4 with all code, if you want to reproduce the issue. -
How to display video and image in same Carousel Slider based on what user have uploaded- Django
I'm trying to build a Instagram Clone using Django. If user uploads video and image for a single post and then I want to display both image and video in single Carousel slider. Do you guys have any idea. How to implement such functionality. Models.py User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, models.CASCADE) caption = models.CharField(max_length=50) post_id = models.CharField(max_length=10) post_media = models.FileField(blank=True) # post_images = models.ManyToManyField('PostFiles', null=True, blank=True) timestamp = models.DateTimeField() # Will be de-activated if found suspicious is_active = models.BooleanField(default=True) likes = models.ManyToManyField(User, related_name='post_likes') comments = models.ManyToManyField('comment', related_name='post_comments') def __str__(self): return self.user.username def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): if not self.post_id: self.post_id = ''.join(random.choices( string.ascii_uppercase + string.digits, k=8)) return super().save(*args, **kwargs) class PostFiles(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) post_media = models.FileField(upload_to='post_media/') def __str__(self): return self.post.caption -
Why does it show TypeError: UpdateContent() got an unexpected keyword argument 'instance'?
Working on a simple project in Django 3.2 and trying to add an edit button, to edit the content of the page. To do that I did: views.py def UpdateContent(request, pk): contents = todo.objects.get(id=pk) form = UpdateContent(instance=contents) if request.method == 'POST': form = UpdateContent(request.POST, instance=contents) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'html/update.html', context) forms.py class UpdateContent(ModelForm): class Meta: model = todo fields = ['content'] home.html <table class="table table-dark table-hover table-bordered"> <thead> <tr id="tr-table"> <th id="text-left">#</th> <th id="text-center">ITEMS</th> <th id="text-right"><i class="material-icons">&#xe872;</i></th> </tr> </thead> <tbody> {% for all_item in all_items%} <tr> <th id="row" scope="row"> {{ forloop.counter }} </th> <td id="content">{{ all_item.content }}</td> <form action="delete_todo/{{all_item.id}}/" method="post"> {% csrf_token %} <td class="text-right-delete"> <button id="btn-delete" class="btn btn-outline-danger">Delete</button> </td> </form> <td><a class="btn btn-outline-info" href="{% url 'todo:update' all_item.id %}">Edit</a></td> </tr> {% endfor %} </tbody> </table> update.html {% extends 'html/main.html' %} {% load static %} {% block content %} <form action="", method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Submit"> </form> {% endblock %} But when I run the code it shows me this error TypeError: UpdateContent() got an unexpected keyword argument 'instance' Would appreciate any response or suggestion. Thanks! -
How do I handle foreign key relationship in the urlpattern in the django-rest-framwork
In my models.py I have the following classes: class Project(models.Model): name = models.CharField(max_length=100) class ProjectMaterial(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE) material = models.CharField(max_length=150) units = models.IntegerField() My serializers are like this: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = "__all__" class ProjectMaterialSerializer(serializers.ModelSerializer): class Meta: model = ProjectMaterial fields = "__all__" My current views.py looks like this: class ProjectList(generics.ListCreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectMaterialList(generics.ListCreateAPIView): queryset = ProjectMaterial.objects.all() serializer_class = ProjectMaterialSerializer How should I create my urlpatterns to make a PUT request to change the units value for a project with an id=1 for a material with an id=3? -
Django how do we send a model into javascript and render it onto a template
I'm trying to pass a Django model into a template using javascript. I can't seem to filter or do anything with the QuerySet once I get the javascript to read it and pass it on to the template. My html file: <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat}}"; var lastEntry = "{{last}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry; } </script> The result I get after 2 seconds: 2 seconds <QuerySet [<ChatStream: ChatStream object (31)>, <ChatStream: ChatStream object (32)>]>lastEntryChatStream object (31) Instead of showing "<QuerySet [<ChatStream: ChatStream object (31)>....] " How do I show the text inside the model named ChatStream?... I've tried: <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat.user}}"; var lastEntry = "{{last.user}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry; } </script> But the above displays nothing. I've also tried <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat | last }}"; var lastEntry = "{{last}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + … -
File upload Django form is not valid
I have a Django Model as follows class NewFile(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=200) address = models.CharField(max_length=1000) csv_file = models.FileField(upload_to ='retailer_uploads/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name And a Django form as follows class NewFileForm(forms.ModelForm): class Meta: model = NewFile fields = ('name', 'phone', 'address', 'csv_file') This is my Django views def handle_new_file(request): if (request.method == 'POST'): form = NewFileForm(request.POST, request.FILES) if form.is_valid(): form.save() csv_file = request.FILES['csv_file'] fs = FileSystemStorage() csv_file_name = fs.save(csv_file.name, csv_file) csv_file_url = fs.url(csv_file_name) return redirect('home') And lastly my template <form action="{% url 'handle_new_file' %}" method='post' enctype="multipart/form-data" id='new_form'> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{ new_file_form.name|as_crispy_field }} </div> <div class="col-md-6"> {{ new_file_form.phone|as_crispy_field }} </div> </div> {{ new_file_form.address|as_crispy_field }} {{ new_file_form.ean_mapping|as_crispy_field }} {{ new_file_form.retailer_file|as_crispy_field }} <div class="d-grid gap-2"> <button class="btn btn-primary" type="submit">Submit</button> </div> </form> Firstly the issue I am facing is that, for some reason this form is not valid as it is not getting saved. Not sure why. But what I want to do is after the form is saved, I want to open the csv file from the media folder and get the column names from the file. I have the helper function to that. The problem is I am … -
How does Django find template?
Below is my urls.py in mysite/mysite/settings.py urlpatterns = [ path('', TemplateView.as_view(template_name='homepage/main.html')), path('admin/', admin.site.urls), # add something path('polls/', include('polls.urls')), path('hello/', include('hello.urls')), path('accounts/', include('django.contrib.auth.urls')), # Add, Search how does djnago find template. path('autos/', include('autos.urls')), ] If some user request www.mysite.com/accounts/login This request go to 'django.contrib.auth.urls' in there request go to path('login/', views.LoginView.as_view(), name='login') not in django/contrib/auth/urls.py.. But my login template is in mysite/homepage/templates/registration/login.html And below is my login.html {% extends "base_bootstrap.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} It works well. so I don't know how Django find my login.html How does Django find my login.html? -
How to load bootstrap styles in Django
ingestion-dashboard/ ├── apps │ ├── adapter │ ├── authentication | |__init__.py │ ├── static │ │ ├── assets │ │ │-- css │ │ │── img │ │ │── scss │ │ │── vendor │ └── templates │ ├── accounts │ ├── home │ ├── dashboard │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └───staticfiles ├── assets │── css │── img │── scss │── vendor settings.py CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ingestion-dashboard STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) With this layout, django works fine with local server with proper loading of bootstraps and styles. But when i ran this on kubernetes/nginx , the app is working fine but missing bootstraps, styles. The staticfiles dir in ingestion-dashboard/dashboard/staticfiles is being populated by command django-admin manage.py collectstatic. Any help is appreciated. I have loaded styles as <script src="/static/assets/vendor/@popperjs/core/dist/umd/popper.min.js"></script> works fine with local development.