Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to define a location/latlon field in a django model
I have a model "Store" which somehow needs to store the address, latitude, and longitude of the "Store" instance so I can show the exact location on the map later. I tried to store lat long as CharField in separate fields but is there any better solution for this purpose? maybe PoinField or DecimalField? lat = models.CharField(max_length=50) lon = models.CharField(max_length=50) -
django: object has no attribute 'cleaned_data'
I'm trying to make a registration page for my project. Standart model User is not enought for me, so I created another model named Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='М', verbose_name='Пол') third_name = models.CharField(max_length=30, verbose_name='Отчество') grade = models.CharField(max_length=2, choices=GRADE_CHOICES, default='1', verbose_name='Класс обучения') age = models.PositiveSmallIntegerField(default=7, verbose_name='Возраст', validators=[ MaxValueValidator(100), MinValueValidator(4) ] ) school = models.ForeignKey(School, on_delete=models.PROTECT, verbose_name='Учебное заведение', blank=True, null=True, default=None) interest = models.ManyToManyField(OlympiadSubject, verbose_name='Интересующие предметы') On both, User and Profile I created a ModelForm: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('third_name', 'sex', 'grade', 'age', 'school', 'interest') And wrote a view for registration: def create_profile(request): if request.method == 'POST': user_form = UserForm() profile_form = ProfileForm() if user_form.is_valid() and profile_form.is_valid(): User.objects.create(**user_form.cleaned_data) Profile.objects.create(**profile_form.cleaned_data, user=User) return redirect('/login') else: profile_form.add_error('__all__', 'Данные введены неверно!') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'users/profile_create.html', { 'user_form': user_form, 'profile_form': profile_form }) and of'course i have a template for that: {% extends 'main/layout.html' %} {% block title %} Some text {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <button type="submit">Сохранить изменения</button> </form> {% endblock %} but … -
django.db.utils.ProgrammingError: column app_poll.approve_id does not exist LINE 1:
I have two two models, 'Poll' and 'Approve'. The 'Approve' model is created later and appears much later in the migrations and i want to reference it as Foreign key in the Poll model. If i delete all tables from the database and run migrations, i get an error that says column 'approve_id' does not exist. class Poll(models.Model, ContentTypeMixin): date = models.DateTimeField(auto_now_add=True, verbose_name='Date') comment = models.TextField(blank=True, verbose_name=_('Comment')) approve = models.ForeignKey('Approve', on_delete=models.CASCADE, null=True, blank= True, verbose_name=_('Final Approval By')) class Approve(models.Model, ContentTypeMixin): name = models.TextField(blank=True, verbose_name=_('Name')) -
django-elasticsearch-dsl: how to add script to filter?
I have a 'MovieDoc' document and inside it a ListField called 'actors' that contains a list of ObjectFields with properties such as 'last_name', 'first_name', 'country,' etc. When running a query with Django ElasticSearch DSL, I would like to filter movies by the number of actors they feature (i.e. by the length of the values in the 'actors' ListField). As far as I understand, this should be done using script-filtering (https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html). However, I do not understand how I can apply the ElasticSearch script filtering with django-elasticsearch-dsl. I have tried something like this in different combinations but to no avail: search_query = 'battle' results = MovieDoc.search().query(search_query).filter(script={"script": ["doc['actors'].values.size() > 1"]}) -
Get address from Google maps without API
For educational purposes my teacher has given me a task to figure out how to get chosen address from Google map without API. As i see the one way to use maps without api is 'Share' on google maps site > 'iframe' tag in html. I can easily put different addresses from db to render different locations. But i need to let user to choose location and save this location in db. I have tried to get 'div' with place address but got a "Blocked a frame with origin 'my.site' from accessing a cross-origin frame." Interesting that i can find this div if i inspect iframe element using ctrl+shift+c AND after that can find it via js in console, but because of cross-origin problem i cant do it in my code. I have thought about getting requests but in 'network' tab in DevTools, i don`t see any looks like address info. All the information i found is about using google api key, but the challenge is to do this without it. Maybe someone will have any ideas? If it matters, i use Django for web-application. -
Django: Avoid rendering as variable in template
I just started learning django for a few day. Django's templating system looks fascinating. but currently I am facing an issue. I need to print this kind of text in my webpage multiple times through template. She {{ was }} a very {{ helpful }} and {{ attractive}} girl. But whenever I try to use this in template, it thinks those words are variable thaI am referring, and vanishes them from the output due to not getting a value. So the output becomes, She a very and girl. I completely understand that this is the intended behaviour, but in some case I am trying to tell the rendering engine to render that as it is. Is there any filter or workaround?? [ I have to use them inside the template, and they can't be passed through variables as string] -
Django: access to attributes of custom model field from html template
I implemented a custom model field: class CustomCharField(models.CharField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.my_attr = "MY_ATTR" Now I want to be able to display that additional attribute when I'm iterating over all model's fields in change_form_template: {% block field_sets %} {% for fieldset in adminform %} {% for line in fieldset %} {% for field in line %} {{ field.field }} {% if field.field.my_attr %} {{ field.field.my_attr }} {% endif %} {% endfor %} {% endfor %} {% endfor %} {% endblock %} Unfortunately my_attr is not visible. I was searching the proper method in the django docs but without any success. I was also trying to use the custom form_class (inheriting the django.forms.fields.CharField) -
why do static files don't work in Django?
here is my settings STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] i did this command python manage.py collectstatic it shows 0 static files copied to 'C:\Users\ALOSTATH\Desktop\Xv\Assets-Tracking-Testing-main\staticfiles', 169 unmodified. when i run it locally, this error is displayed django.core.exceptions.SuspiciousFileOperation: The joined path (S:\cdnjs.cloudflare.com\ajax\libs\jquery-easing\1.4.1\jquery.easing.min.js) is located outside of the base path component (C:\Users\ALOSTATH\Desktop\Xv\Assets-Tracking-Testing-main\static) [22/Apr/2021 19:24:38] "GET /static/https%3A/cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js HTTP/1.1" 500 59 any idea? NOTE: i have two folders, static and staticfiles in the project -
404s in production only
First-time django deployer here. My endpoints work in local dev, but in production some of them are responding with a 404. The troublesome seem to be the allauth ones in particular. e.x: accounts/login/ accounts/signup/ accounts/confirm-email/ ... I've confirmed that these endpoints exist in production by hopping into the shell and checking django.urls.get_resolver. I'm using cookiecutter-django so I also confirmed that ACCOUNT_ALLOW_REGISTRATION is set to True. Anything else I should check? -
Join Foreign Key Table Django QuerySet
Hi im learning Django Queryset,but i get confused when i want to use queryset django to join table,instead of using django raw query i want to learn django queryset In my case i want to fetch RiskIdentification data class Activity(models.Model): act_name = models.CharField(max_length = 40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class ActivityDetail(models.Model): act_risk_assessment = models.ForeignKey(RiskAssessment, on_delete=models.CASCADE) act = models.ForeignKey(Activity, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class RiskAssessment(models.Model): name = models.CharField(max_length = 30) date = models.DateField() email_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class RiskIdentification (models.Model): idn_description = models.CharField(max_length = 30) idn_risk_assessment = models.ForeignKey(RiskAssessment, on_delete=models.CASCADE) risk_type = models.ForeignKey(RiskType, on_delete=models.CASCADE) class RiskMitigation (models.Model): mtg_description = models.CharField(max_length = 30) identification_risk = models.ForeignKey(RiskIdentification, on_delete=models.CASCADE) it will look like this in raw query SELECT idn_descriptiom FROM RiskAsessment RA JOIN RiskIdentification RI on RA.id = RI.idn_riskAsessment JOIN ActivityDetail AD JOIN AD.act_risk_assessment = RA.id JOIN Activity A on A.id = AD.act Please help me how django query will looks like,and describe it -
Django messages does not appear. Only appears when I trigger the js function that checks for empty values then submit. If I just submit it wont show
Basically, When the field is invalid, django messages is supposed to print "Invalid test, please try again!" However, its weird because the error message only shows and works when I do the following steps: 1)enter sth into the field 2)backspace and remove everything i have entered 3)the element will show to prompt me to enter a key 4)I press submit button once (it wont submit) 5) I key sth inside (a random invalid key) 6) I press submit If I were to directly enter a random invalid key then press submit, the page will just refresh and django messages wont show. the command prompt will print print('Test Failed!') though, due to the code. Any idea which part of my code messed up? I suspect it might be that I accidentally cause the page to refresh, and hence the django error message doesn't show. Do help! thank you! <form> <div> <input required class="form-control" type="text" id='test' onkeyup="empty_value_check(this)" oninvalid="this.setCustomValidity(' ')"/> <small class="hide" id="test_one"></small> </div> <button class="btn btn-primary btn-lg" onclick='func()' id='button_link'>Submit</button> </form> <script type="text/javascript"> function func(a=false){ // if(!a){ empty_value_check() apiValidate(); } function empty_value_check(ele){ value = document.getElementById('test').value if (value ==''){ $('#test_one').html('Please enter something').removeClass('hide'); $('#test').addClass('is-invalid') } else { $('#test').removeClass('is-invalid'); $('#test_one').addClass('hide'); } } function apiValidate(key='test'){ const request … -
Django Deployment - scriptProcessor could not be found in fastCGI application configuration
I am learning the process to deploy Django Project through IIS and fastCGI. However, I am facing an error <handler> scriptProcessor could not be found in <fastCGI> application configuration. After a little bit of research I've found that this error could be due to rights issue. Hence I've added permission (read, write, execute) for user DefaultAppPool in folder Python37 (contains python virtual environment) and similarly I've done this for folder wwwroot which is on C:\inetpub. Python Virtual Environment: C:\python37 Web.config file path: C:\inetpub\wwwroot\web.config Web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python37\scripts\python.exe|c:\python37\lib\site-packages\wfastcgi.py>" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="c:\python37\scripts\python.exe" /> <add key="WSGI_HANDLER" value="manhour_site.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="manhour_site.settings" /> </appSettings> </configuration> After making changes above I am still facing the similar issue hence I looked at this solution. As per the solution fastCGI settings must be in the applicationHost.config file. This file is located on path C:\Windows\System32\inetsrv\config\applicationHost.config After following this solution I've made following changes applicationHost.config Under <system.webServer> I've added following <fastCgi> <application fullPath="c:\python37\scripts\python.exe" arguments="c:\python37\lib\site-packages\wfastcgi.py" maxInstances="4" signalBeforeTerminateSeconds="30"> <environmentVariables> <environmentVariable name="DJANGO_SETTINGS_MODULE" value="manhour_site.settings" /> <environmentVariable name="PYTHONPATH" value="c:\python37\scripts\python.exe" /> <environmentVariable name="WSGI_HANDLER" value="manhour_site.wsgi.application" /> </environmentVariables> </application> </fastCgi> I've ran the command as administrator wfastcgi-enable. I need a solution … -
Django renders a template that does not exist in specified directory
I have model 'Video' and I have a list view for this model, then in another app I'm trying to create a view 'UserVideosListView' that is viewable to the dedicated user. when I open the page in the browser before making any templates for this view I'm able to see current user's videos (not all videos). # inside 'users' app class UserVideosListView(ListView): model = Video template_name = "users/user_videos.html" context_object_name = 'videos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['videos'] = Video.objects.filter(author=self.request.user) return context # inside 'videos' app class VideoListView(ListView): model = Video paginate_by = 25 template_name = 'videos/video_list.html' context_object_name = 'videos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['videos'] = Video.published_videos.all() return context P.S. I'm sure that the URL I'm entering is current, and there is no template inside the 'users' directory -
Type Error: cannot read property length of undefined for empty_value_check
These are the javascript functions for my html form, to validate for empty values in "input" elements and "select" elements respectively. The empty_select_check function doesn't work and I'm not sure why, but the empty_value check works for the individual fields. However, it does not work in the empty_value_all() fucntion. Note that the empty_value_all() is called when the user clicks submit. I get the following error: Type Error: cannot read property length of undefined for empty_value_check. Any idea why it works for individual fields but not for when i try to submit? Let me know if you require my html code but basically its just input elements with an onkeyup="" where I call the js functions. function submitform(){ empty_value_all() $('#Start').click() } } function empty_value_check(ele) { let value = ele.value; console.log(value) if (value === '' || value.length === 0) { if ($(ele).closest('div').find('small').length != 0) $(ele).closest('div').find('small').removeClass('hide').removeClass('d-none'); else $(ele).closest('div').nextAll('small').removeClass('hide').removeClass('d-none'); $(ele).addClass('is-invalid'); } else { $(ele).nextAll('small').addClass('hide'); $(ele).removeClass('is-invalid'); } } function empty_select_check(ele) { if (ele.value === "Select Folder" || ele.value === undefined) { $(ele).addClass('invalid-feedback'); return false } else { $(ele).removeClass('is-invalid'); } } $(function() { $('#field_5,#field_6,#field_7').on('change', empty_select_check(this)) }) function empty_value_all() { $('#field_1,#field_2,#field_3',#field_4).each(empty_value_check(this)); $('#field_5,#field_6,#field_7').each(empty_select_check(this)); return false; } -
How to send a video to Flutter client from Django backend
I am a beginner in mobile development and I am creating a mobile app using Flutter on the client side and Django as backend. I am basically sending some images from the client to the server and processing them on the server side. I now want to send a video back to the client and play it in the Flutter app. I am currently trying to do this using an HTTP FileResponse in Django, and in Flutter I am writing the received response data as bytes in a file and displaying it with a VideoPlayer object. I think I may not be using the right encoder/decoder for this as the video won't playback (even when I try accessing the file directly from my phone). Also I am not sure this is the right approach to get my video playing in the client app, since I don't necessarily want to download the video on the client side (and store it as a file) but just display it on the screen, but I don't know in what other way I could achieve what I'm looking for. I have looked up how to stream a video but I haven't found any useful answers … -
Django form getting GET request instead POST request
Previously this code was sending post request. Suddenly after restarting server, it started sending get. If I take some working post code for form from internet and then go on trying and erasing then my code starts sending post request. But again after some time when I put my original code, this will start sending get request instead of post request. user_registration_form.html <form method="post"> {% csrf_token %} {{ form }} </form> <input type="submit" value="Register"> forms.py from django.forms import ModelForm from django import forms from .models import StudentData class StudentRegister(ModelForm): class Meta: model = StudentData fields = "__all__" widgets = {'password': forms.PasswordInput(), 'rpassword': forms.PasswordInput()} def clean(self): cleaned_data = super().clean() password, rpassword = cleaned_data.get('password'), cleaned_data.get('rpassword') if password != rpassword: error_msg = "Both passwords must match" self.add_error('rpassword', error_msg) views.py from django.shortcuts import render from .forms import StudentRegister from django.contrib import messages def login_register(request): return render(request, 'users/login_register.html') def guest_register(request): return render(request, 'users/guest_register.html') def student_data(request): if request.method == 'POST': print('post') form = StudentRegister(request.POST) if form.is_valid(): print('valid form') form.save() messages.success(request, f"You are registered successfully, {form.cleaned_data.get('name')}") return render(request, "<h3>Registration done</h3>") else: print('get') form = StudentRegister() return render(request, 'users/user_registration_form.html', {'form': form}) #models.py from django.db import models from django.core.validators import MaxLengthValidator class StudentData(models.Model): name = models.CharField(max_length=100) room_no = models.CharField(max_length=4) … -
Converting or Connecting Flask app.py code to Django
In our project, we are going to create a NLP web site. The user will going to write a text or upload a document and these api's going to help us to do processing. We made a api system with Flask but we made our web site backend with Django. I want to connect these two projects. Is it possible to connected them or I have to convert all the code we write on the django to flask. Flask app.py file: from flask import Flask, jsonify, request, render_template import requests import json app = Flask(__name__) app.config['JSON_AS_ASCII'] = False @app.route("/",methods=["GET"]) def home(): return render_template("SignPage.html") @app.route("/sentiment", methods=['POST']) def sentiment(): url = "http://localhost:5000/sentiment" payload = {"text": request.form["input_text"]} response = json.loads(requests.request("POST", url, json=payload).text) return jsonify(response) Django url.py file: urlpatterns = [ path('', views.index, name='kaydol'), path('anasayfa/', views.home, name='anasayfa'), path('duyguanalizi/', views.link1, name='duyguanalizi'), path('anahtarkelime/', views.link2, name='anahtarkelime'), path('özetleme/', views.link3, name='özetleme'), path('advarlık/', views.link4, name='advarlık'), path('sorucevap/', views.link5, name='sorucevap'), path('konutanım/', views.link6, name='konutanım'), ] urlpatterns += staticfiles_urlpatterns() Django views.py file: def index(request): if request.method == "POST": if request.POST.get('submit') == 'Kayıt Ol': username= request.POST['username'] email= request.POST['email'] password= request.POST['password'] if User.objects.filter(username=username).exists(): messages.info(request,'Bu kullanıcı adı kullanılıyor') return redirect('/') elif User.objects.filter(email=email).exists(): messages.info(request,'Bu email kullanılıyor.') return redirect('/') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') elif … -
how to set a default value in Django forms?
In the database there is class Borrowing which contains employee_id that will borrow item and tag_id (the item) and subscriber_id in my code, if an employee request a borrowing, he can choose subscriber_id. I need to set the subscriber_id to 1, without even asking the employee to choose. in the models.py file class Borrowing(models.Model): borrowing_id = models.IntegerField(null=True) start_date = models.DateField(auto_now_add=True, null=True) end_date = models.DateField(null=True) employee_id = models.ForeignKey(Employee, null=True, on_delete= models.SET_NULL) tag_id = models.ForeignKey(Tag, null=True, on_delete= models.SET_NULL) subscriber_id = models.ManyToManyField(Subscriber) def __str__(self): return str(self.borrowing_id) in forms.py file class BorrowingForm(ModelForm): class Meta: model = Borrowing fields = ['end_date', 'employee_id', 'tag_id', 'subscriber_id'] in views.py def createBorrowing(request, pk): BorrowingFormSet = inlineformset_factory(Employee, Borrowing, fields=('end_date','tag_id','subscriber_id')) employee = Employee.objects.get(id=pk) formset = BorrowingFormSet(queryset=Borrowing.objects.none(), instance=employee) if request.method == 'POST': formset = BorrowingFormSet(request.POST, instance=employee) if formset.is_valid(): formset.save() return redirect('/login') context = {'formset':formset} return render(request, 'assetstracking/createBorrowing.html', context) -
How do I make a counter in Django that is displayed in the template?
Models.py class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True) Views.py class Index(ListView): model = Coche total_coches = Coche.objects.filter(reserved=False, sold=False) Template <span class="text-primary">{{ total_coches.count }}</span> <span>coches disponibles</span></span> ### It does not show the number of cars my application has. Does anyone know what the fault is? ### -
Why am I getting error 404 in my django project when everything seems correct?
I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this: 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('store.urls', namespace='store')), path('basket/', include('basket.urls', namespace='basket')), store/urls.py: from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.all_products, name='all_products'), path('<slug:slug>/', views.product_detail, name='product_detail'), path('category/<slug:category_slug>/', views.category_list, name='category_list') ] basket/urls.py: from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary'), path('add/', views.basket_add, name='basket_add'), ] I am getting an error: Page not found(404) Request Method:GET Request URL:http://127.0.0.1:8000/basket/ Raised by:store.views.product_detail this is my store/views.py: from django.shortcuts import get_object_or_404, render from .models import * def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) context = { 'product': product, } return render(request, 'store/products/detail.html', context) please help me solve this problem i've been stuck on this for a long time. -
Can any tell me a way that can check whether a child has only two sponsorship and not more
language:- python framework :- django i have 3 model child sponsor sponsorship now I want to restrict sponsor to give sponsorship to particular child to 2. he can sponsor 1 as well as 2 . how can I restrict that -
Trying to perform addition operation on elements from rendered Django template
I've been working on this result management system, but I've been stuck on how to display total marks from the entered result. The results are entered from the Staff Panel and then each student has a view on their own page. The problem is how to add the student's result and also declare perform logic for grade declaration from the Student's panel for each course and display such result. Here is my models.py class Students(models.Model): id=models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_pic = models.FileField() address = models.TextField() department_id = models.ForeignKey(Department, on_delete=models.DO_NOTHING) session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) StudentsView.py def student_view_result(request): student = Students.objects.get(admin=request.user.id) student_result = StudentResult.objects.filter(student_id=student.id) for row in student_result: exam_mark = row.course_exam_marks ca_mark = row.course_ca_marks total_mark = exam_mark + ca_mark context = { "student_result": student_result, 'total_mark':total_mark } return render(request, "student_template/student_view_result.html", context) my templates for rendering the result <div class="card-body"> <div class="table-responsive"> <table class="table"> <thead class="thead-light"> <tr> <th>ID</th> <th>Subject</th> <th>Continuous Assesment Marks</th> <th>Exam Marks</th> <th>Total Mark</th> <th>Grade</th> </tr> </thead> {% for row in student_result %} <tr> <td>{{ row.id }}</td> <td>{{ row.course_id.course_name }}</td> <td>{{ row.course_ca_marks }}</td> <td>{{ row.course_exam_marks }}</td> <td>{{ total_mark }}</td> <td> {% if total_mark >= 70 %} A {% elif total_mark >= 60 … -
All I do py manage.py migrate?
Traceback (most recent call last): File "C:\Users\DELL\Desktop\django\first_project\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\DELL\Desktop\django\first_project\manage.py", line 22, in main() File "C:\Users\DELL\Desktop\django\first_project\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?strong text -
Moving an app from a django project to another
I created a django project(prjct1) and has an app in it(app1) I also created another django project(prjct2) which also has an app(app2) How can I move app2 in prjct1 -
How to set Django Model ManyToManyField as none in django backend administation
The Likes Field Shows names of all Users. How to set it to None class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) youtubeVideo = models.CharField(max_length=200, null=True, blank=True) category = models.ForeignKey(Category,on_delete=models.CASCADE, max_length=200, null=True,blank=True) image = models.ImageField(upload_to='images',null=True,blank=True) likes = models.ManyToManyField(User) def number_of_likes(self): return self.likes.count() class Meta: ordering = ['-created_on'] def __str__(self): return self.title