Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to fix 'The included URLconf 'gp.urls' does not appear to have any patterns in it'
when i tried to write the first urlpattern and the first view, i got this error, so i can be able to access to the authentification template, i have no idea what can be the source of this error # my gp/utls.py from django.contrib import admin from django.conf.urls import url from . import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.index, name='index'), ] # my views.py from django.shortcuts import render def index(request): return render(request,'gp/index.html') when i try to run the server this is the error i get raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'gp.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. -
Plesk Django .py files showing in browser. How do I make it safe?
I create some django websites using Plesk Onyx. My problem is If I go to domainname.com/appname/settings.py or domainname.com/manage.py url i see everything in ".py" file. My folder permissions 755, file permissions is 644. The problem is solved when I set the file permissions to 640 or 600. Is there a shortcut in django related to this vulnerability? or do I need to change individual file permissions? I'm looking for an easy way. I don't know, maybe by adding a little code in django I can prevent these files from appearing. Im using python 3.6 - Django 2.2.3 - Plesk Onyx - Nginx -
Comparing request.path to a string in Django template
I've been messing around with Django for a bit and I ran into this issue, where the comparison in the if labeled below, returns false, when they're both the same string. If request.path is /test/ then "/{{values|lower}}/" is also /test/ yet they're not equal. Why is this the case? <form class="btn-group btn-group-sm btn-group-toggle btn-block" action="" method="POST"> {% for i in name %} {% csrf_token %} {{ form.as_p }} <input {% cycle name.0 name.1 name.2 name.3 name.4 as values %} // HERE {% if press == values or request.path == "/{{values|lower}}/" %} class="btn btn-outline-dark btn-block m-2 active" {% else %} class="btn btn-outline-dark btn-block m-2" {% endif %} type="Submit" name="{{values}}" value="{{values}}"/> // THESE TWO LINES PRINT THE STRINGS ON PAGE {{request.path}} /{{values|lower}}/ {% endfor %} </form> -
Make some elements of choice array readonly in Django?
I have a model: class myLimit(models.Model): limit = models.PositiveSmallIntegerField(help_text="The upper limit of the number of points that can be used.") TYPES_OF_LIMITS = [('perday','Limit Per Day'),('lifetime', 'Lifetime Limit'),('peruser', 'Per User'),] limit_type = models.CharField(choices=TYPES_OF_LIMITS, max_length=20, default='lifetime') ... I want to know how to disable (or make it read-only) the "peruser" ("Per User") choice/option. The current myLimit acts as a base model for an extended model which sets the default of limit_type to "peruser" and makes the entire thing read-only my using admin model's exclude = ('limit_type',). I set the default in the save() method of the extended model just before calling the super method. The main question remains: How to make a few choices read-only? I have read tutorials on making the entire field read-only, hiding it, and others but haven't figured out a way to make "only some choices" read-only. -
Always getting {"detail":"Unsupported media type \"application/json\" in request."} error when I try to post data on postman
I am working on a project that requires me to upload an image. However when I am trying to upload one and posting I ma getting the above error. I have no clue what to do anymore. I have already tried using FileUploadParser and creating class Base64ImageField too. Please Help. models class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) avatar = models.ImageField(upload_to='', blank=True, null=True) code = models.CharField(max_length=8, unique=True, default=unique_rand) emailVerified = models.NullBooleanField(null=True, default=None) facebookId = models.CharField( null=True,unique=True, default=None,max_length=255) googleId = models.CharField(null=True,unique=True,default=None,max_length=255) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') mobile = models.CharField(validators=[phone_regex, MinLengthValidator(10)], max_length=10, null=True, default=None) mobileVerified = models.NullBooleanField(null=True,default=None) status = models.BooleanField(default=False) serializers class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() avatar = Base64ImageField(required=False) code = serializers.CharField(read_only=True) serializers.FileField(use_url=False) class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) image = validated_data.pop('avatar') upr=UserProfile.objects.create(user=user,image=image,**validated_data) return upr views class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer user_serializer = UserSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser) def pre_save(self, request): request.avatar = self.request.FILES.get('file') def post(self, request): print(request.data) serializer= UserProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)