Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filtering Post Form option by currently logged-in User's Vehicle
I'm a django newbie and i'm making a form where a User can make a Post and pick one of his Vehicles for the Post. The Vehicle and the Post models are created like so: *blog/models.py* class Post(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('post-detail', kwargs ={'pk': self.pk} ) *vehicles/models.py* class Vehicle(models.Model)*: TESLA = 'TESLA' MAZDA = 'MAZDA' VOLVO = 'VOLVO' VEHICLE_CHOICES = ( (TESLA, "Tesla"), (MAZDA, "Mazda"), (VOLVO, "Volvo"), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) model = models.CharField(max_length=9, choices=VEHICLE_CHOICES, default=TESLA) def __str__(self): return self.model My blog views: *blog/views.py* class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = [ 'vehicle'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I would like to filter the vehicles so that only the current logged in User's vehicles show up in the form, i've tried a variety of different solutions but I seem to be going around in circles, if you could help me out that would be awesome. Thanks! -
How to update a single field in django?
How do I update a single field in django using html template? I have an html page to add records. I need to make an html page only to update a single field of the model. How do I do that. And what should be the view function for it. -
Change saved filepath in a django celery task
I have a model named Flights class Flights(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=timezone.now()) nir = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) red = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) rededge = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) green = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) User uploads some files and through a celery task i get those files and edit them into new ones. After that though they are saved at src folder when i want to save them at src/media/flights/username How do i do that ? Should i change the Flights model and add a filepath or something? And how so? celery task : @shared_task(bind=True) def get_Flights_Data(self,flight_id): identifier = Flights.objects.get(pk=flight_id) redF = identifier.red nirF = identifier.nir rededgeF = identifier.rededge print('Analyzing Flight') red = Image.open(redF) nir = Image.open(nirF) rededge = Image.open(rededgeF) ............... -
Django unable to load svg file in external js file using static reference
I need to load a svg file from my javascript code which I am including in my index.html. I understanding that jinja template cannot be used inside a js external file. And so as a workaround I am storing the same in my whiteLogo and logo variable which I am using in the js code. But when I am running the server and on scrolling on the page I am getting error, that the resource cannot be found. Not Found: /[object HTMLImageElement] [04/May/2022 12:18:05] "GET /[object%20HTMLImageElement] HTTP/1.1" 404 2441 Where am I going wrong, am I loading the logo path correctly? index.html <script type="text/javascript"> var whiteLogo = "{% static "app/images/logo/white-logo.svg" %}"; var logo = "{% static "app/images/logo/logo.svg" %}"; </script> <script src="{% static 'app/js/main.js' %}">></script> main.js window.onscroll = function () { var header_navbar = document.querySelector(".navbar-area"); var sticky = header_navbar.offsetTop; var logo = document.querySelector('.navbar-brand img') if (window.pageYOffset > sticky) { header_navbar.classList.add("sticky"); logo.src = logo; } else { header_navbar.classList.remove("sticky"); logo.src = whiteLogo; } // show or hide the back-top-top button var backToTo = document.querySelector(".scroll-top"); if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) { backToTo.style.display = "flex"; } else { backToTo.style.display = "none"; } }; -
Google Authenticaon in Django and React
Using django-allauth I've enabled google authentication on backend. I can sign in to my Django project and everything. Now, I want to connect that authentication with my React frontend, so I can login/register using google on http://127.0.0.1:3000. What do I need to do? -
Range slider value used in django for advanced search
I have a question. I am attempting to make a multi-value search bar but am having errors having it complete the search. Aim: To be able to search using integer values for people, data, Calls, Messages, and text input. The error being received: MultiValueDictKeyError at /find 'people' Request Method: POST Request URL: http://127.0.0.1:8000/find Django Version: 4.0.3 Exception Type: MultiValueDictKeyError Exception Value: 'people' Exception Location: C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Python Executable: C:\Python310\python.exe Python Version: 3.10.4 ''' Python Path: ['C:\Users\TOSHIBA\Documents\django_projects\Daniskapp\Daniskapp', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Wed, 04 May 2022 11:46:59 +0000 ''' Views.py file: def find(request): if request.method=="POST": searched = request.POST['searched'] people = request.POST['people'] SearchData = request.POST['Data'] SearchCalls = request.POST['calls'] SearchMessages = request.POST['demo'] results = informationBase.objects.filter(title__contains=searched,People=people,Data__lte=SearchData,Calls__lte=SearchCalls,Messages__lte=SearchMessages) return render(request,'finder.html', {'results': results}) ''' ''' Model : ''' ''' class informationBase(models.Model): title = models.CharField(max_length=200) People = models.IntegerField() Data = models.IntegerField() Calls = models.IntegerField() Messages = models.IntegerField() body = models.CharField(max_length=100000000) created_at = models.DateTimeField(default =datetime.now(), blank= True) -
Javascript: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type
i am trying to connet my style.css in django template using the static files {% static 'assets/css/style.css' %} but i keep seeing this error Refused to apply style from 'http://127.0.0.1:8000/assets/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.. NOTE: when i copy my css and manually paste it in a style tag inside the section everything works fine, but my css have over 23,000 lines of code and it's too much to be sitting in the head section of my project. Please how do i go about fixing this error. index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Favicon --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;700&family=Roboto:wght@400;500;700&display=swap"> <!-- Plugins CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/font-awesome/css/all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/tiny-slider/tiny-slider.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/glightbox/css/glightbox.css' %}"> <!-- Theme CSS --> <link id="style-switch" rel="stylesheet" type="text/css" href="{% static '/assets/css/style.css' %}"> </head> tree ├───base │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───course │ ├───migrations │ │ └───__pycache__ │ ├───templatetags │ │ └───__pycache__ │ … -
Django: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type
i am trying to connet my style.css in django template using the static files {% static 'assets/css/style.css' %} but i keep seeing this error Refused to apply style from 'http://127.0.0.1:8000/assets/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.. NOTE: when i copy my css and manually paste it in a style tag inside the section everything works fine, but my css have over 23,000 lines of code and it's too much to be sitting in the head section of my project. Please how do i go about fixing this error. index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Favicon --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;700&family=Roboto:wght@400;500;700&display=swap"> <!-- Plugins CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/font-awesome/css/all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/tiny-slider/tiny-slider.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/glightbox/css/glightbox.css' %}"> <!-- Theme CSS --> <link id="style-switch" rel="stylesheet" type="text/css" href="{% static '/assets/css/style.css' %}"> </head> tree ├───base │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───course │ ├───migrations │ │ └───__pycache__ │ ├───templatetags │ │ └───__pycache__ │ … -
Django filter is not working even after search filter is applied in the url path and also in drf UI
This is my code: models.py class StoreLists(models.Model): id = models.AutoField(primary_key=True) store_name_ = models.CharField(max_length=300,unique=True) brand = models.CharField(max_length=300) class Meta: managed = False db_table = 'stores' serializers.py class StoreListSerializer(serializers.ModelSerializer): class Meta: model = StoreLists fields = "__all__" views.py class StoreListView(generics.GenericAPIView): # even tried with viewsets and ListModelView serializer_class = StoreListSerializer queryset = StoreLists.objects.all() filter_backends = (DjangoFilterBackend,) filterset_fields = ("store_name", "brand") def get(self, request): sales = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) urls.py GET - http://127.0.0.1:8000/api/v1/store_list - getting all data GET - http://127.0.0.1:8000/api/v1/store_list?brand=samplebrand - getting all data (filter is not working, same with search filter) Even added django_filters in application and also tried in postman and drf UI but not able to filter.` -
python manage.py runserver answer Python
PS C:\Users\user\PycharmProjects\mysite\mysite> python manage.py runserver Python PS C:\Users\user\PycharmProjects\mysite\mysite> When I write a request "python manage.py runserver", I get "Python". Terminal Pycharm, Windows 10, Python 3.10, Django 4.0.3 Please, tell me, how to fix this? -
How to automatically translate to another language if msgid and msgstr of a word is not provided in .mo or .po file in django?
I'm using i18n for translating english to hindi language settings.py if LANG_ENABLE: LANGUAGES = [ ('en', 'English'), ('hi', 'Hindi'), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True urls.py urlpatterns += i18n_patterns( # Include urls for mamber path('members/', include('member.urls')), # Include urls for about us path('about-us/', include('about_us.urls')), ) i have run ```django-admin makemessage -l hi``` a folder locale/hi/LC_MESSAGES with ```django.mo``` and ```django.po``` has been created 1. there are few words which i have added in .po file under ```msgid``` and ```msgstr``` for translation 2. there are few words which {% trans %} convert to hindi by itself. (there translation are not added in ```.mo``` ```.po``` file 3. and other words are not getting translated( which i have not added in ```.mo``` ```.po``` file can i do something like if no translation provided in .mo and .po then it should automatically convert to other language(hindi language). It is working few few words but not for whole page. How can i achieve this. -
Changing front-end image based on back-end variable change without reloading page in django
I'm using Django framework to monitor garbage fill ratio. I' m getting the data via IOT device with Raspberry Pi. So when the sensor data change, I want to change the image on front-end without page reload. So I want to see real time data on front-end. I searched about Django channels but I can not figure it out how to change image. <body> <h1 class="title">Garbage Monitoring System</h1> <div class="trash-bin"> {% if binCapacity == 0 %} <img src="static/images/0.png" alt="zeroGarbage" /> <p>Fill Ratio: 0%</p> {% elif binCapacity == 25 %} <img src="static/images/25.png" alt="%25 Garbage" /> <p>Fill Ratio: 25%</p> {% elif binCapacity == 50 %} <img src="static/images/50.png" alt="%50 Garbage" /> <p>Fill Ratio: 50%</p> {% elif binCapacity == 75 %} <img src="static/images/75.png" alt="%75 Garbage" /> <p>Fill Ratio: 75%</p> {% elif binCapacity == 100 %} <img src="static/images/100.png" alt="%100 Garbage" /> <p>Fill Ratio: 100%</p> {% endif %} </div> </body> -
Is it possible to override a wagtail.hooks.register function with a custom function?
Is it possible to override a wagtail @hooks.register function with a custom function or to de-register a function all together? One example of what I would like to achieve is editing the register_styleguide_menu_item function in in wagtail/contrib/styleguide/wagtail_hooks.py so that the style guide is only shown to superusers. For example; I would like to override the current function: @hooks.register("register_settings_menu_item") def register_styleguide_menu_item(): return MenuItem( _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000 ) with this: @hooks.register("register_settings_menu_item") def register_styleguide_menu_item(): return AdminOnlyMenuItem( _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000 ) (note the change from MenuItem to AdminOnlyMenuItem on the third line) The docs for wagtail hooks are available at https://docs.wagtail.org/en/stable/reference/hooks.html but it doesn't cover this scenario. Is there a mechanism to achieve this? -
In views.py file ==> category_posts = Post.object.filter(category=cat) returns an empty query set. The 'Post' model has sample posts with categories
I am creating a blog application in django where i encountered this unusual issue. I am not being able to filter and display blog posts category wise. Please find my code below. Thanks in advance. I have spent two full days trying to figure this out and still got nothing. MODELS.py This is the model which i have created for a blog post. class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): #return reverse('article-detail', args=(str(self.id))) return reverse('homepage') VIEWS.py This is the view that i have created for a category wise blog posts. def CategoryView(request,cat): category_posts = Post.objects.filter(category=cat) return render(request,'categories.html',{'category_posts':category_posts}) URLS.py The urls.py file. path('category/<str:cat>/', CategoryView, name = 'category'), CATEGORIES.html This will be the final display page where the category_posts is displayed as an empty queryset. The for loop is unable to run because category_posts is an empty queryset. Single word categories are also empty(to rule out a slugify issue) {% extends 'base.html' %} {% load static %} {% block content %} <ul> {% for post in category_posts %} <li> <div class="category"> <a href="{% url 'category' post.category|slugify %}">{{ post.category … -
How to prevent a logged in user from posting a post using anothers user name in django rest framework
In my Django rest framework project I want to make sure that for example if testuser1 is logged in when posting a post cannot on the author part chose testuser2 and post the post with the author being testuser2. How I can I make sure only the logged in user creates a post? my models.py from turtle import title from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title my views.py from django.shortcuts import render from rest_framework import generics, permissions from .models import Post from .serializers import PostSerializer from .permissions import IsAuthorOrReadOnly class PostList(generics.ListCreateAPIView): #permission_classes = (permissions.IsAuthenticated,) queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer my serializers.py from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'author', 'title', 'body', 'created_at',) model = Post my permissions.py from re import T from tkinter.tix import Tree from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Read-only permissions are allowed for any request if request.method in permissions.SAFE_METHODS: return True # Write permissions … -
Advise on orm modelling in django
I am building a webapp in which users place orders with nested information. I am after some advice on best practice so I can do some more research. The idea is that a user either loads an existing order, or creates a new order. They then fill in the subsequent order fields, which can be on a one to many basis. My initial thought was to use a variable for order_id and use a foreign key to link the instances of the other classes. However, this seems overcomplicated. order_id would have to be unique and sequential. Is this the best approach to this issue? class Order(models.Model): order_id= xxxx created_by = xxxx class A(models.Model): order_id = models.ForeignKey(xxxxx) someclassafield = xxxx class B(models.Model): order_id = models.ForeignKey(xxxxx) someclassbfield = xxxx This would give the user the ability to create orders such as below: Order 1 (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_B, order_id, someclassbfield) Order 2 (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_B, order_id, someclassbfield) (Class_B, order_id, someclassbfield) -
Multilanguage's Sitemap, get_absolute_url and location
Plz help me with the correct Sitemap generation. My multilanguage site on Django 2.2 with standard internationalization framework. Model.py with get_absolute_url class Data(models.Model): ... def get_absolute_url(self): from django.urls import reverse return reverse("data_detail", kwargs={"slug": str(self.id)}) Sitemap.py class DataSitemap (Sitemap): changefreq = "daily" priority = 0.5 i18n = True def items(self): return Data.objects.all() def location(self, obj): return '/news/data/%s/' % (obj.pk) url.py from django.contrib.sitemaps.views import sitemap from .sitemaps import DataSitemap sitemaps = { 'data' : DataSitemap } urlpatterns = i18n_patterns( path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name='django.contrib.sitemaps.views'), ) Now when I generate sitemap.xml I get no language prefix, <url> <loc>example.com/news/data/1/</loc> <lastmod>2022-03-24</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>example.com/news/data/1/</loc> <lastmod>2022-01-08</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> </url> For the other Model without with get_absolute_url but without harcoded location - everything works fine, language prefix added correctly. How can I fix my Sitemap code? -
'QuerySet' object has no attribute '_meta', Django with ajax
I am building a site for a tattoo shop. In my index view I first display all tattoos by every artist but I am trying to allow users to filter tattoos by artist and then update the page displaying tattoos by the selected artist using jquery/ajax. Artist and Tattoo models: class Artist(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # etc class Tattoo(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=150) image = models.ImageField(upload_to='images/') date_created = models.DateTimeField(auto_now_add=True) forms.py: class FilterArtForm(ModelForm): class Meta: model = Tattoo fields = ['artist'] widgets = { 'artist': forms.Select(attrs={'id': 'filter_by_artist'}), } views.py: def index(request): tattoos = Tattoo.objects.order_by('-date_created') filter_art_form = FilterArtForm() artist_id = request.GET.get('artist') if artist_id: artist = Artist.objects.get(pk = artist_id) tattoos = tattoos.filter(artist=artist) # trying to return this as a JsonResponse is causing some kind of issue return JsonResponse({'tattoos': model_to_dict(tattoos)}, status=200) return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form}) I am new to working with ajax so I was just messing around with my view and if I try to return only the Artist object as such: def index(request): tattoos = Tattoo.objects.order_by('-date_created') filter_art_form = FilterArtForm() artist_id = request.GET.get('artist') if artist_id: artist = Artist.objects.get(pk = artist_id) return JsonResponse({'artist': model_to_dict(artist)}, status=200) return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form}) this will work and I … -
Djanog login not persisting
Login and Log out is only working for admin panel , not for user panel , after loging in from user end , its not getting reflected in the home screen . The default login(request,user) is not setting user to request.user . Thats why after loging in when redirecting to home page there request.user in home page request.user is showing anonymous user instead of loged in user . How to solve this ? I am using custom user model . If it could be solved by Application Backend , then Show How . models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractBaseUser , PermissionsMixin from .UserManager import UserManager from datetime import datetime class User(AbstractBaseUser,PermissionsMixin): username = None FullName = models.CharField(max_length=50) Email = models.EmailField(unique=True) Uid = models.CharField(max_length=6,default="TD") SignUpTime = models.CharField(default=((datetime.today()).strftime("%H:%M >> %a %d-%b-%Y")),max_length=25) is_staff = models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) is_active=models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ["FullName"] UserManager.py from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.hashers import check_password class UserManager(BaseUserManager): use_in_migrations = True def create_user(self,Email,password,**extra_fields): if not Email: raise ValueError("Email is Required") email = self.normalize_email(Email) user = self.model(Email=email,**extra_fields) user.set_password(password) user.save() user = self.model.objects.get(Email=email) return user def create_superuser(self,Email,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') != True: raise ValueError("not a staff") … -
Python Django, API Call with user input
I’m currently building a little Django Project and I’ve got a question. I would like to make an API Call to an external API with a user input. How can I achieve that? Pretty new to Django sorry. Regards, -
Connecting a Neo4j graph database to a Django REST API app
I am trying to connect a remote Neo4j database to a Django app with a REST API. I am trying to specify the database in the settings.py file using the following code: DATABASES = { 'default': { 'NAME': 'papers.db', 'ENGINE': 'django.db.backends.sqlite3', 'USER': '', 'PASSWORD': '', 'PORT': '', }, } I would like to know: What python libraries need to be installed in order to do this? What is the 'ENGINE' that needs to be specified in the code above? The Neo4j database has a URI, but does not provide us with an IP address - am I able to use this URI? I am confident that I know what the other parameters need to be. Thanks in advance -
pip install django-jalali-date problm
Import "jalalienter image description here_date" could not be resolved After installation, I will make a mistake. Thank you for your help -
Can i use Django Admin for the user interface when there will only be 2-3 users?
i am working on a project where i am creating a project management webapp for a small team (4-5 users). They will use it mainly for data management (CRUD operations for projects, resources, work hours, budgets etc.) and creating reports. For the CRUD part of the application i want to use Django Admin. Only 2-3 users will apply CRUD operations on the data. So i want to call them "administrators" and use the built-in Admin app because it literally has all the functionalities i need. It will save a lot of time and costs which is very important for this project I read that Admin is only meant for site administrators and this is not recommended. My question is: With this use case for the application can i use a Django admin app as a part of the User interface? Thanks in advance -
convert ManyToManyField to ForeignKey in Django
I have 3 models: class Series(models.Model): . . . series_name = models.CharField(max_length=50, unique=True) class Lists(models.Model): . . name = models.CharField(max_length=50, unique=True) class Article(models.Model): . . . lists = models.ForeignKey(Lists, blank=True, null=True, related_name='article_has', on_delete=models.CASCADE, default=None) series = models.ManyToManyField(Series, related_name='series', blank=True) is_published = models.BooleanField(default=False) Initially I created some Articles without 'lists' field. Now i want to add the 'Lists' field to the Article model but I am running into errors after makemigrations and migrate. I did the following: python manage.py makemigrations blog python manage.py migrate python manage.py makemigrations --empty blog modified the new empty generated migration file as follows: # Generated by Django 4.0.3 on 2022-05-03 13:54 from django.db import migrations def migrate_m2m_to_fk(apps, schema_editor): Article = apps.get_model("blog", "Article") for article in Article.objects.all(): article.lists = None article.lists.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.RunPython(migrate_m2m_to_fk) ] python manage.py migrate and at the step 5 I get the following error due to Article.objects.all() : MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'blog_article.lists_id' in 'field list'") -
Django collectstatic to look for assets directory in every app in django project
Currently I have 6-7 apps present inside my Django project. In settings.py for STATICFILES_DIRS I need to specify assets directory full path present inside all my apps which is cumbersome in case when I increase my apps everytime I need to add the path here. Isn't there one setting with which I can specify just the assets folders and the collectstatic command will look for static files inside assets in all my apps? This is what I currently have: STATICFILES_DIRS = [ BASE_DIR / "app1/templates/assets", BASE_DIR / "app2/templates/assets", BASE_DIR / "app3/templates/assets", BASE_DIR / "app4/templates/assets", BASE_DIR / "app5/templates/assets", BASE_DIR / "app6/templates/assets", ] What I needed was something like this and the collectstatic would have gone to all my apps(1-6) looking for the assets directory. STATICFILES_DIRS = [ 'templates/assets', ] Is there any way to do the same?