Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get html from page in Django
I was trying to implement some testing in Django, and I needed to check the data on the web page with a string, but I couldn't retrieve data from the web page. so, how can I get data(html) from web page? my tests.py from rest_framework.test import APITestCase class TicketTestCase(APITestCase): def test_user_details_on_ticket_id(self): response = self.client.get(f"/api/ticket/1") print(response.content) # this returns empty data in bytes # I want to check this #self.assertEquals(response.data "helloworld") -
Cannot Filter ChoiceField in Django with Multiple Keys and One Value
I am trying to filter a choicefield in Django by attempting to display one value with multiple keys. I understand choicefields are normally one key per value, but I have some values (names) which are the same with different id's in my database. I do not want to display the names more than once in the choicefield, so I wrote code to display items of a dictionary as a tuple with several id's and one value. I would like to filter these objects (animals) by "species" and "gender," so I created two modelchoicefields in my form. I am able to filter singular names by "species" and "gender" but not the duplicate names. The only error messages I get are Not Found: /filter_species/(1, 4)/ and "GET /filter_gender/(1,%204)/ HTTP/1.1" 404 4306. The "1" and "4" are respectively id's 1 and 4 for two animals with the same name. I have included my code from my forms, views, URLs, and animals template. Any help would be much appreciated as I am fairly new to Django and am still learning. Note: I am wondering if my URLs may be an issue with not showing regex for the parenthesis (tuple)? If so, I've been researching … -
Django, python3, on install I get: "Parent module 'setuptools' not loaded"
I see lots of errors and suggestions about Parent module '' not loaded, ... I don't see any about specifically "out of the box" django 3.5. $ mkvirtualenv foobar -p /usr/bin/python3 Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/isaac/.virtualenvs/foobar/bin/python3 Also creating executable in /home/isaac/.virtualenvs/foobar/bin/python Installing setuptools, pkg_resources, pip, wheel...done. [foobar] $ pip install django Collecting django Using cached Django-2.2.15-py3-none-any.whl (7.5 MB) Collecting pytz Using cached pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Installing collected packages: pytz, sqlparse, django Successfully installed django-2.2.15 pytz-2020.1 sqlparse-0.3.1 [foobar] $ python Python 3.5.3 (default, Jul 9 2020, 13:00:10) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/home/isaac/.virtualenvs/foobar/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line … -
I am having a problem linking my HTML pages in Python Django web framework could you help me with that?
I am getting an error when I run my django application and I saw that I have a problem in my url configuration and templates linking app/views.py from django.shortcuts import render from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/index.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') def contact(request): return render(request, 'blog/contact1.html') models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) 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) class Meta: ordering = ['-created_on'] def __str__(self): return self.title project/urls.py from django.contrib import admin from django.conf.urls import url, include from blog import views urlpatterns = [ url(r'', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), ] app/urls.py from django.conf.urls import url from blog import views #Template tagging app_name = 'blog' urlpatterns = [ url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'', views.PostList.as_view(), name='index'), url(r'<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] templates/home.html --one of my html files <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta … -
Django collectsatic keeps collecting old files
When I run my localserver I noticed that Django is loading a background image I changed a while ago. I checked the folder where my static files are and my new background image was there. Both images had the same name. I changed the name and did collectstatic again and in my STATIC_ROOT the old image appeared. Later I tried python manage.py collectstatic --clear, I also cleared my cache, restarted my server. I tried deleting the file and changing the name and the path and Django keeps collecting old static. Here's my settings.py import os from .passwords import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = SECRET_KEY DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'contact', 'home', 'crispy_forms', 'mathfilters', 'ckeditor', 'ckeditor_uploader' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'spanish.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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 = 'spanish.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': NAME, 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': '5432' } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
Django static file image into template 404 error
I am trying to load a picture into a a Django 3.1 Template. I followed the documentation on the https://docs.djangoproject.com/en/3.0/howto/static-files/ and looked elsewhere for an answer but was not able to solve the issue. Here is all the code that I think is relevant: from settings.py INSTALLED_APPS = [ 'memberships.apps.MembershipsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] from url.py urlpatterns = [ path('', views.index, name='index'), path('memberships/', include('memberships.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and from the template file: {% load static %} ... <img src="{% static 'static/dribblz/images/multicolored-soccer-ball-on-green-field-47730.png' %}" alt="Football on the pitch"> My files are structured such as: dribblz/ -> dribblz/ --> settings.py --> url.py --> views.py ->static/dribblz/images/image.png ->templates/home.html I don't know what other information I can give that may be useful. Thanks in advance. -
How to solve problem with Django & Mongo on azure appservice
I managed to develop django app with vs code but I couldnt publish it. I think I couldnt set up virtual env properly. But then I made it with normal visual studio and that created me virtual environment which azure accepted well. It was working well but with sqlite. I needed mongoDB. I found instructions for dns and djongo and settings.py, so on terminal: 'python manage.py runserver' (locally, but with atlas mongo) it works well. But now, azure isn´t accepting my app. It says only SQL this and that XXXX are accepted... Could someone help me? Heres all the code: https://github.com/Point-SimoSiren/django-suppliers It is now again with sqlite but setting.py: DATABASES mongo stuff I used are on comments right below that. Only virtual env code is in github repo. -
check variable is numerical django template
Hi I want to check if my variable is numeric in Django template and I tried this code {% if isnumeric(item) %} <h1>{{item}}</h1> {% endif %} but this throws me this error Could not parse the remainder: '(item)' from 'isnumeric(item)' I tried to find a builtin template tag or filter in this page https://docs.djangoproject.com/en/3.1/ref/templates/builtins/ of Django document and I searched for this question in StackOverflow too but I did not found my answer -
wordpress + nginx + django: error too many redirect
I have just included wordpress into a project to replace django for the landing page of the website. Up to that point everything server related is working just fine. I am a bit wary to make modification to nginx configuration because I am far from an expert in the domain. I have tried including wordpress location by disabling what I had before which was from django and it is resulting in ERROR TOO MANY REDIRECT here is the code for /nginx/sites-enabled/conf.d that I have: server { server_name mysite.com www.mysite.com; root /var/www/html; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location ^~ / { alias /home/ubuntu/var/www/html/wordpress; index index.php; if (!-e $request_filename) { rewrite ^ /index.php last; } location ~ /wp-content/uploads/ { expires 30d; } location ~ \.php$ { if (!-f $request_filename) { rewrite ^ /index.php last; } include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { if (!-f $request_filename) { rewrite ^ /index.php last; } expires 30d; } } } server { if ($host = www.mysite.com) { return 301 https://$host$request_uri; listen 80; server_name mysite.com www.mysite.com; return 404; … -
Django HttpResponse returning object instead of stated string
I am using Django and React. I need to send a string from Django to React. I have tried using both HttpResponse and JsonResponse but both seem to be returning a response object that does not include the data. The response object from React looks like this: Response {type: "cors", url: "http://localhost:8000/post/", redirected: false, status: 200, ok: true, …} body: (...) bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "cors" url: "http://localhost:8000/post/" __proto__: Response Here is my Django from django.http import HttpResponse, JsonResponse def index(request): string1 = "" if request.method == 'POST': # ...processing upload... string1 = "Hello World" return HttpResponse(string1) And my react request looks like this: async function handleSubmit(event) { let formData = new FormData(); formData.append(file) fetch("http://localhost:8000/post/", { method: "POST", body: formData, enctype: "multipart/form-data", }).then((res) => { console.log(res); }); How can I get the data I need (string1) included in the response object (or without the response object)? I've looked on StackOverflow and around the web and haven't found a solution. I am also not sure whether this is a problem with Django or React but it seems like a Django problem. (Also, I don't believe it is a CORS Problem as … -
how to user prefetch_related and select_related in django rest framework
Hi I have something like this in Model class Task(model.Models): name=model.CharField(max=100) class attachments(model.Models): file=model.FileField() task=model.Foreginkey(Task) In views class myView(APIView): task=Task.object.get(id=1) task_serilizer=TaskSerilizer(task, many=False) in Serilizer class Myserilizer(aerilizer.Serilizers): class Meta: fields='__all__' Now I want to know how I can user select related and prefetch related , its quite confusing right now (And I wrote this code using mobile so kindly forgive me about this) -
Saving 'views.py': Applying code action 'Sort imports'
currently trying to save some python codes in my django but vscode keep showing this popup Saving 'views.py': Applying code action 'Sort imports'. and i dont know how to go about it. I also launched the vscode from my anaconda navigator -
Django DRF (De-)Serializer not working for me?
I'm stumled upon a case I don't understand. I have two related models: class Course(models.Model): code = models.CharField(max_length=10, default='') semester = models.CharField(max_length=10, default='') class Meta: unique_together = [['code', 'semester']] and: class StudentWork(models.Model): code = models.CharField(max_length=10, default='') course = models.ForeignKey(Course,on_delete=models.CASCADE, related_name='student_works') deadline = models.DateTimeField(blank=True) In the StudentWorkSerializer I'd like to expand a course field into [code, semester]: class CourseNaturalSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['code', 'semester'] class StudentWorkWithCourseSerializer(serializers.ModelSerializer): course = CourseNaturalSerializer(read_only=True) class Meta: model = StudentWork fields = ['code', 'course', 'deadline'] This works nicely for GET, e.g. I receive this: {'code': 'HW1', 'course': {'code': 'T101', 'semester': 'S20'}, 'deadline': '2020-09-04T23:59:00+03:00'} but this does not work for POST: POST /studentworks json=dict(code='HW2', course={"code": "T101", "semester": "S20"}, deadline="2020-09-04T23:59") says in the stacktrace: django.db.utils.IntegrityError: NOT NULL constraint failed: botdb_studentwork.course_id So this looks to me that {"code": "T101", "semester": "S20"} does not de-serialize into Course object and it's id is not passed to StudentWork's create? What should I do? Thanks in advance! -
Django form not submitting in POST
Been having an issue where I am unable to upload files into my form. From what I can gather on my own, it's because I'm not submitting in POST (since uploaded files aren't saved unless you're in POST) but I don't know why that's the case. Here's my code: Views.py def commission(request): if request.method == "POST": form = CommissionForm(request.POST) if form.is_valid(): subject = str(form.cleaned_data.get("name")) + "'s commission request" message = form.cleaned_data.get("name") + ",\nhas requested a commission, with the following request:\n" + form.cleaned_data.get("request") + "\n Reply to them using their email:\n" + form.cleaned_data['email'] email = form.cleaned_data['email'] print(form.cleaned_data) attach = request.FILES['reference'] try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) if attach != None: mail.attach(attach.name, attach.read(), attach.content_type) mail.send() return redirect("main-commissions-success") except: return render(request, "main/commissions.html", {"form": form}) return render(request, "main/commissions.html", {"form": form}) else: form = CommissionForm() return render(request, "main/commissions.html", {"form": form}) Commissions.html <div class="row"> <div class="content-section card w-50 mx-auto my-5"> <div class="card-body"> <form method="POST" action="" class="border border-light m-10" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 text-center">Request A Painting</legend> {{ form|crispy }} </fieldset> <div class="form-group text-center"> <button class="btn btn-outline-info" type="submit">Send Request</button> </div> </form> </div> </div> </div> And since this has no model relation, I'm not going to bother adding it here. Hopefully someone can … -
Django Extended Group's Permissions not applied to users
So I have extended Django's Group model to add an extra field like so: class MyModel(Group): extra_field = models.TextField(null=True, blank=True) On doing this, each instance of MyModel created, creates a Group instance as well. If I add a user to the resulting group with user.groups.add(group), the group is added as expected. However, the permissions from the MyModel group do not seem to have trickled down to the user i.e Doing user.get_all_permissions(), get_group_permissions() or even testing a user.has_permission(mygroup_permission) returns nothing. Only permissions from pure Group instances(created before extending the model) are shown. Is there anything I need to do for permissions on customised groups to be visible on the users? TIA -
Django Unsupported Look Unsupported lookup 'expiration_date' for AutoField or join on the field not permitted
I am new to django and i am getting this error My Models are: class Client(models.Model): """ A client who holds licenses to packages """ client_name = models.CharField(max_length=120, unique=True) def __str__(self): return self.client_name class License(models.Model): """ Data model for a client license allowing access to a package """ client = models.ForeignKey(Client, on_delete=models.DO_NOTHING, related_name="client_licenses") created_datetime = models.DateTimeField(auto_now=True) expiration_datetime = models.DateTimeField(default=get_default_license_expiration(),editable=False) def __str__(self): return (self.client.client_name +" "+ str(self.package) +" "+ str(self.license_type)) def get_default_license_expiration(): """Get the default expiration datetime""" return datetime.utcnow() + LICENSE_EXPIRATION_DELTA I want to annotate the related expiration date field but i get this error Client.objects.prefetch_related("client_licenses")\ .annotate( expiration = F('client_licenses__expiration_date') )\ Even if i just put this column name in values() Client.objects.prefetch_related("client_licenses")\ .values('client_licenses__expiration_date') I am more concerned about what is the cause of this error as i can't figure it out and thats why i can't find a fix for it Any sort of help would be appreciated -
POST http://localhost:8000/api/posts/action/ 400 (Bad Request) when working with React and Django
I am trying to build a full-stack app with React and Django. I am sending an API request from the Django server to React. This is my code how I do it: posts/component.js: import React, {useEffect, useState} from 'react' import { apiPostAction, apiPostCreate, apiPostList} from './lookup' export function PostsComponent(props) { const textAreaRef = React.createRef() const [newPosts, setNewPosts] = useState([]) const handleBackendUpdate = (response, status) =>{ // backend api response handler let tempNewPosts = [...newPosts] if (status === 201){ tempNewPosts.unshift(response) setNewPosts(tempNewPosts) } else { console.log(response) alert("An error occured please try again") } } const handleSubmit = (event) => { event.preventDefault() const newVal = textAreaRef.current.value // backend api request apiPostCreate(newVal, handleBackendUpdate) textAreaRef.current.value = '' } return <div className={props.className}> <div className='col-12 mb-3'> <form onSubmit={handleSubmit}> <textarea ref={textAreaRef} required={true} className='form-control' name='post'> </textarea> <button type='submit' className='btn btn-primary my-3'>Post</button> </form> </div> <PostsList newPosts={newPosts} /> </div> } export function PostsList(props) { const [postsInit, setPostsInit] = useState([]) const [posts, setPosts] = useState([]) const [postsDidSet, setPostsDidSet] = useState(false) useEffect(()=>{ const final = [...props.newPosts].concat(postsInit) if (final.length !== posts.length) { setPosts(final) } }, [props.newPosts, posts, postsInit]) useEffect(() => { if (postsDidSet === false){ const handlePostListLookup = (response, status) => { if (status === 200){ setPostsInit(response) setPostsDidSet(true) } else { alert("There was an … -
NoReverseMatch error . Reverse for '...' not found
I was trying to implement dynamic urls in Django when this occured In my template.py, I added this line <a href="{% url 'Index' %}" role="button">Go to Index</a> My urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include("moviez.urls")) ] My moviez.urls.py from django.urls import path from .views import IndexView app_name = "moviez" urlpatterns = [ path("", IndexView, name="Index") ] I think this should definitely should have work but it returned this error NoReverseMatch at / Reverse for 'Index' not found. 'Index' is not a valid view function or pattern name. Can you please help me debug this? Any help will be appreciated! -
Django: changes made to settings.py are ignored - Production - Gunicorn (with supervisor)
I have my Django application running on an Ubuntu server and I am using gunicorn and supervisor. From when I pulled the first version of the project from GitHub, all the changes made to the Settigs.py file are being ignored and the application is running with the first version of the settings file even after numerous pulls from GitHub. If I cd in my project directory and I view the settings.py file I can see that it is up to date, but all the changes it has got from the first upload are being ignored. I tried to restart supervisor with supervisorctl restart app_name but that doesn't resolve the issue. The app is still running with the first version of the settings.py file. I also made some research for a way to restart gunicorn and foun these commands: sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo nginx -t && sudo systemctl restart nginx but when I run the second command I get this error Failed to restart gunicorn.service: Unit gunicorn.service not found. Any ideas to why all my changes to the settings.py file are being ignored? Thanks in advance. -
Customize Django login without creating custom user?
I am trying to create a Django login that will accept both email or username. I know that it is possible to do this by creating a custom user, but we have multiple applications already that reference the Django base user, so I would prefer to avoid having to go through and change all of those. I have a model that is strictly for the user profile, and includes a required, unique email field. Is there any way to customize the Django login to validate email against that user profile model so that I don't have to create a custom user? -
How to use parameter__contains with SearchRank at Django?
I want to use rank for ordering but also I need search with __contains for wide quering. How I can use contains with SearchRank ? vectors = SearchVector('title', weight='A') + SearchVector('title_english', weight='A') + SearchVector('content', weight='B') + SearchVector('content_english', weight='B') query = SearchQuery(value) articles = Article.objects.annotate( rank = SearchRank(vectors, query) ).filter(search__contains = 'rank', category=category).order_by('rank') -
How to get a list of cities in a country from database?
I have 2 models, City and Country. I want to show cities in the country on a page based on the country selected. I tried to query the Country model passing it to the City model to find all cities related to the country but currently, pages show all cities no matter what is the country. How I can show cities in one country when the user selects the country from the page? Any help or suggestions are highly appreciated. models.py class City(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE, related_name='country') name = models.CharField(max_length=90, verbose_name='City name') slug = models.SlugField(null=True, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('city:cities', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class Country(models.Model): country_name = models.CharField(max_length=50, verbose_name='Country name',unique=True) slug = models.SlugField(null=True, unique=True) def __str__(self): return self.country_name def get_absolute_url(self): return reverse('city:cities', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.country_name) return super().save(*args, **kwargs) views.py class CountriesListView(ListView): template_name = "countries.html" model = Country context_object_name = "countries" class CitiesListView(ListView): template_name = "cities_list.html" model = City context_object_name = "cities" def get_context_data(self, *args, **kwargs): context = super(CitiesListView, self).get_context_data(*args,**kwargs) countries = Country.objects.all() cities = City.objects.filter(country__in=countries) context['cities'] = cities return context templates # countries.html <h1>Countries</h1> … -
Return ListView after post django
couldnt correct this issue after looking into for a longtime, Can anyone pls help me how to return exact same listview after the post class NewsletterList(FormMixin, generic.ListView): queryset = newsletter.objects.filter(status=1).order_by('-created_on') template_name = 'newsletterlist.html' form_class = SubscriberForm def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return NewsletterList.as_view()(request, queryset=newsletter.objects.filter(status=1).order_by('-created_on'), template_name='newsletterlist.html', form_class = SubscriberForm) I am getting an error IntegrityError Exception Value: UNIQUE constraint failed: home_subscriber.email Thanks in advance -
Django property and function
If I have to use same property multiple time, what should be the alternative? As example, I need to use image property in product model as well as customer model. @property def imageURL(self): try: url=self.image.url except: url='' return url how can I do this without repeating the same property in multiple class? -
' No migrations to apply' after Django migration
I made a new app called 'contact' which I added to installed_apps, but I can't create a table in the SQLite database! Django version = 3.1 python manage.py makemigrations contact No changes detected in app 'contact' then for : python manage.py migrate contact Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. I have tried many solutions proposed by members here but None worked like checking "init" file existed in migrations folder and it's empty or commands like these : python manage.py migrate --fake contact zero Operations to perform: Unapply all migrations: contact Running migrations: No migrations to apply. python manage.py migrate contact --fake-initial Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply.