Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generict django content type , get the object stored in contentype
Well similar questions have been asked, but none of the answers works for me . Bellow is my contentype model class notifyall(models.Model): target_instance=models.ForeignKey(ContentType,null=True,on_delete=models.CASCADE,blank=True) object_id=models.PositiveIntegerField(null=True) target_object=GenericForeignKey('target_instance', 'object_id') As you can see, contentype has a GenericForeignKey to store different kind of objects from different models when notifyall object is created , this is what i will get >>object_id= e.g 20 >>target_instance = class_name_of_model what is the right way to go about retrieving the object stored in contentype model as object_id and target_instance -
Circular import error when importing weasyprint's HTML
I am trying to generate a pdf and I am getting the error below. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'tenderwiz.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The error occurs when I include this line in my view from weasyprint import HTML utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.conf import settings import os from django.template.loader import render_to_string from weasyprint import HTML def render_to_pdf(template_src, context_dict={}): html_template = render_to_string('invoice_render.html', context_dict) pdf_file = HTML(string=html_template).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="invoice.pdf"' return response user_accounts/views.py from .utils import render_to_pdf from django.shortcuts import render, render_to_response, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.contrib import auth from django.template.context_processors import csrf from packages.models import Packages from .forms import (CustomUserForm, CompanyProfileForm, CompanyProfileEditForm, BankingDetailsForm, PayFast_Form, ) from django.contrib.auth import update_session_auth_hash from .models import CompanyProfile, OurDetails from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm, PasswordResetForm from tender_details.models import Category, Keywords, Province from django.core import serializers from django.http import HttpResponse from django.contrib import messages from django.urls import reverse import json from urllib.parse import urlencode, quote_plus import hashlib from django.conf import settings … -
How to test django channel layer with virtual-env on windows 10?
I'm using anaconda to make virtual environment and using it to develop my django apps. Now I'm working on a project that needs to use websocket to send notifications. I followed this Tutorial and first part worked well but this second part needs to open a port on computer to send data between users, using channel_redis and redis on docker to do this stuff, but as I said I'm using virtual-en on my local system. so is there a way to make it happen? The Output: raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) Sorry for bad english 😓 -
TypeError: 'ShiftSerializer' object is not callable
I am trying to do with ModelViewSet. I am facing this error now Here is my viewset=> class ShiftViewSet(viewsets.ModelViewSet): queryset = Shift.objects.all() serializer_class = ShiftSerializer() # filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ('shiftid',) @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('Created_DT').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) @action(methods=['get'], detail=False) def shiftsum(self, request): query = ( Shift.objects.values('shiftid') .annotate(shiftdesc=Max('shiftdesc')) .annotate(overnight=Max('overnight')) .annotate(isspecialshift=Max('isspecialshift')) .annotate(ct=Count('*')) # get count of rows in group .order_by('shiftid') .distinct() ) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) @action(methods=['get'], detail=False) def byshiftid(self, request): shiftid = self.request.query_params.get('shiftid',None) query = self.get_queryset().filter(shiftid=shiftid) serializer = ShiftSerializer(query,many=True) return Response(serializer.data) Here is my router and url => router.register('shifts_mas', ShiftViewSet, base_name='shifts') path('api/', include(router.urls)) Normally I can call like /api/shifts_mas/ and I will get all record of shift but just now i got this error and i dont know why. May i know why? -
pip inside virtual environment is pointing to global installation and doesnt use the virtualenv site packages
I have a local repo where I have installed packages like django, django rest framework with virtual environment, I have pushed it to git and when I have downloaded the repo on a remote server, I have activated the virtualenv using source bin/activate and tried to run django server, it is showing the packages which are installed inside the virtualenv as not installed I have tried to use which python3.5 It gives me /usr/bin/python3.5 And which pip3 gives /usr/local/bin/pip3, what do I need to make the virtualenv to use the packages inside virtual env lib/ folder? I have no aliases set on bashrc, any idea why this is happening? -
Deploying Django site to heroku isn't working
Me and @MD-Khairul-Basar have been talking for a great while on this chat trying to figure out why my site isn't deploying to heroku. I've tried everything that he's suggested but none have worked. I've put my code on Github so you can see it. The recent errors (HTTP 500) seen on the chat are still the most recent on my local computer. Please help :) dj-database-url==0.5.0 Django==2.2.3 django-crispy-forms==1.7.2 gunicorn==19.9.0 Pillow==6.1.0 psycopg2==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 python==3.7.3 -
What should I modify to add a new field in django-rest-framework?
I want to make "channel" available in the next html form. But I don't know how. Can you help me? models.py class Channel(models.Model): name = models.CharField(_('Name'), max_length=100) # 1(User 진행자) : N(Channel) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='vod_owner_channels', verbose_name=_('User')) description = models.TextField(_('Description'), max_length=1000, blank=True) background_image = models.ImageField(_('Background Image'), upload_to='background_image/%Y/%m/%d', blank=True) create_date = models.DateTimeField(_('Channel Create Date'), auto_now_add=True) class Video(models.Model): # 1(Channel) : N(Video) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='vod_channel_videos', verbose_name=_('Channel')) title = models.CharField(_('Title'), max_length=100) description = models.TextField(_('Description'), max_length=1000, blank=True) video = models.FileField(_('Video'), upload_to='video/%Y/%m/%d', blank=True) video_url = models.URLField(_('Video URL'), blank=True) views = models.PositiveIntegerField(_('Views'), default=0) create_date = models.DateTimeField(_('Create Date'), auto_now_add=True) update_date = models.DateTimeField(_('Update date'), auto_now=True) class Comment(models.Model): # 1(User) : N(Comment) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='vod_user_comments', verbose_name=_('Comment')) # 1(Video) : N(Comment) video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='vod_video_comments', verbose_name=_('Video')) content = models.TextField(_('Content'), max_length=1000) create_date = models.DateTimeField(_('Create Date'), auto_now_add=True) update_date = models.DateTimeField(_('Update date'), auto_now=True) reply = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='vod_reply_comments', verbose_name=_('Reply')) class Meta: verbose_name = _('Comment') verbose_name_plural = _('Comments') serializers.py class VideoSerializer(serializers.ModelSerializer): channel = serializers.ReadOnlyField(source='channel.name') class Meta: model = Video fields = ['id', 'channel', 'title', 'description', 'video', 'video_url', 'views', 'create_date', 'update_date'] I tried to make serializers.PrimaryRelatedKey. But it didn't work. I think, I can solve this problem in this code. but I don't have confidence. views.py # … -
How can I answer to shell questions
I am trying to create a simple program to create a superuser for django but I can't answer to the questions after that. os.popen('python manage.py createsuperuser') when this line of code runs, the interpreter asks me to enter a username like the picture in below : How can I answer that using some variables in python codes and not by hand. I want the program to handle it not a human. Also I can't really work with the manage.py file because then I have to change the content in the library which is not good. -
ModelForm in Django
ModelForm: def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ChapterCreateForm, self).__init__(*args, **kwargs) Not working I wana add self.field other. But it not working. -
Parsing static json file and save values to Django Database/model
I have json file in my static folder in my django project. And I want to save the data from json file to my Django Database. This is my model.py from django.db import models class Coming_Soon(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.TextField(blank=True,max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.TextField(blank=True) release_date = models.TextField() this is sample of my json file { "results": [ { "rating": "PG", "cast": [ "Jeremy Ray Taylor", "Gerard Butler", "Abbie Cornish" ], "synopsis": "some synopsis", "movie_title": "(3D/4DX) GEOSTORM", "image_url": "some url", "id": "8595" }, { "rating": "PG", "cast": [ "Jeremy Ray Taylor", "Gerard Butler", "Abbie Cornish" ], "synopsis": "some synopsis", "movie_title": "(ATMOS) GEOSTORM", "image_url": "some url", "id": "8604" }, what should I write on my view so that I can save those data into my django database? This is my views.py: def polls(request): ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json' json_data = open(ROOT_FILE) json_load = json.load(json_data) with open(ROOT_FILE, 'r') as data: parsed_json = json.load(data) for result in parsed_json['results']: # movie_id = [] # movie_id.append(result['id']) # join = " ".join(movie_id) return HttpResponse(result['results']['id']) I really don't have any idea about getting those file into my database. Thank you. -
How to upload files to databse using django in binary field?
I want to create a biometric authentication system, so i need to save bimetric data(thumb image) to database in binary form. How to do same using django? -
Get current user inside customer user creation form while saving
I have a form derived from UserCreationForm. When I create a member as an admin, on behalf of the member, I want to access the current user (admin), check few conditions, modify the new user object and then save. But self.request throws object has no attribute 'request' exception. Tried if self.request.user.is_superuser: inside save method of MemberCreationForm(UserCreationForm): CBV. class MemberCreationForm(UserCreationForm): def save(self, commit=True): record = super(MemberCreationForm, self).save(commit=False) if self.request.user.is_superuser: record.website_role = 3 record.is_staff=True want to get the current user (logged in user) before saving so that I can modify the new object and save according to the logged in users role. -
How can I loop through json file and return it as HttpRespones in Django?
I have a json file inside my static folder in my django project. I want to return on all the 'id', and 'title' of each data. I have this data in my json file. {"results": [ {"id": "1", "movie_title": "COCO","cast":["cast1","cast2"]}, {"id": "2", "movie_title": "THOR","cast":["cast1","cast2"]}, {"id": "3", "movie_title": "IRONMAN","cast":["cast1","cast2"]}]} I have this code that return all data from json file. def polls(request): ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json' json_data = open(ROOT_FILE) json_load = json.load(json_data) return HttpResponse(json.dumps(json_load)) I would like to get, for example, only some specific values like 'id', 'title'. But when I tried to foreach the results from json_load, It only returns the value of first item in file. Here's my code to that. for r in json_load['results']: return HttpResponse(r['id'] + r['movie_title') But this code only return the first data. Thank you. -
Shopping Cart for Django 1.11.7
I'ved developed my webapp using Django==1.11.7. Before 2.x came about. I would like to now add shopping cart into my application. What would be the recommended library to do this ? Thanks. -
Django with Huey task consumer: TestCase methods touch real DB
I'm writing a Django application employing the Huey task queue, configured as described in the relevant Huey docs. Running some basic tests, I disabled the immediate setting to try the manage.py run_huey command to run the task consumer in its own process. I then ran a Django TestCase that invokes a Huey task that writes to the database (which, inside a TestCase, should be a temporary database created for and destroyed after testing.) The task was consumed in the Huey process and functioned as expected; however, the object created in the task run by the test was written to my actual (development) database. I understand why -- whatever magic Django does to spin up a fake database when running tests just doesn't reach across to the Huey consumer process; and I understand that per the Huey docs, its default behavior is to run in immediate mode (executing tasks as soon as they are enqueued without running a scheduling database or a separate consumer process) when Django's DEBUG setting is enabled, so I was stepping out on a limb. However, I feel like I some of the standard Huey features that aren't available in immediate mode -- scheduling tasks to occur … -
IntegrityError Primary Key Invalid
Sorry I am still trying to learn, but can't get past this problem. I am following sentdex's tutorials for django web development, however I have hit a wall - the error shows "django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value '1' that does not have a corresponding value in main_tutorialseries.id." I've tried removing default=1, and on_delete=models.SET_DEFAULT/CASCADE. I've also tried deleting the SQL database, migrations. I've tried using SQ Browser for SQlite to try and change things. Sadly I've spent hours staring at this and trying to find an answer, any help would be greatly appreciated. Thanks! The code is : from django.db import models from datetime import datetime class TutorialCategory(models.Model): tutorial_category = models.CharField(max_length=200) category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200, default=1) class Meta: # Gives the proper plural name for admin verbose_name_plural = "Categories" def __str__(self): return self.tutorial_category class TutorialSeries(models.Model): tutorial_series = models.CharField(max_length=200, default=1) tutorial_category = models.ForeignKey(TutorialCategory, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) class Meta: # otherwise we get "Tutorial Seriess in admin" verbose_name_plural = "Series" def __str__(self): return self.tutorial_series class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published') tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT) tutorial_slug = … -
Saleor - Trying to modify the dashboard (add 'Job Title' to 'Customer' / 'Account')
I'm new here :) I'm trying to build an eCommerce site using Saleor as the framework, I'm having trouble understanding the framework with the intention to modify the admin dashboard and database. To start simple and practice, I'm trying to add a 'Job Title' field to customers, and want this to be editable on the dashboard. Currently, I've performed a django migration and the new field is liked up to the database - I modified /saleor/saleor/account/modles.py class User(PermissionsMixin, AbstractBaseUser): ... job_title = models.CharField(max_length=256, blank=True) PostgreSQL also works fine SELECT * FROM account_user; SQL Output Where I'm completely stuck is actually getting this field to work with the dashboard/ appear. I've gone through editing the files where 'First Name' field appears, as the django /templates/ file seems to reference a 'form' I can only assume is run by ReactJS (which I'm not as familiar with as Python). The files I've modified (and effectively copied what existed for 'First Name') are: added jobTitle: formData.jobTitle, to line 111 on static/dashboard-next/customers/views/CustomerDetails.tsx added block from line 128 on static/customers/components/CustomerDetails/CustomerDetails.tsx added block from line 24 and 61 on static/customers/components/CustomerDetailsPage/CustomerDetailsPage.tsx I'd really appreciate if someone can help point me in the right direction of how saleor / … -
How to include concurrent function in django app?
I'm building a web site with payments which works the following way: User gotta transfer money with some randomly generated comment, while I regularly check if payment was done and in case of success do something. I have function check_payments that check if payment was done and do stuff if so and I wanna run it every 2 minutes concurrently with my site. This function should have access to all models of my web app. How should I do it? -
What do i need to override in a Model or Field in order to have a custom string representation for the admin site in django?
I'm using a custom dict field as the primary key for a model: class Data(models.Model): _id = DictField(default={}, primary_key=True, db_column='_id') If i want to edit an object, i get this link: http://localhost:8000/admin/managerapp/data/OrderedDict(%5B('key1',%20'value1'),%20('key2',%20'value2')%5D)/change/ Which probably means that DictField isn't written very well, as django doesn't know how to serialize it. What do i need to override Data or DictField and what methods in order to tell django how it can transform the dict {'key1': 'value1', 'key2': 'value2'} into a string and how can it transform that string back into the dict again? I'm not very good at django internals and i don't know what keywords to search for. -
More fields than expected in UserCreationForm
I ve just create a project and setting authentification. But for registeration, I m using UserCreateform expected to have username and password fields only. Instead I have many fields like last login, superuser_status, groups, etc... Where is my error ? Forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class SignUpform(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) Views.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.forms import UserChangeForm from .forms import SignUpform def register_user(request): if request.method == 'POST': form = SignUpform(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(request, username=username, password=password) login(request, user) messages.success(request, 'You are registered') # redirect to a succes page return redirect('home') else: form = UserChangeForm() context = {'form': form} return render(request, 'register.html', context) My goal: having only fields defined in signupform. thanks for helping -
How to use startproject --template? (Django 2.2)
I'm attempting to create a Django templates directory via django-admin startproject and --template. I've tried: django-admin startproject main_project --template=./templates However it only creates an empty startproject directory there is nothing reflecting a Django instance in this directory (ie. no urls.py, settings.py, wsgi.py, etc.) - desktop/ |_ main_project/ # directory where startproject will be executed via CLI |_ templates/ I'm expecting a project Python package to be created as described here: https://docs.djangoproject.com/en/2.2/intro/tutorial01/#creating-a-project mysite/ manage.py mysite/ # or main_project for my example __init__.py settings.py urls.py wsgi.py I'm only getting: - desktop/ |_ main_project/ # directory where startproject will be executed via CLI |_ main_project |_ #empty directory |_ templates/ |_ venv -
What does Import Error: Symbol not found: _PQencryptPasswordConn mean and how do I fix it?
I am trying to execute 'flask run' in the Downloads directory where my Flask_App resides. My Flask_App is 'applications.py'. When I execute 'flask run' in the development environment I am getting a URL. Once I paste the URL into Safari, I get this error. ImportError: dlopen(/Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Symbol not found: _PQencryptPasswordConn Referenced from: /Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so Expected in: /usr/lib/libpq.5.6.dylib in /Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so I am using a MacOSX High Sierra. My PostgreSQL is version 11. My python is updated to version 3.7. And pip is upgraded and psycopg is on version 2.8.3. I have tried running 'flask run' on various directories and tried moving 'applications.py' into different libraries and directories that I am currently on. I have tried using sudo but I realise that I don't know the password. In the past I force-created another admin account when I accidentally removed admin status on my admin account...don't know if this has affected sudo or not but its not accepting my current admin password. I had an issue with installing psycopg2 as well but resolved that by re-downloading PostgreSQL 11. I have successfully installed SQLAlchemy and Flask-Session as well using pip. This is my code for 'applications.py' import os from flask import Flask, session from … -
Django-taggit how to modify to have same tag added by different user
I am trying to modify django-taggit to allow the same tag to be added by separate users. I have so modified django-taggit Model so that it has user and team_id values added when user adds tag. The goal is to allow different teams to have their own separate sets of tags. Teams may edit or delete their own tags and that should not affect other teams. Question: Where in the django-taggit code does it look for duplicate tag values and then not add them but instead refer to the existing tag? `apps.py` `forms.py` `managers.py` `models.py` `utils.py` `views.py` My modified django-taggit Model code is below. from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import IntegrityError, models, router, transaction from django.utils.text import slugify from django.utils.translation import gettext, gettext_lazy as _ from django.conf import settings from crum import get_current_user try: from unidecode import unidecode except ImportError: def unidecode(tag): return tag class TagBase(models.Model): name = models.CharField(verbose_name=_("Name"), unique=True, max_length=100) slug = models.SlugField(verbose_name=_("Slug"), unique=True, max_length=100) ### MODIFIED: added team and user to model team_id = models.CharField(max_length=10, blank=False, null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.name def __gt__(self, other): return self.name.lower() > other.name.lower() def __lt__(self, other): return self.name.lower() < other.name.lower() class Meta: abstract … -
How do I store device and receive Auth token from my Django Webapp
I just started developing on xcode and I am currently trying to allow access with a user and password through to my Django Webapp. The django webapp already has an api-auth route. I am trying to find a direction to go. So far I have tried the normal /login/ route that I have with an HTTP POST. (Which I would usually do with just the webapp) I am assuming its not the same with my xcode app. def post(self, request): # TODO: User can get token even though user is not email verified # this should work for traderocket & flow track etc serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if request.current_site == user.site: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) return Response({'token': None}) This is what my route for the auth looks like. This part of the project was not worked on by myself and I am a bit new to xcode. Is it just the normal http request I have been doing? How do I store the token? I tried to find these answers but perhaps I am looking at the wrong terms/concepts. -
How to sort a result of objects shown after a search with keyword in Django
Actually i have a working code but the issue that i am facing is how to sort the result of the queryset based on multiple rule. This is my models.py : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True)` viewed_by = models.ManyToManyField(CustomUser, related_name='viewed_by', blank=True) bookmarked_by = models.ManyToManyField(CustomUser, related_name='bookmarked_by', blank=True) thumbs_up = models.ManyToManyField(CustomUser, related_name='thumbs_up', blank=True) In my views.py i have managed to queryset the database and show all the results based on all matching words, but the missing point here is that i have managed only to sort the result by the number of bookmarks. For i.e : i have this two objects : Object 1 : name = How to use django forms ? Object 2 : name = Using django forms for searching the database. With object 1 is bookmarked by 20 users and Object 2 is bookmarked by 10 users and i type in my search bar : Using django forms database In the result i have the first object as the first answer shown in the list even if the second one have much more matchs with the searched keywords. So what i want to do here is to sort the result …