Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'person_id' expected a number but got ''
i want to ask about my error , exactly the problem is that i pass a parameter myid to my method newpost , it is working good and i can print it before if request.POST.get('postsubmit') but after this if, when i print it or try to use it, it appears as blank '' i really did not understand the problem please help def newpost (request , myid ): print(myid) assert isinstance(request, HttpRequest) if request.method == 'POST' & request.POST.get('postsubmit') : print(myid) if request.POST.get('postsubmit'): print( myid) if myid not in blockedperson : print ("not blocked") savepost=post() savepost.person_id= myid savepost.content=request.POST.get('postcontent') savepost.p_date=dt.datetime.now() savepost.save() else : blocked="sorry you are blocked , you can not share posts, contact with IT to more information at 437819147@kku.edu.sa" return render (request,'home.html',{'block':blocked}) allpost=post.objects.all() allperson=person.objects.all() allstudent=student.objects.all() allteacher=teacher.objects.all() allcomp=company_rep.objects.all() return render (request,'home.html',{'posts':allpost , 'person':allperson,'student':allstudent,'teacher':allteacher,'comp':allcomp}) error is here (my id is 437819147) to be clear Performing system checks... System check identified some issues: WARNINGS: app.company_rep.comp_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.person.person_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.post.person_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.post.post_code: (fields.W122) 'max_length' is ignored when used … -
How to style Radio button in Django Forms
How can I modify these Radio Buttons? And also align them to horizontal and remove these bullet form buttons. forms.py class CustomerForm(ModelForm): gender = forms.ChoiceField(choices = Customer.GenderChoice, widget=forms.RadioSelect()) class Meta: model = Customer fields = ('first_name','last_name','address','phone','gender','email','password') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'last_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'address': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'phone': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'email': forms.EmailInput(attrs={'class': 'form-control form-control-sm'}), 'password': forms.PasswordInput(attrs={'class': 'form-control form-control-sm'}) } -
IntegrityError 1048: "Column cannot be null"
In a project I have the apps users and comments, connected via ForeignKey. If I edit a user who doesn't have a comment, I can do that without without any problem. I can even add a comment. But when I try to save/patch any User data of a User that already has a comment, I get the IntegrityError. users\models.py: class User(AbstractBaseUser): created_at = models.DateTimeField(auto_now_add=True, editable=False)) .... #nothing special here comments\models.py: class Comments(models.Model): created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) created_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_created', on_delete=models.SET_NULL) modified_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_modified', on_delete=models.SET_NULL) type = models.CharField(max_length=50, blank=True, default='') content = models.CharField(max_length=100, blank=True, default='') owner = models.ForeignKey(User, null=True, blank=True, related_name='comments', on_delete=models.SET_NULL) The Trace in the Error Message points to the line cmnt.save() in the function update in the users\serializers.py, looking like this: def update(self, instance, validated_data): info = model_meta.get_field_info(instance) #extract nested user information to handle those separately ... ... comments_data = validated_data.pop('comments', None) ... ... # update user fields # Simply set each attribute on the instance, and then save it. # Note that unlike `.create()` we don't need to treat many-to-many # relationships as being a special case. During updates we already # have an instance pk … -
Renaming the field or using the right filter with django
I accidentaly named one of the fields "type" with django. Is there a way to rename it or can I still use the filter for that 'type' I understand that 'type' is a built-in function and it tries to use it and gives me errors. class Product(models.Model): name = models.CharField(max_length=60) type = models.ForeignKey(CarType, on_delete=models.DO_NOTHING, null=True, blank=True) year_released = models.PositiveIntegerField(default=0) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) manufacturer = models.CharField(max_length=60,null=True, blank=True) def get_absolute_url(self): return reverse('product-detail', kwargs={"id": self.id}) class HydrogenView(ListView): model = Product queryset = Product.objects.filter(type='Hyrdogen') context_object_name = 'product' template_name = 'Hydrogen.html' -
Django admin lock time for wrong password
I want to set a security line in Django setting to lock the admin (superuser) if it has 3 times wrong password input. For example, for 3 hours. -
When a new model object is create, populate one of the values
I have tried this a few ways but am stuck and unsure where to go. My model (ExampleModStack) has a toadd_fk which is a foreign key obtained from a API. I want to use this to create a forign key refernce to the Toadd model when the ExampleModStack is created. I create ExampleModStack model by reading the API values so I need a funciton to do this for me. I was thinking of using signals pre_save function so that I can set the toadd relationship there. Here is my code: class ExampleModStack(models.Model): toadd_fk = models.IntegerField() toadd = models.ForeignKey( Toadd, null=True, on_delete=models.CASCADE, related_name='%(class)s_toadd' ) class Meta: verbose_name = 'example_mod_stack' verbose_name_plural = 'example_mods_stack' def __str__(self): return str(self.id) @receiver(pre_save) def referenc_product(cls, instance, **kwargs): cls.toadd = Product.objects.get(id=cls.toadd_fk) I can not get this to work though. Does anyone know a way to make this functional? -
ImageField uploads with Django Admin but not with template
I have the following form hooked to my Django Admin: # forms.py class ProfileForm(ModelForm): class Meta: model = UserProfile fields = ('name', 'profile_pic') # admin.py class ProfileAdmin(ModelAdmin): form = ProfileForm admin.site.register(UserProfile, ProfileAdmin) # models.py class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to='profile_image', null=True, blank=True) def __str__(self): return str(self.user) Now if I upload the profile_pic with Django Admin, everything works fine. However, if I submit the image through my template, it doesn't work. Here's my template: {% extends '_base.html' %} {% block content %} <form action="." enctype="multipart/form-data" id="userprofile_form" method="post" novalidate=""> <h1> Update your profile </h1> {% csrf_token %} <div> {{ form }} <button class="border-2">Update Profile</button> </form> {% endblock %} The corresponding view is this: @login_required def get_profile(request): profile = request.user.userprofile form = ProfileForm(instance=profile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'profile-edit.html', {'form':form}) In the view (inside if form.is_valid()), form.cleaned_data has value None for profile_pic. request.FILES is <MultiValueDict: {'profile_pic': [<InMemoryUploadedFile: dave_pic.png (image/png)>]}> What's wrong with my upload logic. As I said, the same works just fine with Django Admin. MEDIA_ROOT and MEDIA_URL are all set. -
How to install custom swagger in django rest framework. I want custom everything using json or yaml
I am new in Swagger Api Documentation and I searched lot of tutorial and i have read many blogs but i didn't find particular solution. I know how to implement using package drf swagger but i want to customise this for example: I want to do middle api url on top means ordering according to me and everything without change in my code. I saw swagger in node also in node one person is doing change everything means sorting, description, parameters, etc. Is it possible to do in django rest framework. -
How to access reverse relationship in django models?
I have two models one for User and another for storing CustomerInfo(user of type customer). class User(AbstractBaseUser): """ This is a class for user table which overrides functionalities of default django user model. Attributes: name (CharField): Name of a user. email (EmailField): Email address of a user. mobile (CharField): Phone number of a user. date_joined (CharField): When a user was added. last_login (CharField): Last login date time of a user. is_admin (CharField): If user is a admin or not. is_active (CharField): If user is active or not. is_staff (CharField): If user is staff or not. is_superuser (CharField): If user is a superuser or not. role (OneToOneField): One to one relationship with role table. """ name = models.CharField(max_length=80) email = models.EmailField(max_length=255, unique=True) mobile = models.CharField( validators=[ RegexValidator( regex=r"^\d{10,14}$", message="Phone number must be entered in format: '+999999999'. Up to 14 digits allowed.", ) ], max_length=15, unique=True, ) role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True) drivers = models.ManyToManyField( "self", through="DispatcherDriver", symmetrical=False ) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) USERNAME_FIELD = "mobile" REQUIRED_FIELDS = ["email", "name"] objects = UserManager() class Meta: db_table = "users" … -
why the Django admin login page throwing FieldError?
Something strange happened. I have created the custom user model. It was working properly until today. And I have no idea what has gone wrong. When I launch the admin page to login, I see below error after I click on 'login'. I use 'email' as an username FieldError at /admin/login/ Cannot resolve keyword 'username' into field. Choices are: auth_token, auth_token_set, contact, dob, email, employee_code, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions I tried to remove the migrations file and re-run the migrations, but no use. Then I deleted the App completely and configured each and everything from scratch. Yet the same error. Here is the full Error stack models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, AbstractUser from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return … -
How to deploy a Vue.js App + Django Database to Heroku?
I created a Vue.js App with a Django Database. The Vue.js App is running with router and webpack-bundle. I want to deploy that App to Heroku, so I can access it from there. When I separately deploy them to Heroku it works, but not together in one combined app. My folder structure looks like that: core/ ├─ views.py ├─ __init__.py frontend/ ├─ node_modules/ ├─ public/ │ ├─ favicon.ico │ ├─ index.html ├─ src/ │ ├─ views/ │ ├─ App.vue │ ├─ main.js │ ├─ router.js ├─ .gitignore ├─ package.json ├─ README.md ├─ vue.config.js ├─ webpack-stats.json my-app-products/ ├─ api/ ├─ admin.py ├─ apps.py ├─ models.py ├─ views.py my-app-shop/ ├─ asgi.py ├─ settings.py ├─ urls.py ├─ wsgi.py ├─ __init__.py The main problem I encounter is, that the vue app is in a subdirectory and I don't know how to deploy two apps in Heroku. If that is even possible, to deploy two apps in one project. I have knowledge on using git and on changing the heroku buildpack. Thanks in advance -
How dowload image from url to this custom ImageField(JsonField) Django
I have custom model_field in Project. I upload an excel file with data where I store links to photos(of this type https://url?token).I perform excel processing using pandas, and save data to the database via the serializer. How can I open the link and get the image to write it to this field of the model. This custom field in model_field.py class PsImageModelFieldBase(JSONField): def __init__(self, ps_image_class, **kwargs): assert issubclass(ps_image_class, BasePsImage) self.ps_image_class = ps_image_class super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args.append(self.ps_image_class) return name, path, args, kwargs def create_object(self, kwargs): if kwargs is None: return None try: if isinstance(kwargs, BasePsImage): return kwargs return self.ps_image_class(**kwargs) except TypeError: return kwargs class PsImageModelField(PsImageModelFieldBase): def get_prep_value(self, value): if value is not None and isinstance(value, (dict, list, BasePsImage)): value = self.create_object(value).as_json return super().get_prep_value(value) def from_db_value(self, value, expression, connection): return self.create_object(value) image.py import os import re from django.conf import settings from common.utils import camel_to_snake from photoservice.service import PhotoService class InvalidFormatError(Exception): pass _default_photo_service = PhotoService() def _validate_format(format_, format_regexes): is_valid = any(regex.match(format_) for regex in format_regexes) return is_valid def _validate_versions(class_name, versions, format_regexes): for fname, format_ in versions.items(): if not _validate_format(format_, format_regexes): raise InvalidFormatError(f'{class_name}: version="{fname}": "{format_}" is invalid') class PsImageMeta(type): """ Metaclass for default formats validation. """ def __new__(mcs, … -
AttributeError: module 'oauth' has no attribute 'OAuthDataStore'
I am facing this error while running the command "python3 manage.py runserver" at my system. I am using oauth module to facilitate connection between Python Oauth and Django Database. I have enclosed the library import and the Base class usage of oauth.OAuthDataStore in my class DataStore. Kindly help. -
You are trying to add a non-nullable field 'id' to useraccount without a default - django
i have this models and when i try to write python manage.py makemigrations it say You are trying to add a non-nullable field 'id' to useraccount without a default; we can't do that (the database needs somet hing to populate existing rows). my models.py : class UserAccount(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Profile_Image = models.ImageField(upload_to='images/',null=True, blank=True) slug = models.SlugField(unique=False) # new def save(self, *args, **kwargs): if not self.id or not self.slug: super(UserAccount, self).save(*args, **kwargs) self.slug = slugify(f"{self.user}") super(UserAccount, self).save(*args, **kwargs) def get_image(self): if self.Profile_Image and hasattr(self.Profile_Image, 'url'): return self.Profile_Image.url else: return '/path/to/default/image' def __str__(self): return self.name what is the error here -
Django djoser has two same urls
I'm reading about Djoser framework for Django. I found that there are two url patters to include, both of which are the same: urlpatterns = [ (...), url(r'^auth/', include('djoser.urls')), url(r'^auth/', include('djoser.urls.jwt')), ] I thought that Django always takes the first match How is it possible that the second path is picked? -
Decrypt in django by using spring boot api
I have a django project and spring project from : in spring project cipher using and in reactjs cryptojs using and in django project i am hitting api of spring boot and i am able to get data but it is in encryption format so how ? i will decrypt that data in django project please help me with proper guidance and flow -
Django creates new user every time doing sign in with apple
I implemented sign in with apple backend on Django by looking this repository's code: https://github.com/truffls/sign-in-with-apple-using-django/blob/master/backend.md. I made very little changes to the code which should not affect to any logic(like changing declaration name and etc.) It strangely re creates a new user every time an iOS app signs in with sign in with apple. I there any way to fix this? class AppleOAuth2(BaseOAuth2): """ Custom BaseOAuth2 backend class for Sign in with Apple Usage: Add this to AUTHENTICATION_BACKENDS on settings.py """ name = 'apple' ACCESS_TOKEN_URL = 'https://appleid.apple.com/auth/token' SCOPE_SEPARATOR = ',' ID_KEY = 'uid' @handle_http_errors def do_auth(self, access_token, *args, **kwargs): """ Finish the auth process once the access_token was retrieved Get the email from ID token received from apple do_auth override this method as you need to verify the code or access token given by mobile client from apple and get the ID token from which other details can be extracted. """ ## Retrieve django project stored data client_id, client_secret = self.get_key_and_secret() headers = {'content-type': "application/x-www-form-urlencoded"} data = { 'client_id' : client_id, 'client_secret': client_secret, 'code' : access_token, 'grant_type' : 'authorization_code', 'redirect_uri' : 'https://example-app.com/redirect' } ## Form data # ID Token(= from AppleID Service) res = requests.post(AppleOAuth2.ACCESS_TOKEN_URL, data = data, headers = … -
Active Directory Authentication - Django & Angular
I am currently working on a web app written with Django as the backend and Angular as the frontend. The webapp will be deployed on an enterprise network, which uses smartcard to authenticate the users with the Active Directory upon login to windows, and I want to use that authentication to automatically login users to my site and get their info, without password / registration / login page. I searched a lot about how we can integrate this smart card authentication with out app but could not find something that uses smartcards / Windows authentication, at least not that I understand that supports it. Any lead on where / what should I look for? -
Django not sending email when attachment size is near to 1 mb Error message SMTPServerDisconnected
I am able to send email with django, in normal course. But when size of attachment is more than few hundred kb, it is showing error. i am not able find the exact cause. i tried changing mysql my.conf max_allowed_packet=10M SMTPServerDisconnected at /sendemail/forfinal Server not connected Request Method: GET Request URL: http://10.0.10.106/assetlist/sendemail/forfinal?doeinput=27-Mar-2021&dofentryinput=2021-04-02 Django Version: 3.1.6 Exception Type: SMTPServerDisconnected Exception Value: Server not connected Exception Location: c:\python\lib\smtplib.py, line 357, in send Python Executable: C:\xampp\apache\bin\httpd.exe Python Version: 3.7.9 . . . . During handling of the above exception ([WinError 10054] An existing connection was forcibly closed by the remote host), another exception occurred: . . . -
Django query self referencing queryset
I have a model Thing that is self referencing. The relation copied_from is being used to save the Thing-Object that the current Thing-Object was copied from. Here is my Model: class Thing(models.Model): copied_from = models.ForeignKey("Thing", related_name="copies", null=True, default=None, on_delete=models.SET_NULL) collection = models.ForeignKey(Collection, ...) ... What I would like to achieve is to get all Things from a collection that have no been copied. I was thinking about using unionto take all Things and "substract" all things that have been copied. The issue is that in my solution I had to iterate over the Queryset where copied_from__is_null=False to get the ids of Things that have been used to create a copy. This is of course not a good solution. -
Django Djoser Token Authentication not working
TLDR: How and where do I get a user's token after logging in and pass it as a header on all subsequent restricted URLs using Django/Djoser? I'm trying to create a user login/sign up using Djoser. On the backend after logging in, I get the auth token but then when I try to access any other pages (e.g. /users/me) it says: { "detail": "Authentication credentials were not provided." } I looked online and everywhere says I need to pass the authentication token in the header but all the examples I see use Postman or curl and they just copy and paste the token into the header section. But I want to use Django to do it without knowing the token. I've seen to use token = request.META['HTTP_AUTHORIZATION'] in order to get the token but I'm not sure where to put it because all I've got is urlpatterns = [ path('', include('djoser.urls')), path('', include('djoser.urls.authtoken')), ] in my urls.py file and that's supposed to handle everything for me, so I don't have anything in my views.py or models.py And then to pass the token value as header I've seen to use the Python requests package: import requests response = requests.get('https://website.com/id', headers={'Authorization': 'access_token … -
How to use Django reset password without using User model class
I have created a custom register model and have used it for registration but now i cannot implement the Django forgot password because it uses Django User model. So is their any solution for this please help -
Terminate Django views function after x seconds
I have a function in my views.py and I want that function to run for 10 seconds after the button click if the output is produced run the whole function else terminate it and show the home page. -
Webpack tries to resolve deleted CSS file (module)
I have a React application where I want to use webpack (and babel). After having a lot of trouble doing so, I decided to clean up my program and remove my CSS files (to simplify everything). While I managed to get rid of some errors this way, I got a new one that I simply can't fix. Now I get the error message : ERROR in ./src/App.js Module not found: Error: Can't resolve './App.css' in 'C:\Users\Garbers\harvardedx\finalproject\finalproject\frontend\src' @ ./src/App.js 1:0-19 @ ./src/index.js I really don't know where the problem lies. webpack.config.js: const path = require("path"); const webpack = require("webpack"); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: "development", entry: "./src/index.js", output: { path: path.join(__dirname, "dist"), filename: "bundle.js", }, devServer: { contentBase: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: "babel-loader" }, }, ], }, optimization: { minimize: true, }, plugins:[ new HtmlWebpackPlugin({ template: './dist/index.html', filename: 'index.html', inject: 'body' }) ] }; package.json: { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@testing-library/jest-dom": "^5.11.10", "@testing-library/react": "^11.2.6", "@testing-library/user-event": "^12.8.3", "babel-loader": "^8.1.0", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "web-vitals": "^1.1.1", "webpack-dev-server": "^3.11.1" }, "scripts": { "start": "webpack --mode=development", "build": "webpack --mode=production", "dev-server": "webpack-dev-server", "test": "react-scripts … -
How to change my Heroku management command to use a worker dyno
I am new to all things Heroku/Django so apologies if this question is elementary. I've developed my first minor app using Django and have just deployed it into Heroku. A major part of the app is that I have a scraper that scrapes about 150K records and dumps the data into my Heroku Postgres database...it takes about 2.5 hours to run - ideally, I'd like this to run every other day but for now, that is another issue. As of right now I have this scraper in a management command in my project and when I want to run it I manually use: heroku run python manage.py scrape_data I inspected my logs while this was running and noticed it is using a one-off-dyno as opposed to a worker which I read was better for long-running jobs like mine. My question is, how can I change my Procfile (or something else) so that Heroku knows to use a worker dyno whenever I execute this task? If it's something I can add to the Heroku scheduler that'd be great to solve, though from what I understand those exclusively use one-off dynos so that is probably out of the question. Here's my current …