Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Lazy load pagination in django
I have a function that makes 100 queries to an API, however there is a rate limit of something like 15 requests per second. Therefore, I tried using Django EL(Endless) Pagination in order to get something like Twitter style pagination. The effect I wanted was something in which by default it would only show the first ten items, and once the user scrolls to end, it would load the next ten items. However, it seems that pagination only paginates the template, not the view in which the data is requested. It seems that what the pagination is doing is: Call the function to send 100 queries. Display first 10 elements. When user reach the end, call again the function to send 100 queries. Show another 10 elements. Basically, each time the next page is requested, the view function is called. The view function is something like this: def user_info(request, user_account, template="entry_list.html"): # Function that makes the 100 requests entry_list = helpers.get_summary_list(user_account) context = { "entry_list": entry_list, } if request.is_ajax(): template = "entry_list_page.html" return render(request, template, context) Then in the template: {% load el_pagination_tags %} {% lazy_paginate entries %} {% for entry in entries %} {# your code to show the … -
gjongo gjango admin list field
models.py: from djongo import models class Passenger(models.Model): _id = models.ObjectIdField() first_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) class Bus(models.Model): _id = models.ObjectIdField() bus_driver = models.CharField(max_length=100, blank=False, null=False, unique=True) passengers = models.ArrayField(model_container=Passenger) admin.py: from django.contrib import admin # Register your models here. from .models import Bus @admin.register(Bus) class BusAdmin(admin.ModelAdmin): list_display = ('bus_driver',) I would like in Django Admin to be able to add passengers to the bus. The bus can be without passengers too. How can I do it? Currently, there is something wrong with the code that does not allow to do it: zero passengers, i.e. zero list is not allowed. Plus the add new passenger button does not exist, i.e. I can not add several passengers. -
I want to convert data from json file to another file
I want to convert data from json file to another file, so I had to use ('for in') because there is a lot of data with different value. The problem is that it displays the same value in different data def pms(request): n= open('./templates/pmsResponse.json') file =json.load(n) guest = dict () newguests = list () newroom=list() for x in file : guests=x['Guests'] for g in guests : guest["guest_id_pms"] = g['Number'] newguests.append ( guest ) data={ "guests" : newguests, } return JsonResponse(data) -
Django-contrib-comments fails to get authenticated user
I'm currently implementing django-contrib-comments and the post_comment view can't figure out the current authenticated user (to say it in my rookie words). I attached the comment form to my object poller which itself has a foreign key to my user model Account. AttributeError at /comments/post/ 'Account' object has no attribute 'get_full_name' class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) [..] The post_comment view fails here: def post_comment(request, next=None, using=None): data = request.POST.copy() if request.user.is_authenticated: if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.get_username() # fails here My custom user model inherited from AbstractBaseUser: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) [..] -
Django+Vue+webpack configuration
I'm trying to setup a project but somehow I cannot properly connecting my backend to my frontend dev.py : from .settings import * DEBUG = True ALLOWED_HOSTS = ["*"] MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware") INSTALLED_APPS.append("debug_toolbar") INTERNAL_IPS = ("127.0.0.1", "localhost") WEBPACK_LOADER = { "DEFAULT": { "BUNDLE_DIR_NAME": "", "STATS_FILE": os.path.join(BASE_DIR, "frontend/webpack-stats.json"), # 'STATS_FILE': BASE_DIR.joinpath('frontend', 'webpack-stats.json'), } } STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = "/dmedia/" MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") VUE_ROOT = os.path.join(BASE_DIR, "frontend\\static\\") CUT FROM settings.py : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) STATICFILES_ROOT = os.path.join(BASE_DIR, "staticfiles") # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "ObjectMgr", "webpack_loader", ] ROOT_URLCONF = "ObjectMgr.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "ObjectMgr.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "/static/" index.html : {% load render_bundle from webpack_loader %} {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frontend</title> <meta http-equiv=X-UA-Compatible content="IE=edge"> <meta name=viewport content="width=device-width,initial-scale=1"> … -
passing django database entries into messages within the line messenger api (linebot)
i would like the linebot to send all classes stored in the database, on a given a particular day, depending on the user input, through line messenger. e.g user types "hello" linebot responds with "hello" user types "monday" linebot sends monday's class schedule user types "studentlist(tutorname)" linebot sends all students in the list of that tutor so far, i can receive the echo, the linebot is storing the user data corectly in the model database too. the bot can differentiate between message type. (i.e "text", "image" etc) everything i seem to do stops the main messages being sent. How would be best to write the loops required to get my desired reponse? I was hoping to using the information in this way and pass that somehow into the message data = Lessons.objects.all().filter(headed_by__name="Tutor Name").filter(day__icontains="Monday") below is not working, and stops the rest of the elif functions from working. elif event.message.type=="text" | event.message.text=="Monday" : message.append(TextSendMessage(text='Monday? Coming right up')) line_bot_api.reply_message(event.reply_token,message) and this is the code that i am using to receive the messages currently @csrf_exempt def callback(request): if request.method == "POST": message=[] signature=request.META['HTTP_X_LINE_SIGNATURE'] body=request.body.decode('utf-8') message.append(TextSendMessage(text=str(body))) try: events = parser.parse(body,signature) except InvalidSignatureError: return HttpResponseForbidden() except LineBotApiError: return HttpResponseBadRequest() for event in events: if isinstance(event, … -
Postgresql database server keeps shutting down randomly
During last two days, it's been five or six times which my postgres database server was shut down unexpectedly, often when server traffic was at the lowest level. So i checked postgresql log: 2021-09-18 10:17:36.099 GMT [22856] LOG: received smart shutdown request 2021-09-18 10:17:36.111 GMT [22856] LOG: background worker "logical replication launcher" (PID 22863) exited with exit code 1 grep: Trailing backslash kill: (28): Operation not permitted 2021-09-18 10:17:39.601 GMT [55614] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.603 GMT [55622] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.686 GMT [55635] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.688 GMT [55636] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.718 GMT [55642] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.720 GMT [55643] XXX@XXX FATAL: the database system is shutting down kill: (55736): No such process kill: (55741): No such process (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Failed to stop c3pool_miner.service: Interactive authentication required. See system logs and 'systemctl status c3pool_miner.service' for details. pkill: killing pid 654 failed: Operation not permitted pkill: killing pid 717 … -
no such column: users_profile.user_id - Django
I have created an app in my Django project called users, and I have created a model called Profile. After registering the app in the admin panel also install the app in the setting.py and created the view for it. When I click on the profile inside the 8000/admin/user/Profile I get the following error: OperationalError at /admin/users/profile/ no such column: users_profile.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/users/profile/ Django Version: 3.2.6 Exception Type: OperationalError Exception Value: no such column: users_profile.user_id Exception Location: C:\Users\Serage\Desktop\devsearch\env\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Serage\Desktop\devsearch\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\Users\Serage\Desktop\devsearch', 'c:\users\serage\appdata\local\programs\python\python39\python39.zip', 'c:\users\serage\appdata\local\programs\python\python39\DLLs', 'c:\users\serage\appdata\local\programs\python\python39\lib', 'c:\users\serage\appdata\local\programs\python\python39', 'C:\Users\Serage\Desktop\devsearch\env', 'C:\Users\Serage\Desktop\devsearch\env\lib\site-packages'] Server time: Sat, 18 Sep 2021 13:59:55 +0000 My profile code is: *from django.db import models from django.contrib.auth.models import User import uuid Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True)> bio = models.TextField(blank=True, null=True) profile_image = models.ImageField(null = True, blank = True, upload_to='profiles/', default="profiles/user-default.png") social_github = models.CharField(max_length=500, null=True, blank=True) social_github = models.CharField(max_length=500, null=True, blank=True) social_linkedIn = models.CharField(max_length=500, null=True, blank=True) social_youtube = models.CharField(max_length=500, null=True, blank=True) social_website = models.CharField(max_length=500, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def … -
Exception Value: no such column: noticia_tb.id
I made a scraping application using scrapy, to scrape the news from a page, I put it to create a sqlite database, and then I made a django api to consume this database and make a link available in json, however when I upload the application from the following error: OperationalError at /news/ no such column: noticia_tb.id So I opened the database file and noticed that the ID was not generated, how do I generate this ID or use it without? follow my moldels.py class NoticiaTb(models.Model): title = models.TextField(blank=True, null=True) subtitulo = models.TextField(blank=True, null=True) url = models.TextField(blank=True, null=True) data = models.TextField(blank=True, null=True) image_url = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'noticia_tb' follow the scrapy project pipeline class ApinoticiaPipeline(object): def __init__(self): self.create_connection() self.create_table() def create_connection(self): self.conn = sqlite3.connect("myapinoticia.db") self.curr = self.conn.cursor() def create_table(self): self.curr.execute("""DROP TABLE IF EXISTS noticia_tb""") self.conn.execute("""create table noticia_tb( title text, subtitulo text, url text, data text, image_url text )""") def process_item(self, item, spider): self.store_db(item) return item def store_db(self, item): self.curr.execute("""insert into noticia_tb values (?,?,?,?,?)""",(str(item['title'][0]),str(item['subtitulo'][0]),str(item['url'][0]),str(item['data'][0]),str(item['image_url'][0]))) self.conn.commit() -
djongo Company with ID “None” doesn’t exist. Perhaps it was deleted?
I couldn't find a solution among similar questions. Using mongosh, the Company objects do exist, but in the admin, they show as object(None) and therefore cannot be edited due to error "Company with ID “None” doesn’t exist. Perhaps it was deleted?". I guess it is about the "id" detection, but can not fix it myself. Question: how to fix the code to make the Company object to be shown correctly, not as None. myproject> db.companies_company.find() [ { _id: ObjectId("6145dd9a8bc9a685b2ae2375"), name: 'company1' }, { _id: ObjectId("6145ddaa8bc9a685b2ae2377"), name: 'company2' } ] models.py: from django.db import models # Create your models here. class Company(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) admin.py: from django.contrib import admin # Register your models here. from .models import Company @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): pass -
How to download a file from my media root folder to my phone or computer
Anytime i click on the download link of the mp3 files or images, instead of them starting to download but they just start to preview on the browser. I want when i click on the url "http://localhost:8000/s/download_rdr/1/" and the file "http://localhost:8000/s/media/music.mp3" starts downloading but all it does is to start playing in the browser. My views.py class DownloadRdr(TemplateView): def get(self, request, pk, *args, **kwargs): item = Item.objects.get(id=pk) #Return an mp3 return redirect('http://localhost:8000/s/media/music.mp3') -
date field value disappears when changing language Django
i'm using this modelform to save the users info class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' widgets = { 'date_of_birth': DateInput(), 'first_name': forms.TextInput(attrs={'placeholder': _('first Name')}), 'address': forms.TextInput(attrs={'placeholder': _('Street')}), } def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['address'].widget.attrs['class'] = 'form-control' self.fields['date_of_birth'].widget.attrs['class'] = 'form-control' self.fields['image'].widget.attrs['class'] = 'form-control p-1' i always use this class which allows me to add a datepicker to the "date of birth" field class DateInput(forms.DateInput): input_type = 'date' it works fine with the English language but when i change the language to french the field stops rendering the value it just keeps showing empty. so in english it looks like this on the same view when i change the language to french it shows like this when i use chrome dev tools i can see that field has a value of the correct date and the console gives a warning message like this 127.0.0.1/:892 The specified value "21/09/2021" does not conform to the required format, "yyyy-MM-dd". I think my problem occurs because the format changes between languages, so is there any way to stop the date format from changing or configure the date input in the form to use one date format on all languages,or any … -
How to handle two SAME form on one page Django views
I pass multiple forms to one template like this, (NOTE THAT address_form and shipping_address_form are same FORM) # views.py class CartListView(generic.ListView): ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['companies_json'] = serializers.serialize( "json", Item.objects.all()) address_form = AddressForm() shipping_address_form = AddressForm() order_form = OrderForm() context['address_form'] = address_form context['order_form'] = order_form context['shipping_address_form'] = shipping_address_form return context In my template i have ONE form tag(due to fact that i want only ONE button to submit them) # template.html <form class="form" action="/payment/" method="POST"> {% csrf_token %} {{ address_form }} {{ shipping_address_form }} question is how to handle them in views.py if i do it like below, it selects only LAST form so address_form and shipping_address_form has values from shipping_address_form (FROM TEMPLATE) #views.py def payment_handler(request): if request.method == 'POST': addres_form = AddresForm(request.POST) shipping_addres_form = AddresForm(request.POST) if addres_form.is_valid(): if i print(request.POST) it shows that it has both address_form and shipping_address_form stored in List, how can i select in views.py which one AddresForm shoud check? 'name': ['Test 1', 'test 2'], 'surname': ['frank', 'albertson'] -
How to annotate related object with MAX by some attribute
class Bill number = CharField class Service number = CharField bill = ForeignKey(order, related_name="bill_services") price = IntegerField bills = Bill.objects.prefetch_related('bill_services').annotate(service_number_with_max_price=....) Hello. How can I annotate a service number with max price for each Bill. I want to use it for something like that: {% for bill in bills %} {{ bill.service_number_with_max_price }} {% endfor %} -
Djongo keeps closing and creating new MongoClient DB connections with each request
I'm using djongo to connect my Django REST framework API with my MongoDB cluster, and when logging the requests at DEBUG level, I see that djongo starts every request by closing the existing MongoClient connection, creating a new connection, doing the query, then closing the connection again. 2021-09-18 13:41:34,714 - DEBUG - djongo.base - Existing MongoClient connection closed 2021-09-18 13:41:34,715 - DEBUG - djongo.base - New Database connection 2021-09-18 13:41:34,716 - DEBUG - djongo.sql2mongo.query - sql_command: ... 2021-09-18 13:41:35,340 - DEBUG - djongo.sql2mongo.query - Aggregation query: ... 2021-09-18 13:41:35,343 - DEBUG - djongo.sql2mongo.query - Result: ... 2021-09-18 13:41:35,454 - DEBUG - djongo.base - MongoClient connection closed Why does it close the connection with every request and how can I stop this behavior? It should initiate the DB connection when the web server starts and keep using that connection for all the requests, instead of creating hundreds of connections each second. Relevant codes from djongo/base.py: if self.client_connection is not None: self.client_connection.close() logger.debug('Existing MongoClient connection closed') self.client_connection = Database.connect(db=name, **connection_params) logger.debug('New Database connection') def _close(self): """ Closes the client connection to the database. """ if self.connection: with self.wrap_database_errors: self.connection.client.close() logger.debug('MongoClient connection closed') For the installation and configuration, I've followed the djongo GitHub … -
Django rest framework, returning item status booked or free based on current date/time
I am currently working on a website for my students where it will help them to book some items on the classroom. I am already done with the booking logic and form so no two students are allowed to book the same item at the same time. I would like to create a table for them where it shows the item name and the status of the item based on the current time. So I have a webpage/django view that have a list of all the booking made including the item name, starting date, ending date, and the person who booked the item. So, based on this booking list, I would like to create some logic that will go through this booking list and compare it against the current time/date. In simple words, if the current time/date falls in between the start and end date of a booked item , it should return the value "booked" other wise "free". I am not sure how to achieve this. I brainstormed for days, and search the Internet for some hints but nothing. I would be very thankful if someone helped me. This is my models: class Items(models.Model): ITEMS_CATEGORIES=( ('item-1', 'item-1'), ('item-2', 'item-2'), … -
Proper Celery Monitoring and File-Management with Web-Services
We are working on an Internet and Intranet platform, that serves client-requests over website applications. There are heavy-weight computations on database entries and files. We want to update the state of those computations via push-notification to the client and make changes to files without the risk of race-conditions. The architecture is supposed to run on both, low- scaled one-server environments and high-scaled cluster environments. So far, we are running a Django Webserver with Postgresql, the Python-Library Channels and RabbitMQ as Messagebroker. Once a HTTP-Request from a client arrives in Django, we trigger the task via task.delay() and immediatly return the task_id to the client. The client then opens a websocket to another Django-route and hands over the task_ids he is interested in. Django then polls the state of the task via AsyncResult(task_id).state. Once the state changes, we read the results via AsyncResult(task_id).get and push the task_results to the client. Here a similar sequence diagramm, from another project I found online. Source(18.09.21) Something that is not seen on the diagram, the channels_worker have to fetch the file they are working on from Django. A part of the result is not for the client, but to update the file. Django locks and … -
getting Error running WSGI application NameError: while i deployed my DJango app to pythonanywhere?
Complete error 2021-09-18 10:35:44,065: Error running WSGI application 2021-09-18 10:35:44,068: NameError: name 'get_wsgi_application' is not defined 2021-09-18 10:35:44,068: File "/var/www/dhruv354_pythonanywhere_com_wsgi.py", line 30, in <module> 2021-09-18 10:35:44,068: application = get_wsgi_application() my wsgi.py file import os import sys path = '/home/dhruv354/Django-grocery/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'ReadingRight.settings' from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(get_wsgi_application()) Everything seems fine to me but still it is giving this error, needs help -
How to count total objects in a django model
I am trying to get total number of items in my model which i will be displaying in my base template as a footer. heres my code. VIEW: def showthis(request): count= Item.objects.all().count() context= {'count': count} return render(request, 'waqart/footer.html', context) TEMPLATE: <h1 class="text-4xl md:text-6xl text-gray-700 font-semibold">UX/UI Components {{count}}</h1> -
Django Dynamic Formet form count
I have been working on Django Model Formset, where I have two models 1: Institutional Objectives and 2: Sub Institutional Objectives. I have used the Model formset here. Using the add_more_subobjective button user can multiple sub_institutional_objective forms under one institutional_objective form (I am using Django Dynamic Formset for this, refer here) Problem: When a user adds sub_objective form I want to show him the count of that form, example [As in image: I am getting Subobjective as 1 for all forms image But I want the user to see it like this result_image form.html <form method="post"> {% csrf_token %} <div class="card"> <div class="card-header"> <h4>Add Insititutional Objectives</h4> </div> <div class="form-group" style="margin: 40px;"> {{ form.non_form_errors }} {{ form.as_p }} {{ subobjective.non_form_errors }} <hr> <h4>Sub Objectives</h4> <h6>These are Sub Objectives of this particular IO</h6> {{ subobjective.management_form }} <div class="form-group nested-query-formset"> <h6>Sub Objective {{ count }} </h6> {{ subobjective.as_p }} </div> </div> </div> <div class="mt-3 mb-5"> <button type="submit" class="px-5 btn btn-info">Submit</button> </div> </form> Django Dynamic Fomrset Options: var count = 1; $('.nested-query-formset').formset({ addText: 'Add Another Sub - Objective', deleteText: 'remove', prefix: '{{ subobjective.prefix }}', added: function($row) { count++; console.log(count) }, removed: function($row) { count++; console.log(count) }, }); Any help here is really appreciated. -
How to handle document request in django?
I have three models, Application, Students and University in this, application is connected with both student and university (Students can apply for an university and university can manage these applications). Now i have an scenario in which university will be "Requesting for documents" - by which students will upload documents later. Am just confused how to handle this. How it happens - On application details page there is a button named "Request Document", when university clicks on this - a popup with available documents will be showed, in this they can multiselect the document and submit. And in students side there will be a space where they need to upload all the required documents So now, from the above i have few problems: How to store these on database, as required documents can be varied (can these be stored in a single row with arrays or should i store each row for each documents ? How to show this on students page ? How to validate if the required documents are uploaded ? Please suggest something to do this efficiently ! -
Why bootstrap carousel and django not workig properly?
I am trying to provide bootstrap carousel backend with django.I have written a simple program view which will pass all images to template.But when i run the program i did't get output as expected, all images are rendered adjecent to one other. There was nothing like forward and backward button and all.And i am posting my view and template. Thanks in advance. Hope to here from you soon. View:- def TaggingView(request): queryset = MyImage.objects.filter(is_tagged=False) return render(request, "taggging.html", {'files': queryset}) Template:- <body> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for file in files %} <div class="carousel-item active"> <img class="d-block w-100" src="{{file.image.url}}" alt="slides"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </body> -
Static files are not loading | Django
Static files are not loading and also does not shows any error. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR,"static") STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') 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('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Console Console Dirs Structure Project Directory Structure CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading but media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. In dir structure image we can see img and css folder at same place in static folder. -
Why is the Django API returning an empty array
I am developing a web application using Django but I am not getting the desired results, the Django API is return an empty array ([]). This is the serializer class I am trying to get the places data -> from rest_framework import serializers from . import models class PlaceSerializer(serializers.ModelSerializer): class Meta: model = models.Place fields = ('id', 'name', 'image') These are the views -> from rest_framework import generics from .import models, serializers # Create your views here. class PlaceList(generics.ListCreateAPIView): serializer_class = serializers.PlaceSerializer def get_queryset(self): return models.Place.objects.filter(owner_id=self.request.user.id) # Only the owner can create or make changes on the places def perform_create(self, serializer): serializer.save(owner=self.request.user) -
Store who updated Django Model from admin
I have a use case where data is only inserted and updated from django admin. Now, I have multiple users who have access to django admin page. I want to be able to store who exactly updated or created a record in django admin page. Ideally, I want to add a separate column to an existing model. models.py class Links(models.Model): link = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) created_by = model.ForeignKey(UserModel) updated_at = models.DateTimeField(auto_now=True) updated_by = model.ForeignKey(UserModel)