Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RelatedObjectDoesNotExist at / User has no customer
RelatedObjectDoesNotExist at / User has no customer. I am getting this error (RelatedObjectDoesNotExist at / User has no customer.) after I register a user and attempt to sign in. I am only able to sign in with a superuser I created but not with a new user I register. views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): #saving the registered user form.save() username= form.cleaned_data.get('username') messages.success(request, f'Your Account has been created! You can now log in') return redirect('login') else: form = UserCreationForm() #creates an empty form return render(request, 'store/register.html', {'form': form}) #THIS IS THE ERROR IT LEADS ME TO def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() # getting all the products context = { 'products': products, 'cartItems': cartItems } # allows us to use in our template return render(request, 'store/store.html', context) #models.py class Customer(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=50, null=True) email=models.CharField(max_length=200) def __str__(self): return self.name #this will show on our admin panel [yellow page error][1] [1]: https://i.stack.imgur.com/mfKgq.png -
Can a ThreadPoolExecutor be used as a DB connection pool for Django's ORM?
I have an async python application that uses Django's ORM and executes concurrent queries. For the concurrent queries I am using a ThreadPoolExecutor with 10 worker threads. I set django's CONN_MAX_AGE setting to 5 minutes, so the database connection will be open during that time. All queries are wrapped in a try/finally block that closes old connections by calling django.db.close_old_connections() like: import asyncio from django.db import close_old_connections def async_query(...): async def decorator(...): try: return await asyncio.get_running_loop().run_in_executor(...) finally: close_old_connections() return decorator Is that the right way to make a connection pool? I am using Python 3.7.7, Django 2.2.12 and MySQL 8. -
Django Generic views not working for PUT , GET , UPDATE , PATCH
I have RetrieveUpdateDestroyAPIView view like this. class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): lookup_field='id' serializer_class = TasksSerializer def get_queryset(self): query_set=Task.objects.get(id=self.kwargs['id']) def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) and my urls like this path('task_detail/<int:id>', TaskRetrieveUpdateDestroyAPIView.as_view(), name="get_task"), I am trying to PUT , PATCH , GET but getting same error { "detail": "Not found.", "status_code": 404 } -
Django Video File
I have a problem when I try to display a video in a post. It won't display it HTML FILE {% if post.video %} <video width="400" height="300" controls > <source src={{post.video.url}}" type="video/mp4" > </video> {% endif %} Models.py class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now ) #one user can have multiple posts, but one post can only have one author author = models.ForeignKey(User, on_delete = models.CASCADE) image = models.ImageField(blank = True, null=True, upload_to='post-images') video = models.FileField(blank=True, null=True, upload_to='post-images') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') how can I solve this -
Is it possible convert an serializer Field to array
While using DRF I need create a list of values inside my API response which I could not manage yet. For my User and Media serializers, I have come by this solution. class UserMediaSerializer(serializers.ModelSerializer): thumb = HyperlinkedSorlImageField( '40x40', options={"crop": "center"}, source='image', read_only=True ) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') src=serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = [ "thumb", "image", "src"] def get_src(self, obj): src = get_thumbnail(obj.image, '200x200', crop='center', quality=99).url return src class UserDisplaySerializer(serializers.ModelSerializer): thumbnail = HyperlinkedSorlImageField( '40x40', options={"crop": "center"}, source='image', read_only=True ) middle_thumbnail = HyperlinkedSorlImageField( '75x75', options={"crop": "center"}, source='image', read_only=True ) big_thumbnail = HyperlinkedSorlImageField( '120x120', options={"crop": "center"}, source='image', read_only=True ) media = serializers.SerializerMethodField(read_only=True) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') class Meta: model = User fields = [ "username", "big_thumbnail","middle_thumbnail", "thumbnail","image", "media"] def get_media(self, instance): user = User.objects.get(username=instance) serializer = UserMediaSerializer(user, read_only=True) return serializer.data and my views: class TeacherListView(APIView): queryset = User.objects.filter(is_active=1) serializer_class = UserDisplaySerializer lookup_field = "username" def get(self, request, format=None): users = User.objects.filter(is_active=1).filter(is_teacher=1) serializer = UserDisplaySerializer(users, many=True) return Response(serializer.data) now my API response: #api_view HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "username": "ytsejam", "big_thumbnail": "/media/cache/98/82/9882fa018db6f63c56f095d39729bdc8.jpg", "middle_thumbnail": … -
python codes dosent work in template django
I don't know why but my code doesn't work I don't know where the problem is .please help my product doesn't appear on the template although I have saved products in the database > {% for product in products %} > <div class="col-md-6 col-lg-3 ftco-animate"> > <div class="product"> > {% if product.ImgProduct %} > <a href="#" class="img-prod"><img class="img-fluid" src="{{ product.ImgProduct.url }}" alt="Colorlib > Template"> > <div class="overlay"></div> > </a> > {% endif %} > <div class="text py-3 pb-4 px-3 text-center"> > <h3><a href="#">{{ product.product_name }}</a></h3> > <div class="d-flex"> > <div class="pricing"> > <p class="price"><span>{{ product.product_price }}</span></p> > </div> > </div> > <div class="bottom-area d-flex px-3"> > <div class="m-auto d-flex"> > <a href="#" class="add-to-cart d-flex justify-content-center align-items-center text-center"> > <span><i class="ion-ios-menu"></i></span> > </a> > <a href="#" class="buy-now d-flex justify-content-center align-items-center mx-1"> > <span><i class="ion-ios-cart"></i></span> > </a> > <a href="#" class="heart d-flex justify-content-center align-items-center "> > <span><i class="ion-ios-heart"></i></span> > </a> > </div> > </div> > </div> > </div> > </div> > > {% endfor %} -
Django Rest Framework User List Is Missing 1 User
In Django i have a view that list all the user using Serializer by Django Rest Framework. class UserListView(generics.ListAPIView): def get_queryset(self): return UserListSerializer.Meta.model.objects.all() renderer_classes = (JSONRenderer,) permission_classes = (IsAuthenticated,IsAdminUser) serializer_class = UserListSerializer pagination_class = StandardResultsSetPagination I got all the user from the view except 1, lets say with the username noobmaster. And then i use Django shell to check it manually. UserListSerializer.Meta.model.objects.all() the result of that is including noobmaster. I even try this UserListSerializer(<User: noobmaster>) and it worked. I dont understand what happenned to the view, why it doesnt index noobmaster. any clue? -
Django get related objects in ManyToMany relationship
I have Post and each post contains list of categories The problem is when i get a Post its returning for me the Categories by its ids and i need the whole Category Object Post Model class Post(models.Model): title = models.CharField(max_length=50) notes = models.TextField() image = models.ImageField(upload_to="post_image") time = models.CharField(max_length=50) steps = models.ManyToManyField(Step) categories = models.ManyToManyField(Category) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title @api_view() def get_all_posts(request): all_posts = Post.objects.all() data = JobSerializer(all_posts , many = True).data return Response({"data" : data}) and this is the response { "data": [ { "id": 1, "title": "asdfasdsdasd", "notes": "asdasd", "image": "/post_image/117336221_134077201701397_2783193147332010898_o_oPPEef1.jpg", "time": "12:41", "created_at": "2020-09-24T01:06:58Z", "steps": [ 2 ], "categories": [ 1 ] } ] } -
Using Django with AWS DynamoDB
according to the Django documentation: ENGINE Default: '' (Empty string) The database backend to use. The built-in database backends are: 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' You can use a database backend that doesn’t ship with Django by setting ENGINE to a fully-qualified path (i.e. mypackage.backends.whatever). How can I use DynamoDB with Django? What is the fully-qualified path? Thank you. -
Django search among specific user
I'm looking for how to filter the model with the characteristic is_sugar = True. As I use filter for the search fields I don't really understand how to do it. class UserProfile (models.Model): ... is_sugar = models.BooleanField(default=False) def get_queryset(self): query = self.request.GET.get('q', None) if query is not None: self.update_search_query(query) nutriscore = Post.objects.filter( Q(title__icontains=query) | Q(slug__icontains=query) ).distinct() user = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) ).distinct() catego = Catego.objects.filter( Q(name__icontains=query) ).distinct() #UserProfile.objects.filter(is_sugar=True) I don't know how to manage with two filters usersugar = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) ).distinct() results = chain(nutriscore,user,catego,usersugar) -
is there a way to use an npm package within django without a bundler?
hi I have a Django project which depends on a Django package editorjs, the only way I could get it to work was with npm, but I need it to run without npm, my browser supports type = "module for script tags and i don't need it to be compatible with other browsers, this is my code right now: <script type="module"> import EditorJS from "@editorjs/editorjs"; import Header from "@editorjs/header"; import List from "@editorjs/list"; const editor = new EditorJS({ holder: "editorjs", tools: { header: { class: Header, inlineToolbar: ["link"], }, list: { class: List, inlineToolbar: true, }, embed: { class: Embed, config: { services: { youtube: true, coub: true, }, }, }, }, }); let saveBtn = document.getElementById("savebtn"); saveBtn.addEventListener("click", function () { editor .save() .then((outputData) => { console.log("Article data: ", outputData); }) .catch((error) => { console.log("saving failed: ", error); }); }); </script> and I load the library from a CDN: <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script> the editorjs object works even without explicitly importing it, but none of the others do (header, list, embed, and a couple of other ones I tried) any help would be greatly appreciated thanks in advance -
How to return ordered by date QuerySet with unique field
I have a news aggregator based on Django REST + PostgreSQL. In my view I want to return distincted by link articles (source, title, text, link fields) and sorted by import_date desc. Here is my code: class ArticleViewSet(viewsets.ModelViewSet): """list of news by subscription for authorised users only""" permission_classes = [permissions.IsAuthenticated] def get_queryset(self): """filter news by current user subscriptions""" subs = self.request.user.profile.subscriptions return Article.objects.filter(source__in=subs) \ .order_by('-import_date', 'link') \ .distinct('import_date', 'link') \ def get_serializer_class(self): """news with preview text when listing""" if self.action == 'list': return ArticleListSerializer return ArticleSerializer So I expect to get the list of unique articles sorted by date desc. But my query works only for 'import_date', links not unique. If I swap positions: def get_queryset(self): """filter news by current user subscriptions""" subs = self.request.user.profile.subscriptions return Article.objects.filter(source__in=subs) \ .order_by('link, '-import_date') \ .distinct('link', 'import_date') \ Then sorting by date doesn't work. I concluded that distinct works with only one parameter. My question: how to finally get my unique list of articles sorted by date? Don't understand how to make distinct() work for 2 values. Thanks! -
How to send Push Notifications at Specific times listed in a Django Model
I am looking to use my django rest framework project along with django push notifications to send notifications to iOS users. I want these notifications to be sent at times specified in my django models. What would be the best way to achieve something like this? -
render method returns html code not showing page in django
I am implementing google-sso from login.html and after successful login, it should render to dashboard.html file but, in response render() is giving only HTML code of dashboard rather than showing on the browser. and my dashboard.html file is in dashboard app. so basically I have two app abc and dashboard. Is there anything I am doing wrong? abc/views.py def google_sso(response): return render(response,"abc/login.html",{}) def abc(request): return render(request,"dashboard/dashboard.html",{}) urls.py from django.contrib import admin from django.urls import path, include from abc import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('abc',views.abc, name="abc"), path('',include('dashboard.urls')), ] login.html <html> {% csrf_token %} <script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; function onSignIn(googleUser) { console.log("Sign in successful! Yay!"); let id_token = googleUser.getAuthResponse().id_token; let xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:8000/abc'); xhr.responseType = 'document'; xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function () { }; let send_params = 'provider=google-oauth2&code=' + id_token; xhr.send(send_params); } </script> </html> dashboard/dashboard.html <html> <head> Welcome!! </head> <title>Welcome!!</title> <html> -
Increase the performance in Django ORM
contents = Content.objects.filter(is_excluded=False).prefetch_related('likes').order_by('-id').all()[:500] result = [(v for v in contents if len(v.likes.all()) > 24] return result I want to return the content which has more than 25 like and 500 recently content. This works, but is there other way to increase the performance? -
Pillow is not found by Django thouhg it is installed using docker
Hello I am following this tutorial tutorial link. Everything is working fine but when i run bellow command it says pillow is not found but pillow already is installed. docker-compose -f docker-compose.prod.yml exec app python manage.py migrate --noinput This is the error: employee.Employee.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". students.Student.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Then i again try to install using bellow command docker-compose -f docker-compose.prod.yml exec app python -m pip install Pillow And it says pillow is Pillow is already installed Requirement already satisfied: Pillow in /usr/local/lib/python3.8/site-packages (6.2.1) Here is my docker file ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev zlib-dev jpeg-dev musl-dev # lint RUN pip install --upgrade pip RUN pip install Pillow COPY . . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps … -
Django createView passing current user_id to Modelform
I am trying to make a calendar app and currently trying to stop people from being about to save an event when they are already busy during that time period. I believe my issue is that the modelForm doesn't have the user_id as part of the form object. how can I pass the user_id so I can use it to filter with the clean(). I tried using get_form_kwargs() but this doesn't seem to be the correct route to take. Please can you point me in the right direction of how to do this. view.py class CalendarEventAdd(LoginRequiredMixin, CreateView): model = Event form_class = EventForm template_name = 'calendar_create_event_form.html' success_url = reverse_lazy('calendar_list') def form_valid(self, form): form.instance.manage = self.request.user return super(CalendarEventAdd, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super(CalendarEventAdd, self).get_form_kwargs() kwargs['user_id'] = self.request.user return kwargs form.py class EventForm(forms.ModelForm): class Meta: model = Event widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ['avilibility','start_time','end_time'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) def clean(self, *args, **kwargs): form_start_time = self.cleaned_data.get('start_time') form_end_time = self.cleaned_data.get('end_time') form_manage_id = self.cleaned_data.get('manage_id') between = Event.objects.filter(manage_id=1, end_time__gte=form_start_time, start_time__lte=form_end_time) if between: raise forms.ValidationError('Already Calendar entry … -
Truncate content for Mdeditor (content as markdownx) - Django
I installed Mdeditor and everything works fine. My problem is when I want to truncate the content of my BlogPost in template. And this is how it looks. This is my model blog/models.py class BlogPost(models.Model): # blogpost_set -> queryset # id = models.IntegerField() # pk user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True, height_field='height_field', width_field='width_field') height_field = models.PositiveIntegerField(default=0) width_field = models.PositiveIntegerField(default=0) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # hello world -> hello-world content = MDTextField(default=' ') # content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) category = models.CharField(max_length=255, default='issue') private = models.BooleanField(default = False) tags = TaggableManager() objects = BlogPostManager() This is the template's code for the page in the image: <article class="blog-item heading_space wow fadeIn text-center text-md-left" data-wow-delay="300ms"> <div class="image"> <img src="{{ blog_post.image.url }}" alt="blog" class="border_radius"></div> <h3 class="darkcolor font-light bottom10 top30"> <a href="{{ blog_post.get_absolute_url }}">{{ blog_post.title|capfirst }}</a></h3> <ul class="commment"> <li><a href="#."><i class="fas fa-calendar"></i>{{ blog_post.publish_date }}</a></li> <!-- <li><a href="#."><i class="fas fa-comments"></i></a></li> --> <li><a href="#."><i class="fas fa-user"></i>{{ blog_post.user }}</a></li> </ul> <p class="top15">{{blog_post.content|linebreaks|truncatewords:50}}</p> <!-- <div id="content"><textarea> blog_post.content| </textarea> </div> --> </article> Is there any way to make it show content with truncatewords as markdown ? Or something that is gonna look … -
django-notifications-hq remove notification after creation
I am using django-notifications-hq to send notifications between users. Assuming I create a notification with the following code: notify.send(sender=user, recipient=other_user, verb=message, target=target_obj) Now how can I delete the exact same notification in a separate view? I have looked into the documentation and could not come up across a method that can delete a notification. I appreciate any help in advance! -
How can i find the object location in model using django and pandas
Not that the sequanse of the objects id in the model start from 26500 not from one... when i use iloc[] to get object ihave index erro because the system can not fiend the location.. I am using django and have my data from csv files -
Is there a way to return two combined lists from get_queryset instead of just the query set?
I am using Django to generate a generic.ListView of objects. I am also using Elastic Search for search results. My question is how can I combine my queryset with an ordered list of JSON objects? get_queryset only allows me to return one variable (the queryset) but I need get_context_data to be able to access both the queryset and the associated metadata for the search results. I created a below hack that works but looking for a better solution. def get_queryset(self): # just get 2 documents, in my actual code the queryset is generated by a list of IDs # from the Elastic Search query qs = Document.objects.all()[:2] # create some fake search results, in my actual code I get a similar looking JSON # objects with metadata like result score or highlighted snippets from the search corpus fake_results = [ { 'meta': { 'highlight': { 'title': ['ABC'], 'content': ['123', '456'], } } }, { 'meta': { 'highlight': { 'content': ['789'], } } } ] # this is a hack (i think) but need to merge the metadata from search results into the queryset object for doc, result in zip(qs, fake_results): if 'highlight' in result['meta']: doc.snippet = result['meta']['highlight'] return qs def … -
"You cannot set the upload handlers after the upload has been processed"
I need to change my upload handlers to get the root directory of all files that are upload, in order to do this, I created a custom upload handlers on my views.py: class NamedMemoryFileUploadHandler(MemoryFileUploadHandler): def file_complete(self, file_size): in_memory_file = super().file_complete(file_size) if in_memory_file is None: return return in_memory_file, self.file_name class NamedTemporaryFileUploadHandler(TemporaryFileUploadHandler): def file_complete(self, file_size): temporary_file = super().file_complete(file_size) if temporary_file is None: return return temporary_file, self.file_name @csrf_exempt def upload_files(request): request.upload_handlers = [ NamedMemoryFileUploadHandler(request), NamedTemporaryFileUploadHandler(request), ] return _upload_files(request) @csrf_protect def _upload_files(request): files = request.FILES.getlist("upload") for tmp_file, full_path in files: print(tmp_file, full_path) return files @login_required(login_url='/login/') def code(request): upload_files(request) if request.method == 'POST': form = UploadDocumentForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() if request.FILES: for f in request.FILES.getlist('upload'): data = f.read() print(data) form = UploadDocumentForm() return render(request, 'main/example.html', {'form':form}) But when I try to upload a folder, I get this error: Traceback (most recent call last): File "/Code/modapp/site/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Code/mysite/mysite/main/views.py", line 72, in code upload_files(request) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Code/mysite/mysite/main/views.py", line 57, in upload_files NamedTemporaryFileUploadHandler(request), File "/Code/modapp/site/env/lib/python3.7/site-packages/django/http/request.py", line 300, in … -
Select items from database and add it to temporary table, and make changes to selected items in django
I have created an inventory management system using django. A feature to be added to that... All the items with details are stored in database. Some items are to be transferred to another location. So the user must be given an option to choose items from database and update the location field and file field of selected items at a time. -
How to call Django model class instance method into Django template?
Can anyone plz help me? I want to display the average rating for a tutor in my Django template, but I don't know how to call a model class instance method into a template. Models.py class ratings(models.Model): username= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) rating=models.FloatField() tutorname=models.ForeignKey(tutors,related_name='ratingss',on_delete=models.CASCADE) created_date=models.DateTimeField(auto_created=True) def get_absolute_url(self): return reverse('tutor_detail') def rating_avg(self,id): return self.objects.filter(id=tutorname_id).aggregate(Avg('rating')) -
Django Admin FileFile not open from listview
in my model class i have an attribute like this one: c_cv = models.FileField(upload_to='mysite/static/docs', max_length=254, validators=[FileExtensionValidator(['pdf']),validate_fsize], verbose_name="CV") in my admin.py: list_display = ('c_data', 'c_sur', 'c_name', 'c_dob', 'c_en', 'c_de', 'c_cv') but when i open from admin my list page, if i click on my c_cv field in list i get an error because link does not start from 127.0.0.1:8000/mysite/static/docs/file.pdf but instead from 127.0.0.1:8000/admin/cv_list/... How can i force in admin looking my c_cv field using root of domain instad actual path as prefix? So many thanks in advance