Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying model field data in template/views without get_object_or_404()
Homefeed is the page where i query all the blogposts In this project, any user that sees a blogpost that they are interest in can submit their interest to the post. 1 user can only submit 1 interest to that blogpost, but they can submit as many interest as they want to different blogposts. Right now in my home.html, I am trying to make it such that if YOU have submitted interest,(aka your interest status is at pending or accept or decline) for that particular blog post, you will see the view interest button instead of the submit interest button. But I am facing a problem because in my views, I am querying for blog_posts = BlogPost.objects.all() and not blog_post = get_object_or_404(BlogPost, slug=slug). As such, how am I able to query whether or not for the particular blogpost, the user has already submitted an interest in my template to determine which button should show in my home.html? Thanks, and also I dont want to change the url at all :) views.py def home_feed_view(request, *args, **kwargs): context = {} blog_posts = BlogPost.objects.all() context['blog_posts'] = blog_posts page = pageFilter(request.GET, queryset=BlogPost.objects.exclude(author_id=request.user.id).order_by('date_updated')) context['page'] = page paginated_page = Paginator(page.qs, 4) page = request.GET.get('page') page_obj = … -
how can i open a modal from views.py in django? Is there any way?
I have a django application. when a user clicks the submit button two modals should be shown one after another each has to do different functions in views.py in my django app. I am trying to write the code but the problem is not easy and I have looked everywhere and couldn't get the answer. I have to write the code in the following way: views.py def submit(request): #first modal should pop up which has two options. #secound modal should pop up which also has a two options. and when the user clicks any of the buttons each should also call the different function in views.py. html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button class="btn btn-danger custom" style="position:absolute; left:800px; top:180px;" type="submit">Update the data</button> # user clicks a button in form and modal should pop up # then 2 modals should pop up # the first modal has two buttons # when user clicks the update button the function in the views should be called and also 2nd modal should pop up <!--modal 1--> <div aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade" id="UpdateModal" role="dialog" tabindex="-1"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update Changes</h5> <button aria-label="Close" class="close" data-dismiss="modal" … -
is it possible to create the link of selenium file and insert jquery?
I have created a Python Selenium script in Django framework. I want to manage the link of my selenium project. So that whenever I hit the link in a browser, it should run testing. I don't want to run it from the terminal, as I want to add jquery. here is my code driver = webdriver.Chrome(executable_path='/home/sr/PycharmProjects/selenium/automation/KPTGR/chromedriver') driver.get("https://www.google.com/") get = driver.find_element_by_id("gsr") print(get.text) -
How to short down this code to create django model so it works the same in term of functionality
Just imagine Netflix Site, I want to store video links of multiple seasons of TV shows with multiple episodes, I want to increment number of seasons and episode of a certain tv show on the need specifically from admin area. I don't know ho to do that instead of just creating variable of every episode link and season model. Please Help ! Thanx in adv class Tv_Shows(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() episode1 = models.CharField(max_length=100, null=True) episode2 = models.CharField(max_length=100, null=True) episode3 = models.CharField(max_length=100, null=True) episode4 = models.CharField(max_length=100, null=True) episode5 = models.CharField(max_length=100, null=True) episode6 = models.CharField(max_length=100, null=True) episode7 = models.CharField(max_length=100, null=True) episode8 = models.CharField(max_length=100, null=True) episode9 = models.CharField(max_length=100, null=True) episode10 = models.CharField(max_length=100, null=True) imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views = models.IntegerField(default=0) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() -
How to set up a homepage at django
I am new to django and I want to set my homepage url My homepage is 127.0.0.1:8000/home but I want my homepage at 127.0.0.1:8000/ or I want my django start as 127.0.0.1:8000/home as default. How do I do it? -
unable to upload multi files through django serializer
I can upload single files at a time but cant upload multiple files at once. Any idea how can I upload multifiles ? my models.py class VideoPost(models.Model): user = models.ForeignKey("profiles.HNUsers", on_delete=models.DO_NOTHING) video = models.FileField("Post Video", blank=True, null=True) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) text = models.TextField("Description text", blank=True) class Meta: verbose_name_plural = "VIdeo Posts" my serializers.py class VideoPostSerializer(serializers.ModelSerializer): class Meta: model = VideoPost fields = ( 'user', 'text', 'video', ) and my views.py def video_post(request): if request.method == 'POST': data = request.data print(data) serializer = VideoPostSerializer(data=data , many =True) if serializer.is_valid(): serializer.save() print("audio object saved") try: video_post_object = VideoPost.objects.filter(user__id=data['user']).order_by('-timestamp')[0] print(video_post_object) try: post = Posts() #testing multi files post.user = HNUsers.objects.get(id=data['user']) post.audio_url = video_post_object.video.url post.type = 'V' post.category = data['category'] post.created_on = video_post_object.timestamp post.text = video_post_object.text save_post = post.save() post_id = post.pk try: user = HNUsers.objects.get(pk=data['user']) if user.user_type == 'HN': payload = { "user_name": user.full_name, "image_url": user.profile_img_url, "post_id": post_id, "notification_type": "hn" } print(payload) broadcast_notification('all', payload, 1) except HNUsers.DoesNotExist: print("user_id_does_not_exist") print("post object created") except Posts.DoesNotExist: print("Failed - post creation failed") except HNUsers.DoesNotExist: print("Failed - user object not found") except AudioPost.DoesNotExist: print("Failed - video object not found") return Response(serializer.data, status=status.HTTP_200_OK) -
Celery: Sending email using the Celery throws "Invalid address" error
I am using Django + Celery to send emails. I am basically new to Celery. Whenever I try to send emails using the tasks.py file it shows me following error on console. backends/smtp.py", line 122, in _send recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] **File "/home/ropali/Development/PythonWorkSpace/hrms_venv/lib/python3.9/site-packages/django/core/mail/**backends/smtp.py", line 122, in recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] File "/home/ropali/Development/PythonWorkSpace/hrms_venv/lib/python3.9/site-packages/django/core/mail/message.py", line 84, in sanitize_address raise ValueError('Invalid address "%s"' % addr)ValueError: Invalid address "['test2@test.com']" My tasks.py file import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task from hrms.services import EmailService from django.conf import settings @shared_task def send_marketing_email(email, subject): email_service = EmailService(subject=subject, to=email) # email_service.set_to(email) email_service.load_template('templates/marketing_email.html',context={ 'url': settings.BASE_URL + 'pages/contact-us' }) email_service.send() return 'Email sent to {}'.format(email) My view code: class SendEmailsView(LoginRequiredMixin, AdminRequired,View): template_name = 'marketing/send_emails.html' context = {} def get(self, request): return render(request, self.template_name, self.context) def post(self, request): subject = request.POST.get('subject') if not subject: return JsonResponseBuilder.error('Subject field is required.',HTTPStatus.UNPROCESSABLE_ENTITY.value) # get all the names & emails from the uploaded excel file # send the email to each email address from the file email_df = pd.read_csv(settings.MEDIA_ROOT / constants.EMAIL_LEADS_EXCEL_FILE) for index,row in email_df.iterrows(): send_marketing_email.delay(row['email'], subject) return JsonResponseBuilder.success('Emails sent successfully...') services.py file which contains EmailService class. class EmailService(): email … -
Add Django Rest Framework route to third party urls
I am using Djoser along with Django REST Framework. This is my urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter djoser_urls = [ path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.authtoken")), ] urlpatterns = router.urls + djoser_urls When using the browsable API at localhost:8000/auth/ the djoser urls are available. So that is all working correctly. What I need is to be able to browse to localhost:8000/ and have the above route displayed as an option to click on. Currently there are no routes displayed in the browsable API at localhost:8000/ even though if I manually type localhost:8000/auth/ into the url then I am taken to the djoser urls. In other words, when opening the browsable API at localhost:8000/, I would like the following to be available to click on: { "auth": "http://localhost:8000/auth/" } -
What is the reason for Django- Page not found /login error
I am working on a Django project,upon running the application with python3 manage.py runserver. I am able to get the login page,after logging in,I should be able to see the home/index page however I get an error something like Request Method: POST Request URL: http://127.0.0.1:8000/login Using the URLconf defined in leadgen.urls, Django tried these URL patterns, in this order: index [name='index_view'] [name='login_view'] add [name='add_view'] base [name='base_view'] company [name='company_view'] insigths [name='insights_view'] master [name='master_view'] leads [name='leads_view'] settings [name='settings_view'] team [name='team_view'] admin/ The current path, login, didn't match any of these.``` Leadgen is my project and Leadgen_app is its application. This is how I have written the urls.py for the application leadgen_app/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.login_view, name='login_view'), path('index', views.index_view, name='index_view'), path('add', views.add_view, name='add_view'), path('base', views.base_view, name='base_view'), path('company', views.company_view, name='company_view'), path('insigths', views.enrich_view, name='insights_view'), path('master', views.master_view, name='master_view'), path('leads', views.leads_view, name='leads_view'), path('settings', views.settings_view, name='settings_view'), path('team', views.team_view, name='team_view'), ] and this is how I have written the urls for leadgen project from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('leadgen_app.urls')), path('admin/', admin.site.urls), ]``` How do I solve this error? Please help. -
Call a view from from in django
I want to call a view from my html template using forms but when i click on update button nothing happens. I cant seem to find out the error. Codes are as follows HTML TEMPLATE <form action = {% url 'update' %} method = "POST"> {% csrf_token %} <h6 class="heading-small text-muted mb-4">User information</h6> <div class="pl-lg-4"> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label class="form-control-label" for="input-username">Company ID</label> <input type="text" name="id" disabled="disabled" id="input-username" class="form-control form-control-alternative" value="{{ data.id }}"> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label class="form-control-label" for="input-email">Email address</label> <input type="email" name="email" id="input-email" class="form-control form-control-alternative" value="{{ data.email }}"> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label class="form-control-label" for="input-first-name">Company Name</label> <input type="text" name="name" id="input-first-name" class="form-control form-control-alternative" value="{{ data.name }}"> </div> </div> </div> </div> <hr class="my-4" /> <!-- Address --> <h6 class="heading-small text-muted mb-4">Contact information</h6> <div class="pl-lg-4"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="form-control-label" for="input-address">Address</label> <input id="input-address" name="add" class="form-control form-control-alternative" placeholder="Home Address" value="{{ hno }}" type="text"> </div> </div> </div> <div class="row"> <div class="col-lg-4"> <div class="form-group"> <label class="form-control-label" for="input-city">City</label> <input type="text" name="city" id="input-city" class="form-control form-control-alternative" placeholder="City" value="{{ city }}"> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label class="form-control-label" for="input-country">Country</label> <input type="text" name="country" id="input-country" class="form-control form-control-alternative" placeholder="Country" value="{{ country }}"> </div> </div> <div class="col-lg-4"> <div class="form-group"> … -
ModelBase object argument after ** must be a mapping, not list
I have been working on certain endpoint on Rest Framework I came to following problem. ModelBase object argument after ** must be a mapping, not list In my usecase.py file I have following line of code. class AddRouteRepresentativeWithBusCompanyRouteUseCase(BaseUseCase): def __init__(self, bus_company_route: BusCompanyRoute, serializer ): self._bus_company_route = bus_company_route self._serializer = serializer self._data = self._serializer.validated_data.get('data') def execute(self): self._factory() def _factory(self): print(self._data) route_representative = RouteRepresentative( **self._data, bus_company_route=self._bus_company_route, ) try: route_representative.full_clean() except DjangoValidationError as e: raise ValidationError(e.message_dict) RouteRepresentative.objects.bulk_create(route_representative) Seems I am getting error on **self._data. as I got orderedDict from serializer fields. What should I do in **self.data instead? TIA -
How to get subcategory with their category in django models and showing in templates
I want to present my skill category with their subcategories list. I am facing issue while fetching the data from models to views. my code is given below: model.py Here I create 2 classes SkillCategory and SkillSubCategory class SkillCategory(models.Model): id = models.AutoField(primary_key=True) category = models.CharField(max_length=100) def __str__(self): return self.category class SkillSubCategory(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(SkillCategory, on_delete=models.CASCADE) subcategory = models.CharField(max_length=100) icon_name = models.CharField(max_length=100) def __str__(self): return self.subcategory views.py Here I define a function based view named as skill which return list of list def skill(request): allsubcat = [] skillcat = SkillSubCategory.objects.values() cat = {c['subcategory'] for c in skillcat} for c in cat: skill = SkillSubCategory.objects.filter(subcategory=c) allsubcat.append([skill]) ctx = {'allsubcat':allsubcat} return render(request, "my_folio/skill.html", ctx) skill.html This is the template which should present the Skill like: Skill Category 1 Skill SubCat 1 Skill SubCat 2 Skill Category 2 Skill SubCat 1 Skill SubCat 2 Skill SubCat 3 Could anyone please help me for the given issue. Thanks and cheers!! -
Django Admin does not work after deployment Heroku
After deploying my application the admin of the website does not work. I am able to use the website, create an account and do all the crud, but the admin does not work. 1 - I created the superuser with python manage.py createsuperuser 2 - I deployed and tried to access the admin https://djangotodowoo.herokuapp.com/admin Although, every time that I try to access this page it redirects to: https://djangotodowoo.herokuapp.com/admin/login/?next=/admin/ I am not sure if that's the problem, but it's a hint at least. This is happening because I have on my settings.py the following line LOGIN_URL = '/login' That checks if someone is trying to access a page without login and redirects to the login page. I am not sure what the problem actually is, any ideas on how to solve the issue? Thank you very much folks! -
Run R script in Django
I'm building a site which contains lot of optimization work and all those work are done in R language. I'm building whole site on Django. Is there any way I can connect both R code and Django or what should I do here ? I tried installing rpy2 which works fine in python but in Django I'm getting a error: File "F:\django-app\restapi\views.py", line 25, in <module> import rpy2.robjects as robjects File "F:\django-app\venv\lib\site-packages\rpy2\robjects\__init__.py", line 19, in <module> from rpy2.robjects.robject import RObjectMixin, RObject File "F:\django-app\venv\lib\site-packages\rpy2\robjects\robject.py", line 6, in <module> rpy2.rinterface.initr() File "F:\django-app\venv\lib\site-packages\rpy2\rinterface\__init__.py", line 208, in initr initr(r_preservehash=r_preservehash) RuntimeError: R_USER not defined. what's the best option to do this. Is there any thing I'm missing here? -
Why can't I remove the member from the list and delete their interest?
Every blogpost has their own members. To become a member, the interest you submit must be accepted. i am trying to build a remove member function whereby if you are a member, you can remove yourself from the list and if you are the blog_post.author, you can remove ANYONE except yourself (because to remove yourself you need to delete the blogpost entirely. Once you are removed from the member-list, I also want the initial interest they have submitted to be deleted. I have attached my models.py, urls.py, template.html and views.py in this question. First, i am getting no errors, but I'm unsure of why the interest is not deleted and the member is also not removed. Is there anything wrong with my code? models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") class Interest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) class InterestInvite(models.Model): ACCEPT = "ACCEPT" DECLINE = "DECLINE" PENDING = "PENDING" STATUS_CHOICES = [ (ACCEPT, "accept"), (DECLINE, "decline"), (PENDING, "pending"), ] interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite") status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) views.py class InterestMixin(object): … -
Can´t excecute view action in Django
I would like to understand why when I click on login button I can't run user_login function. I'm new in django. Thanks urls.py: from django.urls import path from iol_dash import views urlpatterns = [ path('', views.index, name='index'), ] views.py: from django.shortcuts import render from iol import Service def index(request): return render(request, 'index.html', {}) def user_login(request): username = request.POST.get('username') password = request.POST.get('password') service = Service() token = service.get_token( username=username, password=password ) print(token) index.html: <form class="modal-content animate" method="post" action={{ views.user_login }}> {% csrf_token %} {{ form.as_p }} <div class="imgcontainer"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span> </div> <div class="container"> <label for="username"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="username" required> <label for="password"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <button type="submit">Login</button> </div> </form> -
How can I pass in url arguments to an APIRequestFactory put request?
I have been trying for hours but cannot figure out how to pass a url argument through an APIRequestFactory put request. I have tried it through Postman when running my server and the url variable is passed just fine, but when I run it in my tests it stops working. What I mean is that when I send a Postman PUT request to '/litter/1/' it will successfully take in the 1 as the variable litterId since my url is setup like this path('litter/', include('apps.litter.urls')), and path('<int:litterId>/', LitterView.as_view(), name='litter-with-id') But when I try and send an APIRequestFactory put request to that same url, for some reason the 1 will not go through as the litterId anymore. Some relevant pieces of code... My top level url.py from rest_framework.authtoken import views from apps.litter.views import LitterView urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('apps.my_auth.urls')), path('litter/', include('apps.litter.urls')), ] This is my app specific urls.py from .views import LitterView urlpatterns = [ path('', LitterView.as_view(), name='standard-litter'), path('<int:litterId>/', LitterView.as_view(), name='litter-with-id'), ] Here is my views.py import json from django.contrib.auth.models import User from django.db import IntegrityError from django.views.decorators.csrf import csrf_exempt from rest_framework import authentication, permissions from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response import … -
Django Deployment - No web processes
I created an application using Django 3.1.5 and for some reason, it does not deploy correctly. I will share what I did and have it. I have set up my Procfile and I have my requirements.txt, I did the deployment as I told on the website, but I am still getting an error. computer setting image and Procfile On my settings.py I have this: # on the top of the file import django_heroku # on the bottom of the file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_DIRS = [ os.path.join(BASE_DIR, 'todo/static') ] LOGIN_URL = '/login' # Activate Django-Heroku. django_heroku.settings(locals()) Procfile web: gunicorn todowoo.wsgi After I finish the deployment I get this error Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. heroku logs --tail for details Here are the details: 2021-01-27T03:16:07.704192+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=djangotodowoo.herokuapp.com request_id=babd8359-3dfe-4df9-8ce6-5243de91b159 fwd="66.31.116.154" dyno= connect= service= status=503 bytes= protocol=https 2021-01-27T03:16:07.912002+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=djangotodowoo.herokuapp.com request_id=4114d73f-f15f-4d35-9c1b-e25225a36bde fwd="66.31.116.154" dyno= connect= service= status=503 bytes= protocol=https 2021-01-27T03:16:10.630599+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=djangotodowoo.herokuapp.com request_id=9426a4a1-061f-41b6-a9a0-46190b752b60 fwd="66.31.116.154" dyno= … -
why doesn't ::after work when trying to change css background?
I have the following problem, Im trying to make a navigation bar with ul in django with css using a background image. The problem is that I want its opacity to be 0.5, but when I do it, the words also gain opacity, which I don't want. So I read that if I use a "pseudo-element" (using ::after in the ul) I could raise the opacity of the background without affecting the words. I used the content:"" variable. ul{ margin: -0.5em 0 0 -0.5em; width: 82.5em; } ul::after{ content:""; background-image:url("fondo.jpg"); opacity: 0.5; } The problem is that after doing it, the ul doesn't load the background, but if I put the background-image in the ul one (without the ::after), it does. Im clearly very noob at this, hehe, thanks! The first picture is what I get when I put the image in the ::after. The second is what I get when I put it in ul. But if I change its opacity, I also change the words. -
Render data from Django multiple times using Vue
I am working on a project running Django and Vue. I want to achieve this: users should be able to book different rooms in multiple terms. In order to do that, I want to use Vue to create a dynamic form (by that I mean adding/removing terms), in which for every term, the user would be allowed to select: day, starting hour, finishing hour, and multiple rooms. Rooms are defined in the database, having their own model, so in order to fetch them, I may use Django template with the following code: {% regroup rooms by get_floor_display as floor_list %} <label for="room_selector">Select classrooms</label> <select class="selectpicker" id="room_selector" multiple> <option value="all" selected="selected">All</option> {% for floor in floor_list %} <optgroup label="{{ floor.grouper }}"> {% for r in floor.list %} <option value="{{ r.number }}"> {{ r.number }} ({{ r.capacity }} places, {{ r.get_type_display }}) </option> {% endfor %} </optgroup> {% endfor %} </select> This code creates a nice select, in which I have optgroups with floors' names (floor.grouper) and possible rooms I may select (given by r.number and some additional informations). Up to this moment, having the code in file.html without any usage - everything works perfectly fine, as expected. Now comes the harder … -
Django intergrity error while signing up using google allauth authentication
I am getting an integrity error when attempting to sign up a new user via google authentication. My normal user registration form works fine though. Here is my model: Class User (AbstractUser) objects = CustomUserManager() email = models.EmailField(unique=True, blank=False) username = models.CharField(max_length=100, unique=True, help_text='Required.') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateField(default=timezone.now) birthdate = models.DateField(default=timezone.now) slug = models.SlugField(max_length=50, null=True, blank=True) gender = models.CharField( max_length=20, choices=GENDER_OPTIONS, blank=False, default='') country = CountryField(default='US') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def save(self, *args, **kwargs): if not self.slug: value = self.username self.slug = slugify(value, allow_unicode=True) super().save() And here are my settings: ACCOUNT_SIGNUP_FORM_CLASS = "core.forms.CustomUserCreationForm" SOCIALACCOUNT_AUTO_SIGNUP = False ACCOUNT_EMAIL_REQUIRED=True SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE':['profile','email',], 'AUTH_PARAMS':{'access_type':'online', } } } Form: class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'placeholder': 'Enter Username'}) self.fields['email'].widget.attrs.update({'placeholder': 'Enter Email'}) self.fields['password1'].widget.attrs.update({'placeholder': 'Enter password', 'label': ''}) self.fields['password2'].widget.attrs.update({'placeholder': 'Repeat your password'}) class Meta(UserCreationForm): model = User fields = ('email', 'username', 'gender', 'country', 'password1', 'password2') help_texts = { 'email': 'required', 'gender': 'optional', 'country': 'required' } labels = { 'email': '', 'username': '', 'gender': '', 'gender': '', 'password1': '', 'password2': '', 'country' :'Your location', } def clean_username(self): username = self.cleaned_data['username'] print(username) if ' ' in username: raise forms.ValidationError("Username may not contain spaces.") … -
How to validate against full model data in Django REST Framework
TL;DR In my Serializer.validate method, I need to be able to access attrs['field'] and fall back to self.instance.field if it's not set in the incoming data, and I'm wondering if there is a common pattern to do so. The Problem Take the example from the Object-level validation section of the DRF Serializers documentation: from rest_framework import serializers class EventSerializer(serializers.Serializer): description = serializers.CharField(max_length=100) start = serializers.DateTimeField() finish = serializers.DateTimeField() def validate(self, attrs): """ Check that start is before finish. """ if attrs['start'] < attrs['finish']: raise serializers.ValidationError("finish must occur after start") return attrs (This uses a normal Serializer, but imagine it's a ModelSerializer for an Event model.) When an event is created, or updated where both the start and finish attributes are included in the data, then this serializer works as expected. However, if you make a request such as: client.patch(f"/events/{event.id}", {"start": "2021-01-01"}) Then the serializer will fail, because trying to access attrs['finish'] results in a KeyError. In this case, I need to be able fall back to self.instance.finish, since the start < finish validation is still necessary. Is there a common pattern that solves this problem? Current Solution You can solve this by adding a snippet to the start of all … -
Not able to deploy Django app on AWS Lightsail using Apache server based on provided tutorial
I followed the tutorial (https://aws.amazon.com/getting-started/hands-on/deploy-python-application/) on deploying Django website in AWS Lightsail. When I use the python3 manage.py runserver 0.0.0.0:8000 to deploy the website then it works perfectly and I can access the website at http://AWS.INSTANCE.PUBLIC.IP.ADDRESS:8000 However, if I follow the Host the application using Apache part of the same tutorial, I am getting the following error when I try to access http://AWS.INSTANCE.PUBLIC.IP.ADDRESS: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at you@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. How to successfully deploy the Django website/app using Apache on AWS Lightsail instance? -
"django-admin" check not finding settings or project modules
I am attempting to check my settings for deployment by running the following on my Django server: django-admin check --deploy When I run the above, I see: django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This seems strange, because my server is up and running, and I've defined DJANGO_SETTINGS_MODULE in my manage.py as follows: def main(): """Run administrative tasks.""" if os.environ.get("ENV") in RELEASE_ENVS: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.prod") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.dev") This is successfully being picked up, as I see Django version 3.1.5, using settings 'app.settings.prod' as the output in my running server logs. As I've seen on other questions, I tried setting the settings more explicitly with: django-admin check --deploy --settings=app.settings.prod However, this is unsuccessful with the following output: ModuleNotFoundError: No module named 'app' I subsequently tried export DJANGO_SETTINGS_MODULE=app.settings.prod and got the same error above. The settings clearly seem to be getting pulled in as I see the settings in my python manage.py diffsettings --all. However, when I do django-admin diffsettings --all I get the below: django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing … -
__init__() takes 1 positional argument but 2 were given "TypeError at /hello/"
i tried to setup hello world project but it give me this error TypeError at /hello/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/hello/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\usama\OneDrive\Documents\atom\Django\FirstPro\app\views.py, line 7, in index Python Executable: C:\Users\usama\anaconda3\envs\MyEnv\python.exe Python Version: 3.9.1 Python Path: ['C:\Users\usama\OneDrive\Documents\atom\Django\FirstPro', 'C:\Users\usama\anaconda3\envs\MyEnv\python39.zip', 'C:\Users\usama\anaconda3\envs\MyEnv\DLLs', 'C:\Users\usama\anaconda3\envs\MyEnv\lib', 'C:\Users\usama\anaconda3\envs\MyEnv', 'C:\Users\usama\anaconda3\envs\MyEnv\lib\site-packages'] urls.py from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('hello/', views.index), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render from django.http import HttpRequest # Create your views here. def index(request): return HttpRequest('hello , world!') installed app in project's setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ]