Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to make model in django. but error. why?
I'm newbie coder. I'm trying to make model. but when i make superuser, always error appear this is my code. i use abstractbaseuser and create account. my account contain username, userid, company, company_code. not use password. but i don't know how to fix this error bold from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): def create_account(self, username, userid, company, company_code, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( Name=username, UserId = userid, Company= company, Code = company_code, ) user.set_password(password) user.save(self._db) return user def create_superuser(self, username, userid, company, company_code, password): user = self.create_user( Name=username, UserId = userid, Company = company, Code = company_code, password=password, ) user.Name = True user.is_superuser = True user.is_admin = True user.is_staff = True user.save(self._db) return user class User(AbstractBaseUser): Name = models.CharField(max_length=10, unique=True) UserId = models.CharField(max_length=100, unique=True) Company = models.CharField(max_length=10) Code = models.CharField(max_length=100) Created_date = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'Name' REQUIRED_FIELDS = ['UserId', 'Company', 'Code'] def __str__(self): return self.Name def get_full_name(self): return self.Name def get_short_name(self): return self.Name @property def is_staff(self): "Is the user a member of staff?" … -
password reset error in django 3.0 and up
i am facing issue to to send email link to reset password kindly refer my code and and guide us setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mygmailid@gmail.com' EMAIL_HOST_PASSWORD = 'mygmailpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'TestG2 Team <noreply@TestG2.com>' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static # for social login from django.contrib.auth import views as auth_views urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), # here using authentication app contain views &urls we use in i.e login and logout page # and create registration folder in path('', include('django.contrib.auth.urls')), # url(r'^login/$', auth_views.login, name='login'), # url(r'^logout/$', auth_views.logout, name='logout'), path('oauth/', include('social_django.urls', namespace='social')), # path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), # path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), # path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), # path('reset_password_complete/', auth_views.PasswordResetConfirmView.as_view(), name="Password_reset_confirm"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # customizing admin text admin.site.site_header = 'ContactApp' admin.site.index_title = "Control Panel" admin.site.site_title = 'Admin Area' i have created registration folder inside i have added code for each and every page page is displaying content properly also everything is running normal but noly problem is it is not sending email to my gmail as per the configuration for reset password, please guide … -
How to change this create view to handle multiple forms in django
hey guys how to change this create view to handle and save multiple forms in django. please have a look at this code. this has 2 forms and how to connect the 2 forms while creating the post? views class CreateVideoPostView(LoginRequiredMixin, BSModalCreateView): def get(self, *args, **kwargs): form = VideoPostForm() v_form = VideoFileForm() context = { 'form':form, 'v_form':v_form, } return render(self.request, 'videos/video/create_video.html', context) def post(self, *args, **kwargs): form = VideoPostForm(self.request.POST or None) v_form = VideoFileForm(self.request.POST or None, self.request.FILES or None) if form.is_valid() and v_form.is_valid(): videopost = form.save(commit=False) videofile = VideoFile(videopost=videopost) videopost.user = self.request.user videopost.save() videofile.save() form.save_m2m() return redirect('videos:my_video_home') else: raise ValidationError('Check all the formfields') forms class VideoFileForm(forms.ModelForm): class Meta: model = VideoFile fields = ['video',] class VideoPostForm(forms.ModelForm): class Meta: model = VideoPost fields = ['title', 'tags',] -
What type of Authentication System does Django use out of the box?
What type of Authentication System does Django use out of the box? Looks to me like Session Based Authentication? -
Deployed Django - project static files css only working for some
I have a question regarding Django's handling of static files. I deployed a Django project on Heroku and use following Procfile web: python3 manage.py collectstatic --noinput; gunicorn testapp.wsgi --log-file - I have a list of different css files which all worked for one html template (applies the style changes). Now I added a second html template which uses the same css files. However, for this file only some css files are discovered while others are completely ignored. For example (one working while the other doesn't) href="/static/css/sidesection.dd3c29e22478.css" --> applies the style changes href="/static/css/checker.5ffe0baa6d94.css" --> does not apply the style changes Does someone have experience regarding this matter and could eventually also provide an explanation? This issue is not the more common issue where the static files do not load at all. It loads all of them for one html but not all for another. -
how to integrate Stripe in my web app without creating products on Stripe dashboard
I have a web app (Angular 8, Django 3) that allows one set of users to create products with whatever price they seem fit. And a second set of users that is going to load these products into the cart and purchase them. All I want Stripe to do is process the card payment for a certain amount (determined by my backend/server side). On the Stripe website it says I have to create products and prices in the "Accepting One Time Payment" section (https://stripe.com/docs/payments/checkout/accept-a-payment). I dont want to do this. I just want to process a payment for an amount that I determine. From the Stripe documentation it says to create a checkout session: const stripe = require('stripe')('sk_test_UO9wbdk2YOZaQK9dDubCYwSO00RIV3STO8'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [{ price: '{{PRICE_ID}}', quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', }); Could i just change the line_items object to have a price that is what I determined on my server and a quantity of 1 to get around this? -
Changing image in django user change form
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed. This is my USER CREATION FORM: class SignUpForm(UserCreationForm): photo = forms.ImageField(required=False) bio = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'})) designation = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'})) university = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'})) company_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"})) grad_year = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'})) phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'})) address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'})) city = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'})) company_category = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's category"})) company_desc = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"})) company_site = forms.CharField() no_employees = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'})) technologies = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'})) markets = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'})) linkedin = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'})) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) del self.fields['password2'] for fieldname in ['password1']: self.fields[fieldname].help_text = None self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'}) self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'}) self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'}) self.fields['company_site'].widget.attrs.update({'placeholder': "Enter … -
Django - VueJS - Can't be null
i work on a project with Django and VueJs. I have a problem with a field can't be null but i don't understand why. models.py from django.db import models from django.conf import settings class Tache(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) echeance = models.DateTimeField(null=True, blank=True) titre = models.CharField(max_length=240) sous_titre = models.CharField(max_length=240, null=True, blank=True) content = models.CharField(max_length=240) fait = models.BooleanField(default=False) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="taches") def __str__(self): return self.content serializers.py from rest_framework import serializers from taches.models import Tache class TacheSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField(read_only=True) # echeance = serializers.SerializerMethodField() echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S") slug = serializers.SlugField(read_only=True) class Meta: model = Tache exclude = ["updated_at"] def get_created_at(self, instance): return instance.created_at.strftime("%d" + "/" + "%m" + "/" + "%Y") # def get_echeance(self, instance): # if instance.echeance != None: # return instance.echeance.strftime("%Y-%m-%dT%H:%M:%S") My problem "field can't be null are on "echeance" field. You can see i have 4 lines in comments because => don't work so i do that : echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S") I think my problem come here... Do you have any idea why "echeance" can't be null...? Thank's -
I have a problem with the django authenticate function
When I input the same username and password as in the database it shows "invalid credentials" instead of "Success". def login(request): if request.method == 'POST': username = request.POST.get('user') password1 = request.POST.get('password1') a = authenticate( username=username, password=password1) if a is not None: return HttpResponse("Success") else: return HttpResponse("Invalid Credentials") return render(request, 'login.html') -
Confusion while using the django-celery-beat to perform some task periodically?
I am learning how to implement celery in django. I want to use the custom scheduler classes to schedule the task from the database so I used the django-celery-beat. But for this I am not using schedular from the database just to check whether it works or not since it is my first time with celery. I placed the celery.py , init.py , tasks.py files as in the django-celery-beat documentation. But I got no idea how to write the tasks and the views. For example I want to create task object in the database every 1 minute so I wrote the views for this with some django logic and I implemented scheduler like this but it is not working. In the console it is throwing this error. celery.beat.SchedulingError: Couldn't apply scheduled task run_every_1_minutes: add_task() missing 1 required positional argument: 'request' What would be the right approach in this example i.e. to create the task object every 1 minute ?How can I write views.py and tasks.py file for this? celery.py inside settings directory from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_demo.settings') … -
Get the length of messages storage Django
I am using messages framework of django (https://docs.djangoproject.com/en/3.0/ref/contrib/messages/) When a user register, i do some check and add messages error to my storage : messages.error(request, gettext("username_already_exists")) In my code i would like to know the length of messages.error, like that i can check if there is error or not in my form. I tried this : if len(messages.error) <= 0: User.objects.create_user( username, email, password, ) But i can't because message 'object of type 'module' has no len()' Do you know a way to check if there is messages errors stored in the messages Framework please ? Thank you ! -
Convert Sql query (Many to Many) to Django ORM query
Please let me know, Is it possible to convert the following query to Django query (Without using raw). SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined", "chat_roomdetails_participants"."user_id", "chat_roomdetails_participants"."id", "chat_roomdetails_participants"."roomdetails_id" FROM "auth_user" LEFT JOIN "chat_roomdetails_participants" ON ("chat_roomdetails_participants"."user_id" = "auth_user"."id") INNER JOIN "chat_roomdetails" ON ("chat_roomdetails"."id" = "chat_roomdetails_participants"."roomdetails_id") INNER JOIN "chat_roomdetails_participants" AS ROOM ON (ROOM."roomdetails_id" = "chat_roomdetails"."id" AND ROOM."user_id" = {LOGIN_USER_ID}) WHERE "auth_user"."is_superuser" = false GROUP BY ("auth_user"."id"); Here is my RoomDetails model: class RoomDetails(models.Model): room = models.CharField(max_length=8, unique=True, null=False, blank=False, verbose_name="Room unique name (Randomly generate)") room_name = models.CharField(max_length=50, blank=False, null=False) room_type = models.IntegerField(choices=RoomType, default=RoomType[0][0]) participants = models.ManyToManyField(settings.AUTH_USER_MODEL) is_active = models.BooleanField(default=True, verbose_name="Is room Active") created = models.DateTimeField(auto_now_add=True) Requirement: After login, the User can see all the user(Except superuser) with roomdetails (Contain only logged In User's belonging roomdertails, Not all roomdertails). The relation between RoomDetails and User has many-to-many. -
How to show a form and assign values to database in a class based detail view
I have two models.Article model and Comment model.I use detail view for a particular article details.I want to add comments on that detail classBased view using form_class.But I can not assign foreign key instance.It gives Comment.post" must be a "Article" instance error. class Article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) details = RichTextUploadingField() #details = RichTextField() title_image = models.ImageField(default='default_title.jpg', upload_to='Article_heading_pics') publish_date = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User,related_name="likes", blank=True) def __str__(self): return self.user.username def total_likes(self): return self.likes.count() class Meta: ordering = ['-publish_date'] COMMENT MODEL class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Article, on_delete=models.CASCADE) cmnt = models.CharField(max_length=400) cmnt_date = models.DateTimeField(auto_now=True) def __str__(self): return '{}--{}'.format(self.post.title, str(self.user.username)) class Meta: ordering = ['-cmnt_date'] Detail view class ArticleDetailView(ModelFormMixin,DetailView): context_object_name = 'article_detail' model = models.Article template_name = 'blogs/detail.html' form_class = CommentForm def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) comments = Comment.objects.filter(post=self.kwargs['pk']) total_cmnt = comments.count() context['comments'] = comments context['total_cmnt'] = total_cmnt context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): cmnt = self.request.POST.get('cmnt') comment = Comment.objects.create(post=self.kwargs['pk'],user=request.user,cmnt=cmnt) comment.save() messages.success(request, 'your cmnt is posted successfully') return HttpResponseRedirect(reverse('blogs:detail', args=[self.kwargs['pk']])) It gives Comment.post" must be a "Article" instance error. -
How to test django app without giving an app_name
My project structure looks like this: backend/src/apps/app_name/tests/foo.py and when I'm trying to run the tests by entering a command python manage.py test it runs 0 tests. The only correct way to test is python manage.py test src.apps.app_name but I'm to lazy to do it with every app. 😄 -
Login Required decorator not redirecting to login url | Django
@login_required decorator not redirecting me to logging page When I click the add to cart button it doesn't redirect me to the login page. It just doesn't do anything. I tried the login required decorator in another function. Like the home view action. And when I try to access the home page it directly redirects me to the login page. But in the combo_add_to_cart it doesn't seems to work. But I have found something in the terminal. I have seen that when I click the add to cart button it first sends a post request of "POST /carts/cart/combo/add-to-cart/ " then it sends a get request "GET /accounts/login/?next=/carts/cart/combo/add-to-cart/". accounts views.py class Login(FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") return super(Login, self).form_invalid(form) cart views.py @login_required(login_url='/accounts/login/') def combo_add_to_cart(request): combo_id = request.POST.get('combo_id') if combo_id is not None: try: combo_obj = Combo.objects.get(id=combo_id) except Combo.DoesNotExist: return("carts:cart") combo = combo_obj cart_item, created = ComboCartItem.objects.get_or_create( combo=combo, user=request.user, ordered=False ) cart_obj, … -
How to create a custom queryset from a json file
Is it somehow possible to create a custom queryset from a given json file? I have the json file and I want the queryset in order to use the queryset for presentation with django_tables2 and filtering with django_filters. The key point is that I do not have any model and I do not want to create a model with the data from json. I just want to create the queryset. existence = 1 try: offer_request = requests.get(url, headers=headers) existence = 2 except: print("nothing") if existence == 2: offers=json.loads(offer_request.text) The offers variable contains my json. -
Angular loading files from backend using the wrong port
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path. Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile. I use proxy to get backend api: { "/api": { "target": "http://localhost:8000", "secure": false } } I do not know where the problem may be. -
django allauth custom signup form not rendering
Background I have two types of users, buyers & sellers, mapped to an extended AbstractUser via a OneToOneField. I want to request different information from them upon sign up, so I extended the allauth SignupForm as described in this helpful post. I have two routes, accounts/signup/user and accounts/signup/seller, which links to the BuyerSignupView and SellerSignupView respectively. The two views extend the allauth SignupView but instead renders custom templates that use my custom forms. Problem The forms aren't rendering at all on the webpage. Clicking inspect on the web shows no html tags related to the form, but calling form.as_p() in the python shell correctly converts my form to its corresponding html components. # view.py class UserSignupView(SignupView): template_name = "accounts/user_signup.html" form_class = UserSignupForm class SellerSignupView(SignupView): template_name = "accounts/seller_signup.html" form_class = SellerSignupForm # forms.py class UserSignupForm(SignupForm): GENDER_CHOICES = [("F", "Female"), ("M", "Male"), ("O", "Other")] AGE_CHOICES = [ ("A", "18-"), ("B", "18-25"), ("C", "25-35"), ("D", "35-45"), ("E", "45+"), ] first_name = forms.CharField(max_length=30, label="First Name") last_name = forms.CharField(max_length=30, label="Last Name") gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False, label="Gender") age = forms.ChoiceField(choices=AGE_CHOICES, required=False, label="Age") phonenumber = PhoneNumberField() def signup(self, request, user): user.first_name = self.cleaned_data["first_name"] user.last_name = self.cleaned_data["last_name"] user.save() new_profile = Profile( user=user, # TODO - add followed_tags = … -
How to run a python script in django server using a button
I want to run my script (makes changes to my database and creates users on another website using an API) whenever a user presses the button on my website. So far i have tried these solutions but they are not working for me. How can i trigger a Python script in background from HTML tag button, in Django? Run python script in Django website when clicking on button submit -
Revealing form fields after checkbox is checked django
Im trying to create a form in which, when a user checks the box, the form shows more values to input. For example, I have the following class ExampleForm(forms.Form): example_name = forms.charField(label='Name here') custom_message_check = forms.booleanField(required=False, initial=False) custom_message = forms.charField(label='Custom message here') Is it there a way to make custom_message field appear only when custom_message_check is activate? I read django docs and didnt find a widget for this, can this be done with django or do I need to create a custom html form? -
How to clear ordering when using .first() in django
I have a query in database as follows. Whenever I try to do a .first() on the query, The equivalent query that gets run in the database is as follows SELECT * FROM “user" WHERE UPPER("user"."email"::text) = UPPER(%s) ORDER BY "registration_user"."id" ASC LIMIT 1 I want to get rid of the order by clause as it interferes with indexes being applied correctly in the db and is also a costly operation. How can I refactor the code below? users = User.objects.filter(email__iexact=email) users.query.**clear_ordering**(True) if users.count() > 0 : return users.first() -
I want to upload multiple files using Django
I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light . I have created my html form like this <input type="file" name="file" multiple /> I have created a model like this File=models.FileField(upload_to="documents/") And views.py like this file=request.FILES.get('file') I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ? And even want to show in Django Admin Panel -
Deploy Django App serverless on GCP cloud functions
I have come across serverless deployment of Django apps on AWS Lambda. Here is one such example source: Is a similar thing possible using GCP cloud functions? -
Temporary database model in django
I want this Temporary models in django to be implimented in django 3.0. -
Django error, CSRF Failed: CSRF token missing or incorrect
I have Backend = Django+Django Rest+Djoser(Token based user auth app) Fontend = React JS + Axios. In Local Host/Development I could do user login and authentication using token. It did'nt give error in Postman too. In production mode It gives error as CSRF failed. Why is so ? I think CSRF token only needed in session authentication. I tried removing session auth but resulted in server crash REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), .... } middlewares MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'shop', 'corsheaders', 'frontend', 'djoser', 'rest_framework.authtoken', 'users' ]