Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Next parameter in url not showing but is printing correctly in django
This is my signup view: def signup(request): next = request.GET.get('next', '') print(next) if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": first_name=request.POST['first_name'] email=request.POST['email'] password=request.POST['password'] cpassword=request.POST['cpassword'] signup_uri = f'/signup?next={next}' if password==cpassword: if User.objects.filter(email=email).exists(): messages.info(request,'Email already in use') return redirect(signup_uri) elif User.objects.filter(mobile=mobile).exists(): messages.info(request,'Mobile Number already in use') return redirect(signup_uri) else: user=User.objects.create_user(first_name=first_name,email=email,password=password) user.save(); return redirect(f'/login?next={next}') else: messages.info(request,'Passwords not matching') return redirect('signup_uri') else: return render(request,'signup.html') The problem I am facing is that when I am printing next under def signup it is printing it correctly but when it has to redirect it redirects without showing anything as next in url. That is signup_uri = f'/signup?next={next}' and return redirect(f'/login?next={next}') are showing the {next} as empty.What could be the reason?Any help would be appriciated. -
Django circular import error - how to debug it?
I tried to follow this tutorial https://blog.nicolasmesa.co/posts/2018/10/saas-like-isolation-in-django-rest-framework/ using: Django 3.1 Python 3.6 Everything I did including 'The User Messages App' paragraph worked perfectly right before the 'Refactoring the views' passage and then I got the error when running manage.py runserver django.core.exceptions.ImproperlyConfigured: The included URLconf 'saas_django.urls' does not appear to have any pa tterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import I tried different types of import but I can't figure out where the cirular import happens My steps to find a bug: the saas_django/urls.py refers to user_messages app: path('api/v1/user-messages/', include('user_messages.urls')), user_messages/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.UserMessageList.as_view(), name=views.UserMessageList.name), path('<uuid:pk>', views.UserMessageDetail.as_view(), name=views.UserMessageDetail.name), ] It seems like something is wrong with the imported user_messages/views.py from rest_framework import permissions from rest_framework import generics from . import serializers from .models import UserMessage class UserMessageList(generics.ListCreateAPIView): name = 'usermessage-list' permission_classes = ( permissions.IsAuthenticated, ) serializer_class = serializers.UserMessageSerializer queryset = UserMessage.objects.all() def perform_create(self, serializer): user = self.request.user company_id = user.company_id # Added from_user serializer.save(company_id=company_id, from_user=user) def get_queryset(self): # Changed this to use the UserMessageManager's method return UserMessage.objects.get_for_user(self.request.user) class UserMessageDetail(generics.RetrieveAPIView): name = 'usermessage-detail' permission_classes = ( permissions.IsAuthenticated, ) … -
Twilio TaskRouter in Django / React JS
I'm building a simple contact center app using Twilio. I'm creating the TaskRouter Worker capability token in my backend like so: Serializer: class TwilioTokenSerializer(serializers.BaseSerializer): def to_representation(self, instance): return { 'token': instance, } View: class TwilioWorkerView(generics.RetrieveAPIView): serializer_class = TwilioTokenSerializer def get_object(self): current_user = self.request.user.worker worker_sid = current_user.worker_sid # Returns a Twilio Worker token for current agent capability = WorkerCapabilityToken( account_sid=TWILIO_ACCOUNT_SID, auth_token=TWILIO_AUTH_TOKEN, workspace_sid=TWILIO_WORKSPACE_SID, worker_sid=worker_sid ) capability.allow_fetch_subresources() capability.allow_update_activities() capability.allow_update_reservations() token = capability.to_jwt() token = capability.to_jwt(ttl=28800) return token In react: import { Worker } from 'twilio-taskrouter'; componentDidMount(){ axios.get('https://myURL.com/api/twilio-worker-token') .then(res =>{ console.log(res.data.token) const worker = new Worker(res.data.token) }).catch(error =>{ console.log(error) }) but I'm getting the 403 web socket error: index.window.js:24 WebSocket connection to 'wss://event-bridge.twilio.com/v1/wschannels?token=(here the token)&closeExistingSessions=false&clientVersion=0.5.2' failed: Error during WebSocket handshake: Unexpected response code: 403 createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 index.js:1 WebSocket error occurred: Event {isTrusted: true, type: "error", target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …} console.<computed> @ index.js:1 <computed> @ index.window.js:17 webSocket.onerror @ index.window.js:24 error (async) createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 setTimeout (async) webSocket.onclose @ index.window.js:24 index.window.js:17 Uncaught n {_errorData: {…}, name: "GATEWAY_CONNECTION_FAILED", message: "Could not connect to Twilio's servers."} r.emit @ index.window.js:17 (anonymous) @ index.window.js:17 r.emit @ index.window.js:17 webSocket.onerror @ index.window.js:24 error (async) createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 setTimeout (async) … -
Difference between form class attribute "fields" and "declared_fields" in Django
I was looking into a way to change the fields of a form dynamically in Django and came across the fields attribute. This attribute makes sense to me and worked as expected. However I also just came across the class attribute declared_fields and I cant wrap my head around what this does differently and why its there. I also cant find an explanation online for it. Can someone please explain the difference between the two? -
How to count how many times foreignkey object can be used
My models.py class Timing(models.Model): time = models.CharField(max_length=250) count = models.IntegerField(default=0) # max=20 class Ticket(models.Model): username = models.CharField(max_length=50) no = models.ForeignKey(Timing, on_delete=models.CASCADE) Is there a way I can increment the value of count variable in class Timing by 1 whenever I use no variable to connect object of Timing class (whenever I use the ForeignKey variable)? -
Can't Retrieve Data from MongoDB in django application
I am trying to develop a website in Django. I am using MongoDB as a database for the first time. I used Djongo to develop the connection between django and MongoDB. I have created a database in the Robo3T and the connection is also developed between django and MongoDB. The data is saving fine in the database I have seen in the robo3T. But when I am trying to retrieve the data back from the MongoDB to dispay on the Django Template, its not shoiwng the data and show the template tag like this {{post.tile}} {{post.content}}. Here is my code: Setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'test', 'HOST':'localhost', 'PORT':27017 } } view.py from django.shortcuts import render from django.views.generic import View,TemplateView from .forms import FormName from .models import Post # Create your views here. class MainPageView(TemplateView): template_name='main.html' class LoginView(TemplateView): template_name='login.html' def RegistrationView(request): form=FormName() if request.method == 'POST': print("In Post") print(request.POST) form=FormName(request.POST) if form.is_valid(): form.save(commit=True) else: form=FormName() return render(request,'registration.html',{'form':form}) # template_name='registration.html' def main(request): post=Post.objects.all() return render(request,'main_temp.html',{'Post':post}) models.py from django.db import models # from OnlineJobPortal.settings import DBNAME # # Create your models here. # # connect(DBNAME) class Post(models.Model): title=models.CharField(max_length=250) content=models.CharField(max_length=250) forms.py from django import forms from .models import Post class … -
Docker container doesn’t starts after changing host directory
I have a django app which i’m dockerizing. Below is the docker-compose.yml file (Only django part is given here). web: build: . command: python ./webapp/server.py restart: always volumes: - .:/code - ./webapp/static:/static networks: - nginx_network - couchserver_network - dummyapi_flaskapp_network when i change the name of the host directory from where it is run, i’m getting the following error : python: can't open file './webapp/server.py': [Errno 2] No such file or directory I have copied the host directory to image using : RUN mkdir /code WORKDIR /code COPY . /code/ So after renaming my host directory why python is unable to find the server.py file as it is available in containers code directory. I’m novice in docker and have little or no knowledge in volumes. Any help is really appreciated. How can i run this computer in another machine where the host directory wont be available -
How to filter django serializer fields?
I have question about Django REST FRAMEWORK. user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usert', null=True, blank=True) question = models.ForeignKey(Question, related_name='userque', on_delete=models.CASCADE, null=True, blank=True) option = models.ForeignKey(Option, related_name='opt', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username + ' - ' + self.question.question ``` ** This is my model for UserTest. And when ever user gives test. The user will see all questions in drop down as well as all options. But I want only the options of which question user choose. But now i get all of the options. ** ``` class TestSerializer(serializers.ModelSerializer): question = serializers.SlugRelatedField(queryset=Question.objects.all(), slug_field='question') option = serializers.SlugRelatedField(queryset=Option.objects.all(), slug_field='option') class Meta: model = UserTest fields = ('question', 'option') ** This is my Test serializer.** I hope you got the question i m trying to ask. When user selects the question. I want to display only the options of that questions in drop down. Thanks in advance !!!! -
Is the a way to fix form from model not saving to database in django?
Its a bit confusing why this doesn't save to Django admin database. I have the followings class User(AbstractUser): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) I also have in model.py class Student(models.Model): email = models.EmailField(max_length=60, default='type here', help_text='Only valid email') town = models.CharField(max_length=50) phone_number = models.CharField(max_length=10) photo = models.ImageField(upload_to='photos') profile = models.TextField() def __str__(self): return self.user Forms.py class Student(models.Model): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = models.EmailField(max_length=50, default='type here', help_text='Only valid email') town = models.CharField(max_length=50) phone_no = models.CharField(max_length=12) photo = models.ImageField(upload_to='photos') profile = models.TextField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.firstname = self.cleaned_data.get('firstname') user.lastname = self.cleaned_data.get('lastname') user.save() st_student = Student.objects.create(user=user) st_student.email = self.cleaned_data.get('email') st_student.town = self.cleaned_data.get('town') st_student.phone_no = self.cleaned_data.get('phone_no') st_student.photo = self.cleaned_data.get('photo') st_student.profile = self.cleaned_data.get('profile') st_student.save() return user Views.py class StudentSignUpView(CreateView): model = User form_class = StudentSignupForm template_name = 'accounts/student_signup.html' def form_valid(self, form): user = form.save() user_login(self.request, user) return redirect('topropage') I don't know why I can't save this form to a database. Please could you check? -
How can i constrain or choose between one or other foreign key?
The problem is conceptual (databases relationships), so the language isn't the focus here, but I'm using Python and Django. I have 3 models/tables: Company Customer Address Eg. class Company(models.Model): name = models.CharField(max_lenght=100) #example class Customer(models.Model): name = models.CharField(max_lenght=100) #example class Adress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example # here i want the adress owner # i could put something like this: company = models.ForeignKey(Company, on_delete=models.PROTECT) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) I want the address to belong to the customer or the company, but not both. I know that i can simply create 2 Address classes, eg, CustomerAddress, CompanyAddress, each one with its correct foreign key: class Company(models.Model): name = models.CharField(max_lenght=100) #example class Customer(models.Model): name = models.CharField(max_lenght=100) #example class CompanyAdress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example company = models.ForeignKey(Company, on_delete=models.PROTECT) class CustomerAdress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example customer = models.ForeignKey(Company, on_delete=models.PROTECT) But i don't want to for two reasons: The duplicated code and the fact that in django admin panel I will have two separeted address lists, wich doesn't makes much sense, since all address are structurally indentical. I can fix the duplicated code creating a base class, inheriting from it and etc, but i … -
Django. How to fill model attribute in view?
When I save Achivement model, I want to set current user as user_owner. user_owner = request.user my view.py def create(request): if request.method == 'POST': form = AchievementForm(request.POST) form.user_owner = request.user if form.is_valid(): form.save() return HttpResponseRedirect('/cabinet/achievement/') else: form = AchievementForm() return render(request, 'achievement/create.html', {'form': form}) my models.py class Achievement(models.Model): name = models.CharField(max_length=10, unique=True) description = models.CharField(max_length=255, blank=True) requirement = models.TextField(blank=True) status = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) user_owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True,) category = models.ForeignKey(Category, on_delete=models.CASCADE) accept_type = models.IntegerField() img = models.CharField(max_length=255, blank=True) my form.py class AchievementForm(forms.ModelForm): name = forms.CharField(widget=TextInputCustom()) description = forms.CharField(widget=TextInputCustom()) requirement = forms.CharField(widget=TextareaCustom()) status = forms.ChoiceField(choices=Achievement.statusList, widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) accept_type = forms.ChoiceField(choices=Achievement.acceptTypeList, widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) class Meta: model = Achievement fields = ['name', 'description', 'requirement', 'status', 'category', 'accept_type', 'img', 'user_owner'] When I set form.user_owner = request.user in views, validaiting is failed. user_owner This field is required. How to save curent user as owner? -
CSRF Forbidden in firefox but when I send same request form chrome it is working
When i am running my website on chrome its working properly but when i am running it from firefox its showing "csrf cookie not set" This is form from where i made the request import React, { useContext } from 'react'; import './form.css' import CSRFtoken from '../csrftoken' // eslint-disable-next-line import { UserContext } from '../../contexts/UserContext' // componentDidMount(){ // } const Login = (e) => { // eslint-disable-next-line // const [user,setUser]=useContext(UserContext); const log = () => { localStorage.clear() var formdata = new FormData(); formdata.append("username", document.getElementById('username').value); formdata.append("password", document.getElementById('password').value); formdata.append("csrfmiddlewaretoken", document.getElementById('csrftoken').value); var requestOptions = { method: 'POST', body: formdata, // redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/bookdetails/login/", requestOptions) .then(response => response.json()) .then(result => { if (result.user == 'exist' && result.password == 'invalid') { document.getElementById('error').innerHTML = 'Incorrect Password'; } else if (result.user == 'invalid' && result.password == 'invalid') { document.getElementById('error').innerHTML = 'Incorrect Username'; } else if (result.user == 'exist' && result.password == 'valid') { localStorage.setItem('data',JSON.stringify(result)); window.location.href='/'; } }) .catch(error => console.log('error', error)); } return ( <div id="focus_form"> <div className="section" id="login_section"> {/* <button onClick='form_out("login_section")' id='close' >X</button> */} <h1 align='center'>Login</h1><br /> <center> <p id='error'></p> <form id='login_form' > <CSRFtoken></CSRFtoken> <input type='text' id='username' name='username' placeholder='usermame' autoComplete="off" required /><br /> <input type='password' id='password' name='password' placeholder="password" required /><br /> <center> <input type='button' onClick={log} … -
Why my date_of_birth not show up in template django?
I have a date of birth field in my model but why it's not showing up in the template when I render it? The date_of_birth is inside Teacher model. And Do you have any good idea on date_of_birth field? Because right now I'm using charfield for that so I need to convert the DateInput to string so that I can add it into charfield. here is my models.py class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) date_of_birth = models.CharField(max_length=100) def __str__(self): return self.user.email my forms.py class TeacherRegisterForm(UserCreationForm): date_attr = {'class': 'form-control', 'id': 'dateofbirth-register', 'type': 'date'} date_of_birth = forms.DateField(widget = forms.DateInput(attrs=date_attr)) class Meta(UserCreationForm): model = CustomUser fields = ['date_of_birth', ..] def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True user.save() teacher = Teacher.objects.create(user=user) teacher.date_of_birth += str(self.cleaned_data.get('date_of_birth')) return user views.py @login_required @teacher_required def teacherInfoView(request): template_name = "attendance/content/teacher/teacher_info.html" teacher_info = Teacher.objects.filter(user=request.user) context = {'teacher_info': teacher_info} return render(request, template_name, context) template {% for info in teacher_info %} <!-- firstname --> <div class="row"> <div class="ml-5 mr-auto"> <h5>Name : {{ info.user.first_name }} {{ info.user.last_name }}</h5> </div> <div class="ml-5"> <h5>Email : {{ info.user.email }}</h5> </div> </div> <div class="row"> <div class="ml-5"> <h5>Date Of Birth : {{ info.date_of_birth }}</h5> </div> <div class="ml-5"> <h5>Gender : {{ info.user.gender }}</h5> </div> </div> {% … -
login_required Django redirect next not working
Hello. I try to redirect user to the page he wants before he login, by login_required but the page doesn't redirecting! I have searched a lot but I found nothing. Here my main codes for login_required: I summarized them to the related subject. If need to add something else, tell me. Thank you in advance. VIEW: from django.contrib.auth.decorators import login_required def user_login(request): next_url = request.GET.get('next') print(next_url) if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request, username=cd['username'], password=cd['password']) if user is not None: login(request, user) messages.success(request, 'Login Successful', extra_tags='success') if next_url: return redirect(next_url) return redirect('post:all_posts') else: messages.error(request, 'Wrong Username Or Password', extra_tags='warning') else: form = UserLoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request, user_id): users = get_object_or_404(User, id=user_id) posts = Post.objects.filter(user=users) context = {'user': users, 'posts': posts} return render(request, 'account/dashboard.html', context=context) Settings: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Post.apps.PostConfig', 'Account.apps.AccountsConfig', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'SocialNetworkP.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
I can't access my XAMPP localhost through internet
I have setup my Django project on my XAMPP server. After doing this i can connect my server through localhost and through my ip on LAN. But i can't access it through internet. I have done the port forwarding on my router and i have even tried to access it through my static ip, but it doesn't connected. Can you guys, please help in fixing the problem? -
How to Display/Fetch Data on button click using AJAX in Python - AJAX
I am new to both ajax and django. I want to fetch phone number from database and want to display on template when click user the contact button. But in my case I am getting all the phone numbers in first button itself which is not correct. Because different persons have different phone numbers. Please help me. Thanks in advance. views.py: from django.shortcuts import render, redirect from .models import listing_model from .forms import listing_form from django.http import HttpResponse def submissions(request): tasks = listing_model.objects.all() form = listing_form() if request.method =='POST': form = listing_form(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('submissions') context = {'tasks':tasks, 'form':form} return render(request, 'submission.html', context) #ajax def contact(request): numbers= listing_model.objects.values('phone') return HttpResponse( numbers ) home.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Home{% endblock %} {% block body %} <div class="container"> <div class="row"> <form method="GET" class="mx-auto" ><br> {{ user_filter.form }}<br><br> <button type="submit" class="btn btn-info" style="margin-left:250px">Search</button> </form> </div> </div> <div>&nbsp; &nbsp;</div> <div class="container"> <div class="row"> {% for task in tasks %} <div class ="col-md-4"> <div class="card" style="width:300px"> <div class="card-body"> <h4 class="card-title">Title : {{ task.title }}</h4> <div>Address : {{ task.address }}</div> <div>City : {{ task.city }}</div> <img src="{{ task.image.url }}" style="max-height:200px"> <div>&nbsp;</div> <button class="btn btn-primary" id="request-btn">Contact</button> <script … -
Quality of image drops when encoding an Image in Python
I am trying to create Barcodes in a Django app using python-barcode library and show them on the django template but it reduces the quality of the image when printing it. Is there a way to keep the resolution same or maybe fix the column size on template such that it doesn't pixelate Views.py def PrintGRNsv1(request, pk): ... for item in items: EAN = barcode.get_barcode_class('code128') d = {'module_width': 0.15, 'module_height': 2.5, 'quiet_zone': 0.5, 'text_distance': 0.5, 'font_size': 6, 'text_line_distance': 5} w = ImageWriter(d) ean = EAN(item['bar'], writer=ImageWriter()) a = ean.save(item['bar'], options=d) print("a ", a) with open(a, 'rb') as image: img = image.read() encoded_string = base64.b64encode(img).decode('utf-8') alist.append({ 'image': encoded_string , **item}) os.remove(a) alist = grouper(alist, 7) return render(request, 'grn/printgrn.html', {'imglist':alist}) template: <div class="grid-col"> <span style="text-align: center"> <br> <br> <img src="data:image/png;base64,{{ row.image }}" alt="" srcset=""> <br> {{ row.label }} <br> {% if row.lname %} {{ row.lname }} {% else %} _____ {% endif %} </span> </div> -
how can i solve paginator problem in python django?
error page it's a search_post.html it's a View.py -
Django Project to convert Binary to Decimal
I recently started learning Django and I want to create a Django project to convert Binary into Decimal The functionality should be similar to this one I am unable to figure out how should I proceed and what should I use. I want to achieve the following : I shouldn't use models.py because I don't want to store the data every time a user enters. I need to pass a condition to check whether the data entered is in the form of 1's and 0's. I need to pass the integer data after it is converted from binary data back to the HTML form and display in the browser forms.py from django import forms from django.forms import TextInput class BinaryDecimalForm(forms.Form) : binary = forms.CharField( widget=forms.TextInput(attrs={'class':'input','placeholder':'Binary...','size':40}), max_length=8 ) views.py from django.shortcuts import render from .forms import BinaryDecimalForm def home(request) : form = BinaryDecimalForm() if request.method == 'POST' : form = BinaryDecimalForm(request.POST) if form.is_valid : data = form.cleaned_data.get('binary') for d in data : if d.is_binary() : pass context = { 'form' : form } return render(request,'app\home.html',context) home.html <main> <br> <div class="container"> <div class="row"> <div class="col-md-8 mx-auto"> <form action="" method="post"></form> {% csrf_token %} {{form.binary}} <br> <br> <button class="btn btn-outline-primary" type="submit">CONVERT</button> <br> <br> <input … -
topic = models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete'
from django.db import models Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() ```def __str__(self):``` ```return str(self.date)``` **on_parameter is required ** I'm using Django v3.0 in Pycharm please guide me CODE THAT I WROTE -
Carousel items not showing 4 items in 2nd slide in django and html template
i am trying to display all carousel item through for loop dynamic from the database but 1st slide is perfectly showing 4 card items but 2nd slide only showing three carousel items . Here carousel items image and the html file <div class="row"> <h2 id="trendingservice">Trending <b class="underline-small"> Services</b></h2> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="0"> <div id="demo" class="carousel slide" data-ride="carousel"> <!--Slideshow starts here --> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ services.0.Image }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ services.0.service_name }}</h5> <p class="card-text"> {{ services.0.service_desc|safe }} </p> <a href="/website/services/{{ services.0.service_name }}" class="color-two btn-custom">Get Services</a> </div> </div> </div> {% for i in services|slice:"1:" %} <div class="col-xs-3 col-sm-4 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ i.Image }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ i.service_name}}</h5> <p class="card-text"> {{ i.service_desc|safe }} </p> <a href="/website/services/{{ i.service_name }}" class="color-two btn-custom">Get Services</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- left and right controls for the slide --> <a class="carousel-control-prev" href="#demo" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#demo" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </div> </div> **here is view.py … -
run Gunicorn with WSGI inside a folder
I have my project structure as below. I use folders to put all the settings files in them. ~/myproject/ - env - server - api - home - settings - dev.py - prod.py - wsgi - dev.py - prod.py the myproject/server/home/wsgi/dev.py is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "home.settings.dev") application = get_wsgi_application() also inside myproject/server/home/settings/dev.py is: WSGI_APPLICATION = 'home.wsgi.dev.application' with all the above setup the server runs perfectly. When i try to deploy and run the gunicorn, it just fails. Here is my gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=demouser Group=www-data WorkingDirectory=/home/demouser/myproject ExecStart=/home/demouser/myproject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/demouser/myproject.sock home.wsgi.dev:application [Install] WantedBy=multi-user.target I am not sure why i get this error as the gunicorn never starts: Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2020-08-30 05:04:48 UTC; 14min ago Process: 13354 ExecStart=/home/demouser/myproject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ Main PID: 13354 (code=exited, status=203/EXEC) Aug 30 05:04:48 localhost systemd[1]: Started gunicorn daemon. Aug 30 05:04:48 localhost systemd[13354]: gunicorn.service: Failed to execute command: No such file or directory Aug 30 05:04:48 localhost systemd[13354]: gunicorn.service: Failed at step EXEC spawning /home/demouser/myproject/env/ Aug 30 05:04:48 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Aug 30 05:04:48 localhost systemd[1]: … -
Why django is accepting two diiferent passwords? Giving no error at all
Why this code is accepting both password and confirm_password field? without errors Here is first models.py file: (indent is not a problem here) from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import UserManager from django.utils.translation import ugettext_lazy as _ # Create your models here. ROLES = ( ('Customer', 'Customer'), ('Vendor', 'Vendor') ) class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email Address', max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) role = models.CharField(max_length=15, choices=ROLES) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def __str__(self): return self.email def get_name(self): return self.first_name + ' ' + self.last_name def get_role(self): return self.role def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active Next the manager for user model: Here I'm just accepting data and creating accounts only. from django.contrib.auth.models import BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('User must have an Email Address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('staff', False) extra_fields.setdefault('admin', False) … -
debugging jQuery ajax - works on localhost server, doesn't work on production server
For example, the following ajax call is working just fine on my localhost: $.ajax({ type:"POST", url: "/teachers/studentMonthAgenda/", data:{ 'event_start': dayMs, 'event_end': endOfMonthMs, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', cache: false, success: function( eventData ) { getEvents(eventData); }, error: function(xhr, status, error){ var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); } }); On my production server with the following attributes: Python 3.6 running on 64bit Amazon Linux/2.9.13 elastic beanstalk the same code leaves absolutely no trace of an error. I'm finding ajax to be the only thing that can't be debugged easily on elastic beanstalk because it leave absolutely squat in the log file if there is an error, and there clearly is something going wrong in this case. The inputs (dayMS and endOfMonthMs) are good too, so it really must be the ajax call that is the problem. I should add, it was working before I redirected traffic from port 80 to port 443. -
Django: Is there a way to use widgets on functions without class in view.py?
I am new to django and trying to use widgets and bootstrap to make my forms template look better. I saw a video tutorial on how to do so, but he uses class in views.py while I want it on function I created. Is there anyway to use the given widget on function addItem? The forms.py file: class ItemsForm(ModelForm): class Meta: model = Item fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'image':forms.TextInput(attrs = {'class':'form-control-file'}), } My views.py file: def addItem(request): if request.method=="POST": form=ItemsForm(request.POST, request.FILES) print(form) if form.is_valid(): try: print("valid") form.save() return redirect("/items") except: print("validation failed") else: form=ItemsForm() print("invalid") return render(request, "dashboard/items/items_form.html",{'form':form}) The template I am trying to render it in: <div class="form-group"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" name="Submit"> </form> </div>