Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Excel file generated by django cannot open because the file format or file extension is not valid?
Say there's a dataframe from pandas like : mediabuy cpa mediabuy cpc cost 2020-02 0.00 371929.95 15956581.16 16328511.11 2020-04 1311.92 224747.07 26710431.81 26936490.80 total 1311.92 596677.02 42667012.97 43265001.91 And I want to return a excel file by using django, and I'tried with codes as below: # return excel view df = pd.DataFrame(data, index=index, columns=column) # saved as excel excel_writer = pd.ExcelWriter(path='temp.xlsx', engine='openpyxl') df.to_excel(excel_writer) wb = excel_writer.book response = HttpResponse(save_virtual_workbook(wb)) response["Content-Type"] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'attachment; filename={}.xlsx'.format("data")) return response I'm working with python3.6.8, django2.2.4, pandas1.0.3, openpyxl3.0.3 But I always get a excel file cannot opened because the file format or file extension is not valid Why the excel file is not correct? How can I make it work ? Thanks. -
Checking if one field is less than the other - forms, Django
I try to check if the start time is less than the end time. If I did not want to raise a error. My code looks like this: class TimeOpeningHoursForm(forms.ModelForm): class Meta: model = BusinessOpeningHours fields = ('mon_st', 'mon_end', ...) widgets = { 'mon_st': Select(attrs={'class': 'form-control'}), 'mon_end': Select(attrs={'class': 'form-control'}), ... } def compare_mon(self): cleaned_data = self.cleaned_data st = cleaned_data['mon_st'] end = cleaned_data['mon_end'] if st > end : raise forms.ValidationError("The start time must be less than the end time.") else: return cleaned_data My validation code works as if it wasn't there at all. Does not raise errors or verify correctness. In the view, of course, I check form via the is_valid method. -
How to fix unbound local error on django?
I have written this code. Every time I assign a variable I am getting "local variable 'obj' referenced before assignment". I don't know where I did wrong. This is my view.py file: def blog_detail(request, slug): queryset = Blog.objects.filter(slug=slug) if queryset.count() == 1: obj = queryset.first() templates = "temp_app.html" context = {"object": obj} return render(request, templates, context) Here is my models.py file class Blog(models.Model): title = models.TextField() slug = models.SlugField() content = models.TextField(null=True, blank=True) every time I run the server I am getting UnboundLocalError. bt if I use "queryset" without assigning it into "obj" I don't get the error. I am getting the error after assigning the "queryset" in "obj". Where am I doing wrong? -
How to setup all ForeignKey & OneToOneField fields into raw_id_fields
For example I have this 3 fields as set_soal, soal and folder. I need to assign all of this fields into raw_id_fields into their admin.ModelAdmin without add manually per-single fields. class DaftarSoal(TimeStampedModel): .... set_soal = ForeignKey(SetSoal, ...) soal = ForeignKey(Soal, ...) folder = ForeignKey(Folder, ...) the basic way to enable raw fields inside the admin.ModelAdmin look like this; @admin.register(DaftarSoal, site=admin_site) class DaftarSoalAdmin(admin.ModelAdmin): raw_id_fields = ('set_soal', 'soal', 'folder') # manually But, can I setup all that OneToOneField and ForeignKey fields automatically into raw_id_fields without add it manually? such as applying the class mixin, for example: class CustomAdminMixin: raw_id_fields = () def __init__(self): self.setup_raw_id_fields() def setup_raw_id_fields(self): # search all OneToOneField and ForeignKey fields. # and assign into variable `raw_id_fields` above. and to implement it; @admin.register(DaftarSoal, site=admin_site) class DaftarSoalAdmin(CustomAdminMixin, admin.ModelAdmin): pass @admin.register(AnotherModel, site=admin_site) class AnotherModelAdmin(CustomAdminMixin, admin.ModelAdmin): pass -
How to capture radio box values in Django?
I am working on a Django project. I am not able to capture radio button values. What I want is this - if out of three answers(three radio buttons with values a, b, c respectively, the user selects say b, then in the answers table, out of the three answers columns, the second column should capture 'b' and nothing (meaning blank) should be stored in the other two columns. Quite obviously the "nm" I have written in request.POST as of now is wrong. Thanks in advance for any help. The form code is as below <input type="radio" id = "ans1" name = "nm" value = "a" class = "form-control">{{question.ans1}} <input type="radio" id = "ans2" name = "nm" value = "b" class ="form-control">{{question.ans2}} <input type="radio" id = "ans3" name = "nm" value = "c" class ="form-control">{{question.ans3}} <input type="submit" value="Submit"> In the views file the function is as below def updateans(request): if request.method == 'POST': user_id = request.POST['user_id'] questionid = request.POST['questionid'] ans1 = request.POST['nm'] ans2 = request.POST['nm'] ans3 = request.POST['nm'] myans = Answers(questionid_id = questionid, userid_id = user_id, ans1 = ans1, ans2=ans2, ans3=ans3) myans.save() -
Django - How to use greater than in template
i am having an issue when implementing greater than in my template. I have a post in homepage which users liked, and i have my friends profile image displayed beside like count if my friends liked a post. Now if 10 friends liked my post, i want only five of my friends profile image to display on template, and there will be a "+" at the end of displayed images. The "+" signifies that there are more friends who liked my post. I tried this but not working; def home(request): #all post in homepage posts = Post.objects.filter(poster_profile=request.user) #Show friend who liked Post friends_like_img = request.user.profile.friends.all().order_by('-id') context = {'posts':posts,'friends_img':friends_img} return render..... {% for post in posts %} {% for img in friends_like_img %} {% if img in post.likes.all > 20 %} <img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> {% else %} <img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> + {% endif %} {% endfor %} {% endfor %} -
Django 2.2 Deleting any user in the admin interface raises this error
Here is the error in question: IntegrityError at /admin/accounts/user/ FOREIGN KEY constraint failed I looked elsewhere and couldn't find any simple fix. This error I believe is because I've used a custom User model where I inherit from AbstractBaseUser because I want my website to not have usernames but instead users are identified primarily by their emails. I am at a beginner level for using Django as well as anything related to relational databases. #src/accounts.models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.core.mail import send_mail from django.template.loader import get_template class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) # change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.is_active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email,full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_active = … -
Django ModuleNotFoundError: No module named 'product'
I am absolute new to django and I have followed the example of Django documentation https://docs.djangoproject.com/en/3.0/intro/tutorial01/ but getting a problem in main project's urls.py file which is Module not found error pls help -
How do i shorten this django view request
def test(request): x1 = MenuItem.objects.filter(item_category__icontains='PANCAKE') x2 = MenuItem.objects.filter(item_category__icontains='EGG') x3 = MenuItem.objects.filter(item_category__icontains='PANNIS') x4 = MenuItem.objects.filter(item_category__icontains='SUBS') x5 = MenuItem.objects.filter(item_category__icontains='WRAPS') x6 = MenuItem.objects.filter(item_category__icontains='TEA') x7 = MenuItem.objects.filter(item_category__icontains='FRAPPE') x8 = MenuItem.objects.filter(item_category__icontains='SMOOTHIE') x9 = MenuItem.objects.filter(item_category__icontains='GLUTENF') x10 =MenuItem.objects.filter(item_category__icontains='WAFFLES') x11 =MenuItem.objects.filter(item_category__icontains='TOAST') x12 =MenuItem.objects.filter(item_category__icontains='HOTPASTA') x13 =MenuItem.objects.filter(item_category__icontains='BAGELS') x14 =MenuItem.objects.filter(item_category__icontains='FRIES') x15 =MenuItem.objects.filter(item_category__icontains='SALADS') x16 =MenuItem.objects.filter(item_category__icontains='DESSERTS') context={ 'p':x1, 'e':x2, 'pn':x3, 's':x4, 'w':x5, 't':x6, 'f':x7, 'sm':x8, 'gf':x9, 'wa':x10, 'to':x11, 'hp':x12, 'b':x13, 'fr':x14, 'sa':x15, 'd':x16, } return render(request, 'posts/test.html',context) I know there are many different ways to shorten this but i was considering taking suggestions on how would someone who's proficient in python frameworks would handle this -
Django Custom model method with additional parameters
I want a price method on model which accepts a parameter from the frontend form and calculates the price and displays in a Listview. MODELS.PY class VehicleCategory: @property def price(self, duration): for item in VehiclePrice.objects.all(): If item.vehicle_category.title == self.title and (duration >= item.slab.start and duration <= item.slab.end): return item.net_price VIEWS.PY class HomeView(ListView): template_name = 'app/home.html' def get(self, request): if request.method == "GET": start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') duration = end_date - start_date return (duration.days + 1) context = { 'vehiclecategory':VehicleCategory.objects.all()} here I get the duration, how can I pass this in the model method price parameter and get the above Queryset to work????""" -
Container exited with code 0 when run from docker-compose
I am trying to run a container from docker file. **docker-compose.yml** services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src ports: - 8000:8000 **Dockerfile** this is entry in Docker file ENTRYPOINT bash start.sh **start.sh** #!/bin/bash ## run gunicorn in background...... gunicorn --chdir hello --bind :8000 hello_django.wsgi:application & when i build image from same Dockerfile, its working fine. when i launch from docker-compose up, it shows exited with code 0. I wanted to know the reason why my docker exited (Exited (0) 18 seconds ago) ?? -
Django ManytoMany not showing in admin
Respected Sir/Mam, As my models are in MANYTOMANY relationship so connection should be in both ways.But is it not. Example in admin For BusinessProfile section i am able to see name and image field of Services model as they are in MANYTOMANY relationship, But this not the case for viceversa.Like i am not able to see BusinessProfile models field in Services model in admin. Is my model structure correct. I have also attached images. models.py class Service(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='image', blank = True) #business_profile = models.ManyToManyField("BusinessProfile", blank=True, related_name="business_of_services") def __str__(self): return "Service - {}".format(self.name) class BusinessProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) business_name = models.CharField(max_length=100, unique =True) register_date = models.DateTimeField(default=timezone.now) pan_number = models.IntegerField(unique=True) pan_name = models.CharField(max_length=100) address = models.TextField(max_length=200) pincode = models.IntegerField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) service = models.ManyToManyField("Service", blank=True, related_name="services_of_business") image = models.ManyToManyField("Service", related_name="image_of_business") def __str__(self): return "Business - {}".format(self.business_name) -
Create a custom user tacking method on the wagtail?
I have been followed [accordbox][1] to create some models. For user activity analysis, I would like to save the user_id, restaurant_id, and time on visited RestaurantPage. The logic is when get_context function in the Restaurant Model, it will use tracking function to save record in TrackUserRestaurant model. The print function is used to check the request.user.id and restaurant.id. But I can't get any new record on the TrackUserRestaurant model. Did I misunderstand something? I am new to Django and wagtail. class RestaurantPage(Page) .... #other fields view_count = models.PositiveIntegerField(default=0, editable=False) @property def restaurant_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(RestaurantPage, self).get_context(request, *args, **kwargs) context['restaurant_page'] = self.restaurant_page context['restaurant'] = self self.tracking(request) return context def tracking(self, request): current_user = request.user track = TrackUserRest track.user = 0 track.rest = self.pk track.date = timezone.now() if request.user.id != None: print('user id:' + str(current_user.id)) track.user = request.user.pk print('rest id:' + str(self.pk)) return track.save(self) class TrackUserRestaurant(models.Model): user_id = models.PositiveIntegerField(null=True) restaurant_id = models.PositiveIntegerField(blank=False, null=False) time = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: ordering = ('time', ) def __str__(self): return 'Restaurant Tracking system: user.id({}) viewed rest.id({}) at timezone.({})'.format(self.user_id, self.restaurant_id, self.time) -
using djongo and while making miratioin its showing AppRegistryNotReady
I am using Djongo in django for using mongodb. I tried to migrate the models all the models get migrated but when i need arrayfield. and when i am trying to migrate it. Its rasing error. I tried all things what i was able to find on internet.I tried Django.setup in manage.py field i tried all things please help me. code for my setting Django settings for questions project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w6(hj1%1d=kc%z^$@0z4&r(02&00jz#-t%ql2l7g&#3+!(csjr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multi_questions', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'questions.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], … -
Python, enumerate list assignment index out of range error
I have the following code: iva_versamenti_totale={'Liquidazione IVA': [sum(t) for t in zip(*iva_versamenti.values())],} utilizzato=dict() riporto=dict() utilizzato['Key_1']=list(0 for m in range(13)) riporto['Key_2']=list(0 for m in range(13)) for index, xi in enumerate(iva_saldo_totale['Saldo IVA'], 0): if xi > 0 : riporto['Key_2'][index] = riporto['Key_2'][index] + xi else: riporto['Key_2'][index] = riporto['Key_2'][index-1]-utilizzato['Key_1'][index] for index, xi in enumerate(iva_saldo_totale['Saldo IVA'], 1): if xi > 0 : utilizzato['Key_1'][index] == 0 elif riporto['Key_2'][index-1] >= xi: utilizzato['Key_1'][index] = - xi else: utilizzato['Key_1'][index]=riporto['Key_2'][index-1] But Python give me the following error: IndexError: list assignment index out of range I want that the for loop start from the second element of each variable (riporto, utilizzato and iva_versamenti_totale) in such a way that I can set manually these values. -
Generating token in django
I'm very new to django. I'm working on resetting the password with PasswordResetView. I've made all the necessary configurations. All the views are working properly(reset,done,confirm,complete) but the email is not being sent. I'm using file based method. The mail content is also stored in a text file successfully. The text file MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Subject: Password reset on 127.0.0.1:8000 From: webmaster@localhost To: user1991@gmail.com Date: Fri, 08 May 2020 13:07:44 -0000 Message-ID: <158894326451.7060.3441580324173819052@DESKTOP-G46QTJT.localdomain> You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000. Please go to the following page and choose a new password: http://127.0.0.1:8000/accounts/profile/reset-password/confirm/Ng/5gb-4468fc4f5f5c9ad67d90/ Your username, in case you’ve forgotten: test@5 Thanks for using our site! The 127.0.0.1:8000 team ------------------------------------------------------------------------------- But i didn't received the mail. Hoping for a solution. Atleast I want to know how to generate the one time url alone like the one django created automatically. -
Django accessing sublass of model within a form
I have different models in a class and subclasses of them - and I want to create a form for all of them - I know I could do it with a single page for all of them, but is there a smart way to this? models.py: class ProductBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Per part", decimal_places=2, max_digits=6) class Software(ProductBase): link = models.URLField('Download Link', blank=True) class Hardware(ProductBase): shipping_cost = models.DecimalField("UPS", decimal_places=2, max_digits=6) forms.py: class ProductForm(ModelForm): required_css_class = "required" class Meta: model = Product fields = "__all__" views.py: def add_part(request): submitted = False if request.method == "POST": form = PartForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/add_product/?submitted=True") else: form = PartForm() if "submitted" in request.GET: submitted = True return render(request, "gap/add_product.html", {"form": form, "submitted": submitted}) add_product.html: {% extends 'base.html' %} {% block content %} {% if submitted %} <p class="success">Part was saved successfully.</p> {% else %} <form action="" method="post" novalidate> <table> {{ form.as_table }} <tr><td><input type="submit" value="Submit"></td></tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} This way I create the form to save a product in the database in the probably simplest way. Is there any way I can achieve something like a dropdown menu that lets me … -
AttributeError: 'TweetSerializer' object has no attribute 'get_likes'
I am following a series https://youtu.be/f1R_bykXHGE and I am getting error with the code for serializers. Code is working fine but when i tried to add likes = serializers.SerializerMethodField(read_only=True) it's throwing error AttributeError: 'TweetSerializer' object has no attribute 'get_likes'. I am not able find the error. serializers.py class TweetSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content','likes'] def get_likes(self, obj): return obj.likes.count() def validate_content(self, value): if len(value) > MAX_TWEET_LENGTH: raise forms.ValidationError("This tweet is too long") return value #models.py import random from django.conf import settings from django.db import models User = settings.AUTH_USER_MODEL # Create your models here. class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): # id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) #many users can have maany tweets likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) content = models.TextField(null=True, blank=True) image = models.FileField(upload_to='images/', blank=True, null=True) #image bs file timestamp = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.content class Meta: ordering = ['-id'] def serialize(self): return { "id": self.id, "content": self.content, "likes": random.randint(0, 25) } views.py import random from django.conf import settings from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from … -
Why my django code is not sending Email to my newly register user?
I want to verify new user registration by sending confirmation token to email of user. the code is showing no error in console but also not sending the email to user email. i am using django 3.0 and python 3.8. the code is executing this part, when i signup a new user, this message poput but i am not receiving email "Open your email to activate account." help me to fix this: views.py from .forms import CreateUserForm from django.views import View from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.core.mail import EmailMessage from .tokens import activation_token from django.contrib.auth.models import User from django.contrib import messages class RegisterPageView(View): def get(self, request, *args, **kwargs): form = CreateUserForm() template_name = "register/register.html" return render(request, template_name, {"form": form}) def post(self, request, *args, **kwargs): form = CreateUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() message_subject = "Activate your account" domain_url = get_current_site(request) user_email = form.cleaned_data["email"] message = render_to_string( "Backend/accounts/activation_message.html", { "domain": domain_url.domain, "user": user, "uid": urlsafe_base64_encode(force_bytes(user.id)), "token": activation_token.make_token(user), }, ) email = EmailMessage(message_subject, message, to=[user_email]) email.send() activation_msg = "Open your email to activate account." return render( request, "Backend/accounts/activate_email.html", {"activation_msg": activation_msg} ) template_name = 'register/register.html' … -
I want values in single row if job no and invoice no is same
This is my windows look like but i want the values in a single row not multiple rows if job no is same -
Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['catalog/projects/(?P<pk>[0-9]+)/$']
I am trying to figure out why it is that I am getting the following error: NoReverseMatch at /catalog/projects/delete/1/ Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['catalog/projects/(?P<pk>[0-9]+)/$'] Here's the url for the catalog app. I think the problem is from here but I don't seem to be able to figure it out urls.py urlpatterns = [ path('projects/', views.ProjectListView.as_view(), name='list'), path('projects/<int:pk>/', views.ProjectDetailView.as_view(), name='project_detail'), path('projects/new/', views.ProjectCreateView.as_view(), name='project_new'), path('projects/edit/<int:pk>/', views.ProjectUpdateView.as_view(), name='project_edit'), path('projects/delete/<int:pk>/', views.ProjectDeleteView.as_view(), name='project_delete') ] views.py class HomeView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context = { 'projects': Project.objects.all(), 'num_projects': Project.objects.all().count(), 'num_ongoing_projects': Project.objects.filter(status__exact='OG').count(), 'num_clients': Client.objects.count(), } return context class ProjectListView(ListView): context_object_name = 'projects' model = Project paginate_by = 10 class ProjectDetailView(DetailView): model = Project context_object_name = 'project_detail' template_name = 'catalog/project_detail.html' class ProjectCreateView(CreateView): # login_url = '/login/' form_class = ProjectForm model = Project redirect_field_name = 'catalog/project_detail.html' class ProjectUpdateView(UpdateView): fields=('project_title', 'location', 'status', 'start_date', 'end_date') # form_class = ProjectForm model = Project redirect_field_name = 'catalog/project_detail.html' class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('catalog:list') The edit button works fine but the delete button doesn't. It produces that error code project_detail.html {% extends "catalog/catalog_base.html" %} {% block content %} <h1>Welcome to Project Detail Page</h1> <h2>Project details:</h2> <p><strong>Project Number:</strong> … -
Django 2.2 Deleting any user on the admin interface raises this error
Here is the error in question: IntegrityError at /admin/accounts/user/ FOREIGN KEY constraint failed I looked elsewhere and couldn't find any simple fix. This error I believe is because I've used a custom User model where I inherit from AbstractBaseUser because I want my website to not have usernames but instead users are identified primarily by their emails. I am at a beginner level for using Django as well as anything related to relational databases. #src/accounts.models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.core.mail import send_mail from django.template.loader import get_template class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) # change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.is_active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email,full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_active = … -
Filter by calculated field dependent on foreign key
How to filter django queryset by calculated field dependent on foreign key? This is my models.py: class RealEstate(models.Model): location = models.TextField() @property def is_occupied(self): return Agreement.objects.filter(allocated_house=self, contract_expiration_date__gte=date.today()).exists() class Agreement(models.Model): allocated_house = models.ForeignKey(RealEstate, on_delete=models.CASCADE) contract_expiration_date = models.DateField() I need something like RealEstate.objects.filter(is_occupied=True). Thank you for your time. -
I can't run python manage.py collectstatic?
So I've been trying to fix up an old project of mine made using Django. I've been trying to deploy to heroku and after searching online, someone said I had to run the collectstatic command. But when I do it, this happens (this is after having tweaked loads of stuff in the settings.py): Found another file with the destination path 'admin/js/vendor/select2/i18n/gl.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/js/vendor/select2/i18n/it.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Post-processing 'admin/css/base.7ea12481fb59.css' failed! Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 133, in collect raise processed whitenoise.storage.MissingFileError: The file 'admin/css/fonts.cc6140298ba7.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object … -
Is there possibility for integrating css and html files with django?
i'm working on a personal project that involves full-stack development of a AI Recruiting website.I developed its backend using django.I know basic front end development.(HTML,CSS).But the thing is how to integrate my frontend designs with my django ?.