Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url with params, don't know how to test
can anyone give help me how to test the following url in django? path('<int:id>/update/', MyUpdateView.as_view(), name='my-update') So far I have this, but it does not contains the param, therefore it fails. def test_url(self): url = reverse('my-update') self.assertEquals(resolve(url).func.view_class, MyUpdateView) Thank you in advance! -
FormSet with different Form value
I would like to have several form according to the day. That's why using FormSet object is a good idea. Each Form is dynamically changed according to the day. I would like to display several Form, each of them with different day. This is my Form : class AvailabilitiesForm(forms.Form): time_slot = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) def __init__(self,*args,**kwargs): date = kwargs.pop('date') super().__init__(*args,**kwargs) ava_value_timeslots = ((key, val) for key, val in dict(Appointment.TimeSlot.choices).items() if int(key) not in list(Appointment.objects.filter(date = date).values_list('time_slot', flat = True))) self.fields['time_slot'].choices = ava_value_timeslots the ava_value_timeslots variable returns a couple like this : ('0', '9:00 - 09:30'), ('1', '9:00 - 09:30'), ... ('26', '22:00 – 22:30') Is this possible to pass argument in FormSet to have different day of each form like this ? def chooseAvailabilities(request): dates = [ (datetime.date.today() + datetime.timedelta(days=i)).strftime("%Y-%m-%d") for i in range(7)] AvailabilitiesFormSet = formset_factory(AvailabilitiesForm, extra = 7, date = dates) return render(request, 'panel/choose_availabilities.html', {'form' : AvailabilitiesFormSet}) This is actually my view but for one form... : def chooseAvailabilities(request): date_3 = (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d") return render(request, 'panel/choose_availabilities.html', {'form_date_3' : AvailabilitiesForm(date = date_3)}) -
The current path, imgupload/imageprocess, didn't match any of these
I'm trying to create a Django app but I'm stuck at this error. Using the URLconf defined in my_first_site.urls, Django tried these URL patterns, in this order: imgupload [name='home'] imgupload imageprocess [name='imageprocess'] admin/ here are my files: home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Home</title> </head> <body> <form action="/imgupload/imageprocess" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input id="image" type="file" name="image"/> <input type="submit" value="submit"> </form> </body> </html> urls.py (This one is from project i.e. my_first_site) from django.contrib import admin from django.urls import path,include urlpatterns = [ path('imgupload',include('imgupload.urls')), path('admin/', admin.site.urls), ] urls.py -- (this one is from webapp i.e. imgupload) from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.home, name='home'), path('imageprocess', views.imageprocess, name='imageprocess'), ] views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html') def imageprocess(request): return render(request,'result.html') result.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Result page</title> </head> <body> <h1>This is result page</h1> </body> </html> This is the error Django giving me -
Django Model not accepting field
I created the following Model: class dv_model(models.Model): Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200 ) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200 ) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv =models.CharField(_('If Correctly Captured No dv'), max_length=200) Country_dv = models.CharField(_('Country dv'), max_length=200) Region_dv = models.CharField(_('Region dv'), max_length=200) Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200) def __str__(self): return f"Data_Val: {self.Defect_Area_dv}-{self.Key_Driver_dv}-{self.Sub_Key_Driver_dv}-{self.QS_Login_dv}-{self.QS_Name_dv}-{self.Status_dv}-{self.Metric_name_dv}-{self.Correct_Associate_Action_dv}-{self.Correct_investigator_Action_dv}-{self.Action_Correctly_Captured_dv}-{self.Audit_Outcome_dv}-{self.Defect_Area_Investigator_dv}-{self.Document_Name_dv}-{self.Document_Type_dv}-{self.Type_of_Audit_dv}-{self.If_Correctly_Captured_No_dv}-{self.Country_dv}-{self.Region_dv}" Everything worked fine, until I decided to add these two fields: Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) After adding these two fields and running makemigrations and migrate i kept on getting this error: When looking at sqlite3, i dont see the fields: Metric_name_dv & Defect_Area_Investigator_dv: What could I be missing? I tried to clear all past migrations and that didnt work, so i reset it back to normal. Here … -
Display media images from directly Digitalocean app platform
I hosted web app to digital ocean app platform, but media files aren't displaying at all, is there any way to serve that from digital ocean and not to use aws. models file: class Projects(models.Model): title = models.CharField(max_length=50) description = models.TextField() image = models.ImageField(upload_to='images/',null=True) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: ordering = ['title'] view file: class ProjectList(generic.ListView): model = models.Projects url: urlpatterns = [ path('', views.ProjectList.as_view(), name='all'), path('postmodernism/', include('postmodernism.urls', namespace='postmodernism')), path('newstories/', include('newstories.urls', namespace='newstories')), ] template: {% extends 'projects/projects_base.html' %} {% block projects_content %} {% for projects in projects_list %} {% include 'projects/_projects.html' %} {% if projects.title == 'პოსტ მოდერნიზმი' %} <a href="{% url 'projects:postmodernism:postindex' %}"><img src="{{ projects.image.url }}" alt="postmodernism" width="100" height="100"></a> {% endif %} {% if projects.title == 'ამბების ახლებური განვითარება' %} <a href="{% url 'projects:newstories:all' %}"><img src="{{ projects.image.url }}" alt="newstories" width="100" height="100"></a> {% endif %} {% endfor %} {% endblock %} -
Django - Have a user logged in authentication check on every REST API call
I have this code of 2 views in Django. You will notice that each REST API call has a verify_login() function call that ensures that the request contains a verified JWT token. I'm wondering if there's a better way to implement this so that I don't have to have these lines specifically in every REST endpoint verify_response = verify_login(request) if verify_response not None: return verify_response I'm trying to follow the D.R.Y. (Do Not Repeat Yourself) principle of coding. It'd be nice if there was a cleaner way to represent this. I thought about maybe creating a module extending APIView that automatically has this and then all my Views extend that, but runs into the issue of having to call super().API_REQUEST() and then having to do the same if-statement check to see if it's None or not. class PostView(APIView): """ View for Post object * requires token authentication """ # Create post @swagger_auto_schema( request_body=PostSerializer, operation_description="Create a post object" ) def post(self, request): verify_response = verify_login(request) if verify_response not None: return verify_response serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # get all posts @swagger_auto_schema( operation_description="Get all posts from the DB" ) def get(self, request): verify_response = … -
How to determine the correct user to update or delete the post
I want to update and delete post and it is happening but now I want users to Update and delete a post only created by them. Strating from delete this is my delete function def delete_post(request , id): post=Post.objects.get(pk=id) if request.user==post.user: '''I think this if is not true even when the post is created by the same user who is requesting to delete it.''' post.delete() print("ok") return redirect("home") Now when click on delete post it returns to home page but the post remains same.it doesn't delete the post. -
Django Model Meta Ordering on Property
I am trying to tell Django to order my Host model based on a property but am getting the following error: app.Host: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'primary_hostname'. What's the correct approach to ordering based on a property like this? I want the queryset to be ordered by primary hostname which I define as the shortest hostname assigned to each host. models.py class Hostname(models.Model): name = models.CharField(max_length=settings.MAX_CHAR_COUNT, unique=True, blank=False, null=False) class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) names = models.ManyToManyField(Hostname) class Meta: ordering = ['primary_hostname'] @property def primary_hostname(self): return self.names.annotate(text_len=Length('name')).order_by('text_len').first() def __str__(self): return "[Host object: id = {}]".format(self.id) def __repr__(self): return "[Host object: id = {}]".format(self.id) def __eq__(self, other): if isinstance(other, Host): return self.id == other.id return False def __hash__(self) -> int: return hash(self.id) def __lt__(self, other): return self.id < other.id def get_absolute_url(self): return '/host/{}'.format(self.id) -
Django: use a Foreignkey relationship for custom user model
I am writing a webapp where I want to have a general Person table to uniquely identify any person interacting with the website, e.g. to be able to comply to GDPR requests. Some Persons will should also be Users in the authentication sense. I'd like to use Person.email for the username. However, I cannot manage to make authentication / admin interface work. Simplified models: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class Person(models.Model): name = models.CharField(max_length=255, blank=False) email = models.EmailField(blank=False, unique=True) class User(AbstractBaseUser, PermissionsMixin): person = models.OneToOneField(Person, on_delete=models.PROTECT) USERNAME_FIELD = ...# what to put here? I found a very old Django issue that seems related: https://code.djangoproject.com/ticket/21832 Any idea, how to make this work with a foreign key to hold the basic user information? -
How to apply only to optional products using template tags
I want to import the code below using the template tag. I'd like to write a code for a product that has an option and a product that doesn't have an option. "If you don't have an option, launch the following code." How do I write this condition? views.py option_object = Option.objects.all() value_object = Value.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) Models.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) ordering = ['photo_code'] class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code', null=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code', null=True) name = models.CharField(max_length=32, null=True) extra_cost = models.IntegerField(null=True) def __str__(self): return self.name class Meta: ordering = ['value_code'] I'd like to upload the code below only when it's a product without options. … -
Method Not Allowed (GET): and one keyerror
I know this error is because of not adding the 'GET' method but in my program I don't really get the point how I have to use that method in here. In here,I'am trying to add a favorite button in the page describing the car's details. So if I think iam right, the favorite button is embedded within the cardetails page. And when the 'favorite button is clicked, the post method is activated and straight to the method. There, I capture the 'POST' data named 'favorite' from the form .and i store it in the session. Then after every loading of the 'cardetail' page the method, loading the detail page will check whether, if this car is favorite or not, and pass adequate Boolean to HTML. So if only 'POST' is getting excuted then, why 'GET'? and after initializing the 'GET' I still got the Key error for the word 'favorite', in the get_context_data, of accessing the favorite ** This is my html {% if is_favorite %} <h2>This is my favorite</h2> {% else %} <form action="{% url 'favorite' %}" mthod='POST'> {% csrf_token %} <input type="hidden" value={{showroom.id}} name="favorite"> <button> Make This Favorite </button> </form> {% endif %} ** This is my … -
Maximize selection in MultipleChoiceField in Django?
Is there a way to maximize the selected elements in a MultipleChoiceField form ? -
i want to render a html invoice to pdf in django which module is best
i want to render a html invoice to pdf in django which module is best plz help!!! -
trying to send email with python and django
So I am trying to send email with python in a django view problem is everything inside my own server localhost is ok but in production it just dont like to work and I dont know why here is the code @api_view(["PUT"]) @permission_classes([IsAuthenticated]) def updateOrderToPaid(request, pk): order = Order.objects.get(taransId=pk) orderItems = OrderItem.objects.filter(order=order).all() address = ShippingAddress.objects.get(order=order) smtp_server = "smtp.gmail.com" port = 465 sender_email = "MYGMAIL" password = "MYPASSWORD" receiver_email = "RECEIVERGMAIL" message = MIMEMultipart("alternative") message["Subject"] = "DONE" message["From"] = sender_email message["To"] = receiver_email context = ssl.create_default_context() text = """\ ITS WORKING """ html = """\ <html> <body> <p class="text-danger">Done!</p><br> <ul>\n """ html += "\n".join(["<li>" + str(s) + "</li>" for s in orderItems]) html += f""" \n</ul> </body> </html>""" part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) data = { 'pin' : 'SOME_PIN', 'amount' : int(order.TotalPrice), 'transid' : order.taransId } try: response = requests.post('https://panel.aqayepardakht.ir/api/verify', data = data) if response.status_code == 200 and response.text == '1': order.isPaid = True order.paidAt = datetime.now() order.save() return Response({"message": "پرداخت با موفقیت انجام شد"}, status=status.HTTP_200_OK) with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) elif response.status_code == 200 and response.text =='0': print(response, "else if error") return Response({"details": "تراکنش با موفقیت انجام نشد"}, status=status.HTTP_400_BAD_REQUEST) … -
"Could not parse some characters" in Crispy Form Django
I have a checkbox to filter the data in the template. While I have a field name which is having space in between words something like this: Dual Channel. I'm getting errors like this: Could not parse some characters: formChannel.Dual| Channel||as_crispy_field While when I have field names like single words then there is no problem for eg: Dual. but when I have words more than one, then it shows the above error. for eg: Dual Channel This is my template code: <form action="{% url 'main:other' %}" method="POST"> {% csrf_token %} {{ formChannel.Dual Channel|as_crispy_field }} </form> views.py if request.method == 'GET': formChannel = Form() elif request.method == 'POST': formChannel = Form(request.POST) if formChannel.is_valid(): channel_names = [] for channel_name in formChannel.cleaned_data: if formChannel.cleaned_data[channel_name] == True: channel_names.append(channel_name) if channel_names: channel = Channel.objects.filter(channel__in=channel_names) How to get rid out of this problem in Django crispy form -
Django form with queryset
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. Which it does with a signal, @receiver(post_save, I am trying to save the value. But the problem is with my form.py. In my forms.py I filter away assets that are not allowed to be loaned and assets that are loaned at the moment. That gives a problem when I try to edit/update it. Because the form does filter away it's own items. asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) forms.py class Loan_assetForm(forms.ModelForm): loaner_name = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner name'})) location = forms.ModelChoiceField(queryset=Locations.objects.all(), label="Asset loaned form", widget=forms.Select(attrs={'class': 'form-control'})) loaner_address = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaners address'})) loaner_telephone_number = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner telephone number'})) loaner_email = forms.EmailField(label="", max_length=100, widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Loaners email'})) loaner_quicklink = forms.URLField(label="", max_length=100, required=False, widget=forms.URLInput( attrs={'class': 'form-control', 'placeholder': 'Quicklink'})) loaner_type = forms.ModelChoiceField(queryset=Loaner_type.objects.all(), label="Loaner type", widget=forms.Select(attrs={'class': 'form-control'})) … -
my change password forms error is not working in my html page
my html form is {% if messages %} {% for message in messages %} <div class="alert alert-danger" role="alert"> <strong>{{message}}</strong> </div> {% endfor %} {% endif %} {% if form.errors %} {% for field in form %} {% for error in field.error %} <div class="alert alert-danger" role="alert"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% endfor %} {% endif %} my views.py when i enter wrong passwords its redirect me to same page , if i not return the else part of is_valid it giving me object return error. what can i do for showing form error in frontend def change_password(request): if request.user.is_authenticated: if request.method == "POST": form = PasswordChangeForm(request.user , request.POST) if form.is_valid(): user = form.save update_session_auth_hash(request , user) messages.success(request , "Your password is successfully changed") return redirect('index') else: messages.error(request , "Please correct the error below.") return redirect('change_password') else: form = PasswordChangeForm(request.user) return render(request , "change-password.html" , {'form':form}) else: messages.error(request , "Please login to see that page") return redirect('login') -
HttpResponse with JsonResponse for showing detail object django
i'm trying to show detail page which is JsonResponse @login_required def booking_detail_lists(request,id): obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id) bookingvisitors = BookingVisitor.objects.filter(booking=obj) doc = Document.objects.filter(booking=obj) documents = [] for i in doc: documents.append({ 'source':i.docs.url }) visitors = [] for i in bookingvisitors: visitors.append({ 'full_name':i.visitor.full_name, 'reason':i.reason, 'check_in_vis':i.check_in_vis, 'check_out_vis':i.check_out_vis, 'admin':i.admin.username, 'date':i.date }) data = { 'check_in':obj.check_in, 'check_out':obj.check_out, 'taker':obj.taker, 'phone':obj.phone, 'no_person':obj.no_persons, 'id':obj.id, 'takes_by':visitors, 'images':documents, } return JsonResponse({'data':data}) object lists def lists(request): lists = Booking.objects.all() return render(request,'lists.html',{'lists':lists}) lists.html to redirect to booking_detail_lists {% for i in lists %} <button><a href="{% url 'booking:booking_detail_lists' i.id %}"><i class="fas fa-file-invoice"></i></a></button> {% endfor %} my urls.py path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'), in this template i want to show booking_detail_lists view $.ajax({ type:'GET', url:"{%url 'booking:booking_detail_lists' %}" success:function(data){ //add some data into html content } }) <!--some html content--> but i dont know how to give object id to {%url 'booking:booking_detail_lists' %}! and also i'm not sure how to render the json data with http response -
Return redirect with query paramters in Django
Using django-filter a user can set a specific filter. If the user then decides to delete a product with that filter, I would like to return the same page with the given filter applied. Right now I'm using a delete-view to handle the deleting class WishlistProductDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView): model = WishlistProductPrices success_url = "my_wishlist" context_object_name = "links" def test_func(self): """ Check if the logged in user is the one created the link """ link = self.get_object() #Gets the current link if self.request.user == link.user: return True return False def get_success_url(self): messages.success(self.request, "Product was removed") return reverse_lazy("my_wishlist") #Parse the filter parameters to "my_wishlist" The view for generating the HTML where the deleting occurs is the following: @login_required def my_wishlist(request): user = request.user user_products = WishlistProductPrices.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = AddWishlistForm(request.POST) if post_form.is_valid(): messages.success(request, "Thanks a lot!") filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) form = AddWishlistForm() context = { "form":form, "filter":filter } return redirect("my_wishlist") #How to add parameters to else: #Some irrelevant stuff else: #Get request form = AddWishlistForm() context = { "form":form, "filter":filter } return render(request, "discounttracker/add_wishlist.html",context=context) As a comment in [this][1] SO answer I'm thinking about … -
How to upload photos to a fle in m'y computer using Django reste framework
I created a photo model, serializer and view, Users Can upload photos to m'y website. I learned that thé best solution to do it is to upload thé photo on thé computer and the path on data base. But how Can i upload thé photo to my computer via my website or my api ? Modèles.py ken authentification. So for adding an Announcement the user must be authenticated. Models.py class User(AbstractUser): username = None email = models.EmailField(max_length=100, verbose_name='email', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Announcement(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) photo = models.ManyToManyField(Photo, blank=True) class Photo(models.Model): name = models.CharField(max_length=100) content_type = models.CharField(max_length=100) path = models.CharField(max_length=100) Serializers.py class AnnouncementSerializer(serializers.ModelSerializer): author = UserSerializer(required=True) parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class Meta: model = Announcement fields = ['id', 'name', 'author', 'parameters', 'photo'] class UserSerializer(serializers.ModelSerializer): photo = PhotoSerializer() class Meta: model = User fields = ['id', 'email','photo', ] class ParameterSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = '__all__' class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = '__all__' Views.py class AnnouncementCreate(CreateAPIView): permission_classes = [IsAuthenticated] queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer -
Django `LookupError: App 'accounts' doesn't have a 'User' model` causes AUTH_USER_MODEL fails with `accounts.User` has not been installed
I am trying to refactor an existing code base by creating new accounts app with new custom User model. When I try to do makemigrations, I get the following error: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 268, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 270, in get_model raise LookupError( LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 22, in <module> main() File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen … -
Django_filters Reverse foreign key relationship lookup
I am working on an application and recently trying to figure out how to use the reverse foreign key relationship lookup in django filters. models.py class Units(models.Model): Unit = models.CharField(primary_key=True, max_length=200, null=False, unique=True) Type = models.CharField(max_length=200,null=True) Floor = models.CharField(max_length=200, null=True) Building = models.CharField(max_length=200, null=True) def __str__(self): return str(self.Unit) # Keeps track of the inventory updates class Inventory(models.Model): Unit = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, to_field="Unit") Price = models.IntegerField(null=True) Status= models.CharField(max_length=200, null=True) Cancelations_Swaps = models.CharField(max_length=200, null=True) Date_of_update = models.DateField(default=timezone.now) Custumer = models.ForeignKey('Lead', on_delete=models.CASCADE, null=True, to_field="id") def __str__(self): return str(self.Unit) I am displaying in my template all the units with theire latest Status (filtering on Date of update) using the tag bellow @register.filter_function def fil(i): if i.inventory_set.all().order_by('-Date_of_update'): status=i.inventory_set.all().order_by('-Date_of_update')[0].Status return status else: return False and the template is as follows: template {% for i in Unit %} <tr> <td> {{i.Unit }}</td> <td> {{i.Type }}</td> <td> {{i.Floor }}</td> <td> {{i.Building }}</td> <td>{{i|fil}}</td> Where Unit is simply Units.objects.all() I also have built a filter in order to filter the data diplayed as follows: class Unitfilter(django_filters.FilterSet): class Meta: model = Units fields = '__all__' filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, } } I want to be able to filter the … -
For loop in Django templates
I want to display the center of a for loop, for example i for loop the 1-30 then i want to for loop the 11-20 here is the example of how i use the for loop in my html: this is method that i used when i for loop to 30-20 {% for category in category_list reversed %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} this i the method when i for loop to 1-10 {% for category in category_list %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} problem how to for loop the 11-20? thanks for the help! -
Django + PostgreSQL: pagination extremely slow for millions of objects
I have around 6 million objects in my database. For these objects, I need to have a structure page, where the users would browse through the aforementioned 6 million objects as paginated content. My code for the pagination is a total duplicate of what is given in the documentation of Django: def listing(request): movie_list = Movie.objects.all() paginator = Paginator(movie_list , 100) # Show 100 movies per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'movies.html', {'page_obj': page_obj}) Howevre, most of the resulting 60,000 pages with the movies are too long to open, and give 504 timeout errors, which also results in the content being unreadable for GoogleBot (which is actually the main aim of the structure page). What can be the turnaround to prevent these timeouts and ensure the normal load speed for the large paginated content in Django? The database I am using is PostgreSQL. -
send contents of csv from react to django backend
Any advise on how i can get my backend (django) to receive and further process the csv contents sent from react? FrontEnd- import Papa from "papaparse"; export default function App() { return ( <div className="App"> <input type="file" accept=".csv" onChange={(e) => { const files = e.target.files; console.log(files); if (files) { console.log(files[0]); Papa.parse( files[0], { header:true, skipEmptyLines: true, complete: function (results) { console.log("Finished:", results.data); } } ); } }} /> </div> ); } Backend - Standard Django framework