Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin custom list filter different model
I'm using Django 2.1 and I need to add a list filter on model(#1) admin page referencing a field from a different model(#2)(which has a foreign key referencing the current model(#1) These are my 2 models: class ParentProduct(models.Model): parent_id = models.CharField(max_length=255, validators=[ParentIDValidator]) name = models.CharField(max_length=255, validators=[ProductNameValidator]) parent_slug = models.SlugField(max_length=255) parent_brand = models.ForeignKey(Brand, related_name='parent_brand_product', blank=False, on_delete=models.CASCADE) ... class ParentProductCategory(models.Model): parent_product = models.ForeignKey(ParentProduct, related_name='parent_product_pro_category', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='parent_category_pro_category', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) Here is my admin class for model 'ParentProduct': class ParentProductAdmin(admin.ModelAdmin): resource_class = ParentProductResource form = ParentProductForm class Media: pass change_list_template = 'admin/products/parent_product_change_list.html' actions = [deactivate_selected_products, approve_selected_products] list_display = [ 'parent_id', 'name', 'parent_brand', 'product_hsn', 'gst', 'product_image', 'status' ] inlines = [ ParentProductCategoryAdmin ] list_filter = [ParentBrandFilter, 'status'] Here is the ParentBrandFilter: class ParentBrandFilter(AutocompleteFilter): title = 'Brand' field_name = 'parent_brand' This works correctly because the field 'parent_brand' exists on my model 'ParentProduct'. How do I get the same autocomplete type list filter for the field category which is actually inside the 'ParentProductCategory' model. Note: 'ParentProductCategory' -> 'ParentProduct' is a many-to-one mapping. Note #2: Django admin add custom filter. I tried going through this question but couldn't get through with the approach and also my requirement is different. I … -
Unable to parse Formdata in django
I convert the JSON object to FormData. The JSON object has an array of objects , which format is not readble by django backend. Here's the example of my Formdata. Unable to parse the client_stage array in django irn_no: 12345 client_ref_number: 0000077918IN01 / RecID 85403089 application_number: 201827002702 priority_date: 2015-7-01 application_type: PCT National Phase forum: 27 client_stage[0][c_client]: 94566 client_stage[0][c_office]: 93466 client_stage[0][client_type]: Applicant client_stage[1][c_client]: 31483 client_stage[1][c_office]: 28466 client_stage[1][client_type]: Instructor client_stage[2][c_client]: 23585 client_stage[2][c_office]: 67593 client_stage[2][client_type]: Debtor client_stage[3][c_contact]: 97031 client_stage[3][client_type]: Inventor ipo_branch: 1 matter_category: 1 matter_sub_category: 1 matter_standing_instruction: ddd -
Filter queryset against current user in Django Rest Framework where User sits in seperate model
I am trying to limit a set of list objects made a available to those created by specific users in Django Rest Framework. I have been following the DRF documentation to filter against current user, the main difference I have is that User is defined in a seperate model to the the objects I am working with. I'm trying to use a dunder to fix this but the data isn't filtering correctly. All list objects are available to any user rather than only some objects being available based on the creator who is logged in. I'm wondering if anyone could propose a way forward? Here are the models: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) And here are the views.py #this is where a user can assign cafe objects to their list object (but currently can see all lists) class UserVenueViewSet(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() def get_queryset(self): user = self.request.user return UserVenue.objects.get_queryset().filter(list__user=user) #this shows all lists for a user class UserList(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def get_queryset(self): return super().get_queryset().filter(user=self.request.user) -
Insufficient number of arguments or no entry found.| Web Pack build failed Djago React
Please help me out , I am learning raect with django tutorial here, and here I installed babel using yarn but now "npm run dev" is failed. Please also refer me a suitable community for instant solutions.enter this is package.jsone this is terminal screen shot -
The Compose file '.\docker-compose.yml' is invalid because: Invalid top-level property "db"
My docker-compose.yml file contains version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: Dockerfile contains # Pull base image FROM python:3.8.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Using that command to build image and run the containers with one command $ docker-compose up -d --build And gitbash terminal throwing that error $ docker-compose up -d --build The Compose file '.\docker-compose.yml' is invalid because: Invalid top-level property "db". Valid top-level sections for this Compose file are: version, services, networks, volumes, secrets, configs, and extensions starting with "x-". You might be seeing this error because you're using the wrong Compose file version. Either specify a supported version (e.g "2.2" or "3.3") and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1. For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/ According to … -
How to run two separate django instances on same server/domain?
To elaborate, we have one server we have setup to run django. Issue is that we need to establish "public" test server that our end-users can test, before we push the changes to the production. Now, normally we would have production.domain.com and testing.domain.com and run them separately. However, due to conditions outside our control we only have access to one domain. We will call it program.domain.com for now. Is there a way to setup two entirely separete django intances (AKA we do not want admin of production version to be able to access demo data, and vice versa) in such a way we have program.domain.com/production and program.domain.com/development enviroments? I tried to look over Djangos "sites"-framework but as far as I can see, all it can do is separate the domains, not paths, and it has both "sites" able to access same data. However, as I stated, we want to keep our testing data and our production data separate. Yet, we want to give our end-user testers access to version they can tinker around, keeping separation of production, public test and local development(runserver command) versions. -
Django Vue Js Authentication
I am working on a project using Django and Vue Js. Currently, i have authenticated my users and they can now log in and logout and tokens are also saved in stores too. But I have added permission to my Django views and in my models, I also included a user field as a foreignkey. The problem now is to know the user making a post from the vue js point so my user field is not null just like other fields like content field is populated by form data. Thanks. AddPost.vue data() { return { posts: { user: "", name: "", version: "", }, submitted: false, } }, methods: { post: function() { axios.post('http://127.0.0.1:8000/posts/list/', this.posts, { headers: { Authorization: `Bearer ${this.$store.state.accessToken}` } }) .then(function(data) { console.log(data); this.submitted = true; }); } } -
Disable django-summernote widget
How can I disable the summernote widget used by django-summernote? I have read many similar posts in Stackoverflow, but none has solved my problem. I tried solving it with jQuery, but nothing is returned when I use $('#summernote') or $('.summernote') from the browsers object inspector, that even if I already loaded the summernote script in the head of my html models.py class Note(models.Model): contents = models.TextField() forms.py class UpdateNoteModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['contents'].disabled = True class Meta: model = Note fields = ('contents') widgets['contents'] = SummernoteWidget() html head <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> html body <script type="text/javascript"> $(document).ready(function(){ $('#summernote').summernote('disable'); }); </script > -
UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id
I am working on small django project and for that i have created one functionality that allows user to create and then join the group. Now , here is the problem : whenever i leave the group and try to rejoin it , it shows error that i mentioned in the the question "UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id" here is my join class : class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group, slug=self.kwargs.get('slug')) from sqlite3 import IntegrityError try: # GroupMember.objects.create(group=group) GroupMember.objects.create(user=self.request.user, group=group) except IntegrityError: messages.warning(self.request, 'already a member!') else: messages.success(self.request, 'You are now a member!') return super().get(request, *args, **kwargs) Can you please help me to solve this problem ? Thank you ! :) -
Django Practice to organize views that have same permission
The login_required, user_passes_test and permission_required decorator only apply to specific functions, similar for the mixin. But is it a good practice to put @permission_required('polls.add_choice') to each and every view that require such permission? I think it is quite common that multiple views have the same permission. For example, you have an employer and job seeker, only the employer can add company name/ address, post a job and check job application. It is also common that the website requires login for most of its pages. So my question is what is the idioms/practice assigning the same permission to multiple views? The only recipe I can find is Beginning Django - Listing 10-8. Permission checks in urls. Pay for include () definitions. Another approach is to swap the view function inside a class (as static method) and do some trick the add permission to all methods. Is there any better sulotion? Or any reason not to do that? -
How to run WebSocket (django-channels) in production Pythonanywhere?
I created a simple chat app using WebSockets after following the official Django-channels tutorial. However, I can't get it to work in production. I have done a few google searching to find out a forum in Pythonanywhere saying that they don't support WebSocket, I contacted the team and they told me the same thing. I have done even more google searching and found things related to Daphne server, Nginx, and a few other things I never heard about before. As I'm new to Django-channels I'm currently very confused! Is there something I can do to make my WebSocket website run normally in Pythonanywhere on production (for free of course) Or I have to delete all of the WebSocket code and replace it with repetitive Http called to check of new messages (With AJAX)? And if there is no other solution but to move to repetitive Http calls, is there any other web hosting service that offers free play which includes free SSL certification, the domain name (such as mydomain.servicename.com) instead of random characters, and WebSocket support? Thanks the code i use I don't know if it was relevant, also it's working perfect in development so i don't think there is … -
Bug Display whith chrome
i am currently on a python / django project, i am also using bootsrap. I have a display bug only with google chrome. When I load my page everything is fine then when I scroll, the bug occurs: When I reload the page everything is back to normal: This bug is not present on the project locally, only from production on a server (ubuntu with gunicorn and nginx). When i hover the mouse over this white block, the text displays randomly. This is not the only place where it happens. I don't know if this problem is known but I have absolutely no idea what it might be. here is the part of the code that we see in picture : <!-- Description content --> <div class="container-fluid main-color-dark-bg pb-4"> <div lass="row"> <div class="col-lg-8 col-md-10 col-12 mx-auto mb-3"> <a href="{% url 'watch' 'theoretical' level video_previous %}" class="text-left subpart-link">< Précèdent</a> <a href="{% url 'watch' 'theoretical' level video_next %}" class="subpart-link float-right">Suivant ></a> </div> </div> <!-- Description --> <div class="row col-lg-8 col-md-10 col-12 mx-auto"> <div class=""> <p class="theoretical-watch-p ext-md-left text-center"> {{ video.description }} </p> </div> </div> <!-- Sous parties et Ressources --> <div class="row mx-auto col-lg-8 col-md-10 col-12"> <!-- Sous parties--> <div class="col-lg-7 col-12 … -
Trying to display image in web page generated by django view
My goal is to have a simple form that allows a user to input a function to graph, along with a display window, and once the user hits the submit button, I would like numpy and matplotlib to take the form data and generate a figure, then display that figure in the new web page. So far, I followed this where it says "Create the Contact Form View" to get the form to generate and make the data usable. I found this which allows me to display the image. However, the image takes up the whole browser window like so. I would instead like that image to display in my web page. I'm very new to Django, so sorry if this doesn't make sense or isn't enough info. I'd love to give clarification or additional info if needed. Here is my app's views.py: from django.shortcuts import render from django.http import HttpResponse from matplotlib.backends.backend_agg import FigureCanvasAgg from .forms import GraphingInput from .graphing_tool import graph import io # Create your views here. def grapher_tool_input(request): submitted = False if request.method == 'POST': form = GraphingInput(request.POST) if form.is_valid(): cd = form.cleaned_data fig = graph(cd['left_end'], cd['right_end'], cd['top'], cd['bottom'], cd['function']) response = HttpResponse(content_type='image/jpg') canvas = FigureCanvasAgg(fig) … -
Django icalendar dtstart datetime issue
I have a form in Django-python for an event program. I'm trying to create an ics file for the events with icalendar, for this, I want to get the values 'dtstart' and 'dtend' from the variables 'starttime' and 'endtime' in the form, but I'm getting the code: Wrong datetime format. Anyone with any advice to solve this issue? ERROR elif not ical[15:]: return datetime(*timetuple) elif ical[15:16] == 'Z': return pytz.utc.localize(datetime(*timetuple)) else: raise ValueError(ical) except: raise ValueError('Wrong datetime format: %s' % ical) … class vDuration(object): """Subclass of timedelta that renders itself in the iCalendar DURATION format. """ CODE def event(request, id=None): instance = Event_cal() if id: instance = get_object_or_404(Event_cal, pk=id) else: instance = Event_cal() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() startdate = request.POST.get('starttime') endate = request.POST.get('endtime') event = Event() event.add('summary', 'My Summary') event.add('dtstart', vDatetime.from_ical(startdate)) event.add('dtend', vDatetime.from_ical(endate)) Thanks in advance, I am learning python, so I don't have have much experience. -
Django GET returning only 1 child instead of collection
I'm having an issue getting a list of objects with a GET request on this endpoint: /api/stock/{bar_id}/ It should return a list of stock for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. When I make the GET request I only end up getting the first stock, but I should be getting the full list of stocks. I understand that this end point is not RESTful, however it is an imposed constraint I have to make do with it and can't even pass the bar_id as parameter. What am I missing or doing wrong? Thanks for your responses! Object returned after the GET request: { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } Expected returned object after the GET request: { [ { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 }, { "ref_id": { "ref": "second", "name": "second one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } ] } Here is my BarSerializer: from rest_framework import serializers from … -
AttributeError: 'QuerySet' object has no attribute 'objects' when using count
I have a problem with show total number of my list. I want to count the total number of my list_value variable below, but it seems it returning an error. AttributeError: 'QuerySet' object has no attribute 'objects' when using count views.py @login_required(login_url='log_permission') def data_table(request): if request.method=='POST': province = request.POST['province'] municipality = request.POST['municipality'] list_value = Person.objects.filter(province=province,municipality=municipality) final_value = list_value.objects.count() //here is the problem print(final_value) return render(request, 'data_table.html') models class Person(models.Model): covid_id = models.CharField(max_length=50) firstname = models.CharField(max_length=50) middle = models.CharField(max_length=50,blank=True, null=True) lastname = models.CharField(max_length=50,blank=True) extension = models.CharField(max_length=50,blank=True, null=True) province = models.CharField(max_length=50) municipality = models.CharField(max_length=50) barangay = models.CharField(max_length=50) remarks = models.CharField(max_length=50) amount = models.CharField(max_length=50) remarks_miray = models.CharField(max_length=50) count = models.CharField(max_length=50) -
TypeError: missing 2 required positional arguments
from django.db import models from hospital.models import HospitalList from django.db.models.signals import post_save from django.dispatch import receiver class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) @receiver(post_save) def set_h_code(instance, created, **kwargs): testhospital = HospitalList.objects.get(code = h_code).values('code') instance.d_code = testhospital instance.save() d_code = models.CharField(primary_key=True, max_length = 200, default=set_h_code, editable=False) error code: TypeError: set_h_code() missing 2 required positional arguments: 'instance' and 'created' I don't know why the error occurs. What is the problem? Thanks in advance to those who respond. -
Invalid HTTP_HOST header: 'api.binance.com'
I keep on getting this error the moment I enabled error messaging in Django. I research about it. This binance thingy is about bitcoin and it is not related to what I'm doing. Is this an attack that's trying to check/access my Django Web app? Invalid HTTP_HOST header: 'api.binance.com'. You may need to add 'api.binance.com' to ALLOWED_HOSTS. Report at /api/v1/time Invalid HTTP_HOST header: 'api.binance.com'. You may need to add 'api.binance.com' to ALLOWED_HOSTS. Request Method: GET I check the api.binance.com. It is like an api and it says "ok" What's your thought about this? -
Django submit button refreshes page and does not remove values
I'm trying to get this submit button to work in my CreateView and have been debugging for quite some time now. Basically when I enter my values into the form and click submit, the page refreshes and all the values simply remain there. I do have a form_valid method where I print form.cleaned_data, but over at the terminal, it only shows a POST request but did not show form.cleaned_data. I'm really not sure where the problem is at all. I've tried setting action="." in my html but it simply says page not found. Any help is super appreciated! Template: travelandentertainment_create.html: {% extends "user/base.html" %} {% load crispy_forms_tags %} {% load static %} {% load widget_tweaks %} {% block topbar %} {% if user.is_authenticated %} <a class="navbar-brand" href="{% url 'budget-home' %}">Select Category</a> <a class="navbar-brand" href="{% url 'logout' %}">Logout</a> {% else %} <a class="navbar-brand" href="{% url 'register' %}">Register</a> {% endif %} {% endblock %} {% block content %} <a class="btn btn-success mb-3 mt-3" href="{% url 'budget-home' %}" role="button">Back</a> <a class="btn btn-success mb-3 mt-3" href="{% url 'budget-travelandentertainment_list' %}" role="button">View Submitted List</a> <form method="POST"> {% csrf_token %} <div class="field"> <label class="label">Company</label> <div class="control"> {% render_field form.company class="form-control" %} </div> </div> <div class="field"> <label class="label">Air … -
Does using static variables in django views a good practise?
Assuming the get method is called at least one time before the post method.(This is not my actual code, if there's any silly mistake, don't consider it, my question is CAN I INSTANTIATE AND USE STATIC VARIABLE LIKE BELOW) class McqView(View): course=None all_questions=None start_time=None def get(self,request,someid): if not McqView.course: McqView.course = Course.objects.get(id=someid) if not McqView.all_questions: McqView.all_questions = Question.objects.filter(course=McqExamView.course) if not McqView.start_time: McqView.start_time = datetime.now() #using the static variables somewhere here def post(self,request): #using the same static variables somewhere here I thought of using the two as member variables but it is not possible. So I thought of using the two as static variables. will any problem arise while using this method? like 1.The static variables become None 2.The static variables gets instantiated more than once. If the second case happens, the start_time variable value will become wrong. Please tell me whether this is a wrong approach, if it is wrong tell me an alternative way of doing the same. -
How to make the ImageField optional in django rest framework API
I'm pretty tired finding solution to make the imagefield optional in django rest framework API. I tried each and every solution I found in stack overflow but nothing seems to be working fine. I know there are fewer posts related to same query but I didn't find the solution in that. Let me explain you what is my requirements. Here is my User model with some basic info fields including an Image field. models.py class User(models.Model): firstname = models.CharField(max_length=100, validators=[firstname_check]) lastname = models.CharField(max_length=100, blank=True, null=True, validators=[lastname_check]) username = models.CharField(max_length=100, unique=True, blank=True, null=True, validators=[username_check]) email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=50, blank=True, null=True, validators=[password_check]) mobnum = models.CharField(max_length=50, blank=True, null=True, validators=[mobile_num_len]) timestamp = models.DateTimeField(auto_now=True) gender = models.CharField(max_length=50, blank=True, null=True) language = models.CharField(max_length=100, blank=True, null=True) profile_img = models.ImageField(upload_to ='uploads/', blank=True, null=True) is_active = models.BooleanField(default=False, blank=True, null=True) serializer.py from utils import Base64ImageField class UserMannualSerializer(serializers.ModelSerializer): profile_img = Base64ImageField( max_length=None, use_url=True, allow_empty_file=True, required=False ) class Meta: model = User fields = [ 'firstname', 'lastname', 'username', 'email', 'password', 'mobnum', 'gender', 'language', 'timestamp' 'profile_img' ] Here is the Base64ImageField() function which I've written inside the utils.py file. Which will take the base64 string and convert it back and store in the server and that is happening properly. But … -
Django problem: RuntimeError: __class__ not set defining 'AbstractBaseUser' as
Just upgraded Ubuntu from 18.04 to 20.04 and my Django project failed (it worked fine on Ubuntu 18.04) with the following message: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fc139bd14c0> Traceback (most recent call last): File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? My requirements.txt is as follows: appdirs==1.4.2 beautifulsoup4==4.5.3 certifi==2018.4.16 chardet==3.0.4 dj-database-url==0.4.2 dj-static==0.0.6 Django==1.10.6 django-toolbelt==0.0.1 gunicorn==19.7.0 idna==2.6 packaging==16.8 psycopg2==2.8.6 … -
Foreign key multiple images not saving in django
i am trying to save a form with multiple images. I have two models post model and images model. The problem is when i try to upload the post the images are not saving. i can upload images in form but when i click Post it only save title, images are not save. Can someone point me what i do wrong please? Models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) class Images(models.Model): article = models.ForeignKey(POst, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to='media/images/',blank=True, null=True) Views.py class CreatePost(CreateView): model = Post form_class = Createpost template_name = 'add_post.html' def get_context_data(self, **kwargs): data = super(CreatePost, self).get_context_data(**kwargs) data['form_images'] = PostImageFormSet() if self.request.POST: data['form_images'] = PostImageFormSet(self.request.POST, self.request.FILES) else: data['form_images'] = PostImageFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() form_img = context['form_images'] atc = form.save(commit=False) save = atc.save() if form_img.is_valid(): form_img.instance = save form_img.save() form.save_m2m() return super(CreatePost, self).form_valid(form) def get_success_url(self): return reverse('detail', args=(self.object.id,)) forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images exclude = () widgets = { 'images': forms.ClearableFileInput(attrs={'multiple':True}), } class CreatePost(forms.ModelForm): class Meta: model = Post fields = ["title",] PostImageFormSet = inlineformset_factory( Post, Images, form=ImageForm, extra=1, can_delete=True, #fields=['images'], ) templates <form class="post" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{form.title.label_tag … -
Pagination for Django with big data
I tried to install pagination into Django app. I searched many codes online how to do that but most of them are for pagination with small amount of data. My app has close to 1 million PostgreSQL data. It seems like handling those big data with a typical pagination system does not work. you can see tons of pagination there. I want to line them like << 1 2 3 4 5 6 7 8 9 10 >> Here are my codes. urls.py urlpatterns = [ path('', views.find,name='find'), path('<int:num>', views.find, name='find'), path('detail/<str:pk>', DbDetail.as_view()), path('list', views.DbList.as_view(), name='list'), ] views.py class DbList(ListView): model = TestEu paginate_by = 10 def get_queryset(self): q_word = self.request.GET.get('query') if q_word: sql = 'select * from test_eu' sql += " where eng_discription ~ '.*" + q_word +".*'" object_list = TestEu.objects.raw(sql) else: sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) # object_list = TestEu.objects.all() return object_list testeu_list.html {% if is_paginated %} <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for … -
How to convert the list into a list of dictionaries?
I have a list like this. ls = ['Size:10,color:red,', 'Size:10,color: blue,'] I want to convert the list into this format. [{'Size':'10','color':'red'}, {'Size':'10','color': 'blue'}] What I have tried is: [dict([pair.split(":", 1)]) for pair in ls] # It gave me output like this. [{'Size': '10,color:red,'}, {'Size': '10,color: blue,'}] But this method works if the list is like this ['color:blue,'] but didn't worked properly with the above list.