Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Django Logging Filter for a Particular API
In my app, there is this API named 'UserChangeWorkScheduleViewSet' where its uri is 'host/api/v1/workSchedule' I have been trying to make a custom logging filter that would send me an error log whenever a user causes 400 status code. Below is the UserChangeWorkScheduleViewSet in 'workschedule.py': class UserChangeWorkScheduleViewSet(viewsets.ModelViewSet): queryset = UserChangeWorkSchedule.objects.all() serializer_class = UserChangeWorkScheduleSerializer permission_classes = (IsAuthenticated,) def create(self, request, *args, **kwargs): UserChangeWorkSchedule.objects.filter(user=request.user.id).update(status=0) is_many = isinstance(request.data, list) if not is_many: request.data['user'] = request.user.id return super().create(request) else: for data in request.data: data['user'] = request.user.id serializer = self.get_serializer(data=request.data, many=True) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: print('UserChangeWorkScheduleViewSet', request.user.id, serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is my customlog.py: import logging class UserChangeWorkScheduleViewSet400(logging.Filter): def filter(self, record): record.levelname == 400 record.filename == "workschedule.py" return True And here is the logging in the settings from api import customlog LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'only_400_from_workschedule': { '()': customlog.UserChangeWorkScheduleViewSet400 }, }, 'formatters': { 'simple_trace': { 'format': '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(message)s', } }, 'handlers': { 'telegram': { 'class': 'telegram_handler.TelegramHandler', 'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA', 'chat_id': '-429967971', 'formatter': 'simple_trace', } }, 'loggers': { 'django.request': { 'handlers': ['telegram'], 'level': 'ERROR', 'propagate': True, }, }, } I intentionally sent a bad request to raise … -
Unknown column 'distance' in 'where clause'
I'm new to the Django rest framework. I want to find users in the database that have the shortest distance to the given coordinates. This is my code: User.objects.extra( select={ 'distance': "POW(69.1 * (latitude - %s), 2) + POW(69.1 * (%s - longitude) * COS(latitude / 57.3), 2)" }, select_params=[latitude, longitude], where=[ "is_superuser = false", "not id = %s", "latitude is not null", "longitude is not null", "distance < 25" ], params=[current_user_id] ) .values_list('id', 'distance') and exception: "Unknown column 'distance' in 'where clause" -
I have a URL Shortening Service, I want to track on which day the short url was clicked. Basically I Want To Track Views Per Day For Analytics
I have a URL Shortening Service, I want to track on which day the short_url was clicked. So I can get data of views per day. I am using django. I have created url shortener service. URL SHORTNERE MODEL: from django.db import models from django.contrib.auth.models import User # Create your models here. from authentication.models import Profile class ShortenURL(models.Model): user = models.ForeignKey( Profile, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=70, null=True, blank=True) original_url = models.URLField(max_length=2048, null=True, blank=True) short_url = models.CharField(max_length=7, null=True, blank=True) clicks = models.IntegerField(default=0, null=True, blank=True) date_created = models.DateTimeField( auto_now_add=True, null=True, blank=True) def __str__(self): return f"{self.name} By {self.user}" Profile Model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField( User, related_name='profile', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(max_length=1500, null=True, blank=True) location = models.CharField(max_length=30, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) limit = models.PositiveIntegerField(default=10, null=True, blank=True) # For Guest User device = models.CharField(max_length=50, null=True, blank=True) profile_picture = models.ImageField( upload_to='ProfilePic/', null=True, blank=True) def __str__(self): if self.user: return "%s's profile" % self.user else: return "%s's profile" % self.device @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get_or_create(user=instance) user_profile, created = Profile.objects.get_or_create(user=instance) user_profile.save() Please … -
No value for argument 'phrase' in method call
I am currently working on a Django website. However, I am experiencing some errors with the parameters of the function. I know that self and request have to go in this order. However, the phrase parameter doesn't get recognized because when I run the program, it appears this error: No value for argument 'phrase' in method call Here's the code and where the error appears: def build_protein(self, request, phrase): #argument phrase doesn't get detected protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') return protein Does anyone know how to solve this? -
module 'django.db.models' has no attribute 'model'
enter image description hereI am very new to django and i just got an error (module 'django.db.models' has no attribute 'model') while creating a website for my project . can anyone help me to resolve these issue ? -
How to filter Django queryset by model property?
I have a method in my django app model like below : @property def invoice_id(self): """ Represent the invoice object in __str__ format BELLA-17-08-20-2 :return: """ day_list = [] invoice_list = Invoice.objects.filter(timestamp__year=self.timestamp.year, timestamp__month=self.timestamp.month, timestamp__day=self.timestamp.day).all() for invoice in invoice_list: day_list.append(invoice.id) position = 0 for i in day_list: if i == self.id: invoice_id = 'BELLA-' + self.timestamp.strftime("%d-%m-%y") + '-' + str(position + 1) return invoice_id position += 1 I want to filter in my views.py like : queryset = Invoice.objects.filter( Q(.......) ) How can I do this ?? Any Suggestion ?? -
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead
I am building a blog app in django. But, when I write a function for logging users out, I get this traceback error: Internal Server Error: /users/logout/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 309, in check_response "instead." % name ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead. My logout_user view function is only two lines, so I can't seem to understand the error. Here is my view function: @login_required def logout_user(request): logout(request) Can anyone help me out? -
UNIQUE constraint failed: store_order.id
i have created a payment system so after successful payment the orders status will change to PAID Here is my models.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField(max_length=100, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here status field has been set to unpaid but when payment is successful it will show PAID For that i tried this : def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) print(customer) user_orders = Order.objects.get(pk=kwargs['id']) # index = Order.objects.get(customer=customer) # print(index.total) total = user_orders.total print(total) balance = request.session['customer']['coin'] print(balance) if balance >= total: balance = balance - total # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer.coin = balance customer.save() user_orders.status = "PAID" user_orders.save() request.session['customer']['coin'] = str(balance) return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") But getting this error : UNIQUE constraint failed: store_order.id -
How to create instance with pre-populated ChoiceField in form
This is my forms.py. I want to create instance with default 'V' choice into my model. So instance was created, but with choice 'A', which i provided in model for default. class VideoForm(forms.ModelForm): theory_type = forms.ChoiceField(choices=quests.StageTheories.THEORY_TYPE) class Meta: model = quests.StageTheories fields = ['title', 'youtube', 'stage'] class StageTheories(models.Model): THEORY_TYPE = ( ('Q', 'Quiz'), ('A', 'Article'), ('V', 'Video'), ) stage = models.ForeignKey(to=Stages, on_delete=models.CASCADE, db_column="stage_id",verbose_name="Этап", ) title = models.CharField(max_length=47, db_column="title", verbose_name="Заголовок теории",) text = models.TextField(db_column="text", verbose_name="Текст теории", null=True, blank=True,) youtube = models.URLField(db_column="youtube", verbose_name="Ссылка на youtube", null=True, blank=True,) sortOrder = models.PositiveIntegerField(null=True, blank=True, db_column="sort_order", verbose_name="Порядковый номер", ) theory_type = models.CharField(max_length=1, choices=THEORY_TYPE, default='A') class AddVideoView(CreateView): model = quests.StageTheories form_class = VideoForm success_url = '/' template_name = 'add_video.pug' def get_initial(self): initial = super().get_initial() initial['stage'] = quests.Stages.objects.get(id=self.kwargs['pk']) initial['theory_type'] = 'V' return initial Is initial value not going for form data? -
Django/Python zlib Compress Json - Uncompress JS Client Size
I'm compressing json in Python using the following code: chartDataListJsonCompressed = zlib.compress(str.encode(chartDataListJson)) Then I send the data to client-side using Httpresponse (convert it to string as well): return(HttpResponse(str(chartDataListJsonCompressed))) On Ajax client side I'm trying to convert this compressed string data back to string using the pako library: success: function (data) { //Convert string data to char data var charData = data.split('').map(function(x){return x.charCodeAt(0);}); //Convert char data to array var binData = new Uint8Array(charData); // Pako - inflate bin data var d = pako.inflate(binData); // Convert gunzipped byteArray back to ascii string: var strData = String.fromCharCode.apply(null, new Uint16Array(d)); } Unfortunately I get the error: Uncaught incorrect header check Thus, I'm obviously doing something wrong. I just cannot get my finger on it. Any ideas? -
How to use create function instead of perform_create in ListCreateApiView in django rest framework
I am trying to create a booking api for a website. For this, I used perform_create function in ListCreateApiView. But, it was someone else who helped me and told me to use perform_create function. But, I was thinking, it should be possible using create function and is a right approach rather than perform_create function. Also, I don't really know the difference between these two functions and don't really know when to use which. Here is my view: class BookingCreateAPIView(ListCreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def perform_create(self, serializer): # user = self.request.user package = get_object_or_404(Package, pk= self.kwargs['pk']) serializer.save(user=self.request.user,package=package) Here is my serializer: class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] Here is my model: class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package') name = models.CharField(max_length=255) email = models.EmailField() phone = models.CharField(max_length=255) bookedfor = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) -
Django / MySQL / Python Programming Error ( 1064)
when I run python manage.py migrate I keep getting the following error. django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, user_id_id integer NOT NULL)' at line 1") I'm running Python 3.8.6, and mysqlclient 2.0.1 and Django 3.1.3. Model from ..assets.provinces import PROVINCE_CHOICES from ..assets.industries import INDUSTRY_CHOICES from django.contrib.auth.models import User class GrantProfile(models.Model): user = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) province = models.CharField( max_length=2, choices=PROVINCE_CHOICES, help_text="Province your organization is based out of" ) company_size = models.IntegerField(help_text="Company size") industry = models.CharField( max_length=150, choices=INDUSTRY_CHOICES, help_text="Industry your organization is part of." ) class Meta: db_table = "grantprofiles" View # Grant Profile View from rest_framework import viewsets from ..serializers.grantprofile import GrantProfileSerializer from ..models.grantprofile import GrantProfile class GrantProfileView(viewsets.ModelViewSet): serializer_class = GrantProfileSerializer queryset = GrantProfile.objects.all() Admin from django.contrib import admin from ..models.grantprofile import GrantProfile # Grant Profile Admin class GrantProfileAdmin(admin.ModelAdmin): list_display = ('user_id', 'province', 'company_size', 'industry') admin.site.register(GrantProfile, GrantProfileAdmin) Serializer from django.contrib import admin from ..models.grantprofile import GrantProfile from rest_framework import serializers from ..models.grantprofile import GrantProfile class GrantProfileSerializer(serializers.ModelSerializer): class Meta: model = GrantProfile fields = ('user_id', 'province', 'company_size', 'industry') I'm not sure if I'm missing something? -
Add item to dropdown without refresh
City is a (dropdown in a main form ) with a +(Add) button. This +(Add) button opens another form in separate window. On saving a new city in the second form, I want the new city name to be added in the City dropdown without refreshing the main form. Here is my code. <form method="POST" enctype="multipart/form-data" id="form"> {% csrf_token %} <td>City: {{ form.city }} <button class="btn btn-primary" onclick="addCity(event)">+</button> </td> <button type="submit" class="btn btn-primary">Save</button> </form> <script> function addCity(e){ e.preventDefault(); window.open("/city/", "", "width=500,height=500"); } </script> city.html <form method="POST" class="post-form" action="/city/" id="form"> {% csrf_token %} <div class="container"> <div class="form-group row"> <label class="col-sm-2 col-form-label">City:</label> <div class="col-sm-4"> {{ form.name }} </div> </div> <button type="submit" class="btn btn-primary">Save</button> </div> </form> urls.py urlpatterns = [ path('city/', views.add_city, name='city_master'), ] views.py def add_city(request): cities = City.objects.all() if request.method == "POST": form = CityForm(request.POST) if form.is_valid(): try: form.save() return redirect('/city/') except: pass else: form = CityForm() return render(request,'city.html',{'form':form}) -
empty tag {% empty %} in django template doesn't work when "if" condition is nested inside for loop
<ul> {% for entry in entries %} {% if title in entry %} <li><a href="/{{ entry }}">{{ entry }}</a></li> {% endif %} {% empty %} <li>Sorry! No result matches your search.</li> {% endfor %} </ul> This is my html template. Want to create a list where the list items have to meet certain condition, so I nested if condition inside for loop. The list works, but empty tag doesn't. When the list is empty, it doesn't show anything. When I tried to nest empty tag inside if condition, then the empty tag message shows for every list item where the item doesn't meet the if condition. How can I make it work? -
I am extending my header and footer but when i pass data in footer it is visible only at home page not on other pages
I am extending my header and footer but when i pass data in footer it is visible only at home page not on other pages. I know that i have to pass that data on every pages but i am looking for a easy solution example: from django.shortcuts import render,redirect from footer.models import Footer def home(request): contact_info = Footer.objects.all() return render(request,'frontend/index.html', {'contact_info':contact_info}) Index.html <div class="col-md-3 col-md-push-1"> <div class="gtco-widget"> <h3>Get In Touch</h3> <ul class="gtco-quick-contact"> {% if contact_info %} {% for i in contact_info %} <li><a href="tel:{{ i.phone }}"><i class="icon-phone"></i>{{ i.phone}}</a></li> <li><a href="mailto:{{ i.email }}"><i class="icon-mail2"></i>{{ i.email }}</a></li> <li><a href="http://maps.google.com/?q={{ i.location }}"><i class="ti-location-pin"></i>{{ i.location }}</a></li> {% endfor %} {% endif %} </ul> </div> </div> At Contact Page: At Index Page: -
Hello, can this function be converted into a class
I have a function that transfers data to the index page, def index(request): news = News.objects.all()[:3] sponsors = Sponsors.objects.all()[:6] programs = Programs.objects.order_by('date') speakers = Speakers.objects.reverse()[:3] context = { 'news': news, 'sponsors': sponsors, 'programs': programs, 'speakers': speakers, } return render(request, 'landing/index.html', context) can this function be converted into a class as in the example class Home(ListView): model = News template_name = 'landing/index.html' context_object_name = 'news' paginate_by = 3 def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Новости' return context -
Grabbing models from database in asynchronous function (Channel Consumer) Django
Summary Hello, currently I am working on a application that sends data to the frontend in Realtime through using django-channels. I have been able to do this for all models that are created when they page is opened, however I have not yet been able to grab previous models for when the page has not been opened yet. Code Below was one of my first attempts at getting this system working, this would be called when the consumer connect method would be fired, and after the connection was accepted I would run this for loop for app in Application.objects.all(): app_json = ApplicationSerializer(app).data await self.send_json({'action': 'create', 'data': app_json}) When running this code I would get the error message of django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. This makes sense since the consumers connect method is asynchronous, so following the advice of the message I went ahead and used sync_to_async for app in sync_to_async(Application.objects.all)(): app_json = ApplicationSerializer(app).data await self.send_json({'action': 'create', 'data': app_json}) I decided to use sync_to_async around the Application objects since the error message highlighted the for loop line itself and also I know that the applicationSerializer would be working correctly since I … -
Modified User problem django but it's not registering to db
I have modified User in django but it's now registering user to the db. Here is views.py from django.shortcuts import render, redirect from .forms import RegisterForm # Create your views here. def login(request): return render (request, 'UsersAuth/login.html') def register(request): error = "" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: error = 'Form is not valid' form = RegisterForm() context = { 'form': form, 'error': error } return render(request, 'UsersAuth/register.html', context) Here is the forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms import datetime class RegisterForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email *'})) first_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class':'form-control', 'placeholder':'First name *'})) last_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class']= 'form-control' self.fields['username'].widget.attrs['placeholder']= 'User name *' self.fields['password1'].widget.attrs['placeholder']= 'Create a password*' self.fields['password2'].widget.attrs['placeholder']= 'Confirm a password*' self.fields['password1'].widget.attrs['class']= 'form-control' self.fields['password2'].widget.attrs['class']= 'form-control' registration page register.html {%extends 'UsersAuth/base.html'%} {%block title%} Registration {%endblock%}s {%block content%} <form method ='POST' class="form-group text-white"> {%csrf_token%} <div>{{form.username}}</div><br> <div> {{form.first_name}}</div><br> <div>{{form.last_name}}</div><br> <div>{{form.password1}}</div><br> <div>{{form.password2}}</div><br> <button type="submit" class = "btn btn-success">Register</button> </form> {%endblock%} Form on method post and it's sending a post response but in DB … -
Using Django with NextJS
I am looking at integrating NextJS into an existing Django project. The project makes heavy use Django templates for most of its pages and I am looking at modernising the project by taking advantage of React and building out a design / component system. I have been able to use Django to proxy a request through to NextJS, and it works great! I have also been able to send data directly to the NextJS route so that I do not have to call back to Django to get data. Here is the working code. # django def _handle_request(self, data, make_request): data = {"hello": "world"} response = make_request("http://localhost:3000", data=data) return HttpResponse(response) //nextjs Home.getInitialProps = async (ctx) => { const { req, query } = ctx; const data = await parse(req); console.log("body", data); return {}; }; I have read online that using data on a GET request is not recommended for various reasons (eg How to send data in request body with a GET when using jQuery $.ajax()) and POST requests should be used instead. I have tried to get a NextJS route working with POST and it doesn't look like this is an option. So with this in mind, is there … -
Django Admin - Accessing New Model gives 500 error
I created a Django app with one Model initially, and hosted the site successfully with Heroku. I've since added another Model, have run makemigrations and migrate commands, and pushed code to Heroku. Everything appears to be working fine, I can even see the new Model listed on the Admin portal. However, when I click the model, or try to add a new instance of the model, I am thrown and internal service 500 error. I've turned DEBUG to True, and I am seeing this: relation "my_model" does not exist. The other model I have still works, even when I delete all instances. Please help -
AttributeError: 'NoneType' object has no attribute 'AddressLine'
I have: Models: class Profile(models.Model): # Họ Và Tên UserFirstName = models.CharField(max_length=128, validators=[name_regex]) UserMiddleName = models.CharField(max_length=128, validators=[name_regex]) UserLastName = models.CharField(max_length=128, validators=[name_regex]) UserFullName = models.CharField(max_length=256) AddressIDProfile = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) AddressProfile = models.CharField(max_length=128, null=True) class Meta: db_table = "Profile" def save(self, *args, **kwargs): try: self.AddressProfile = self.AddressIDProfile.AddressLine except ObjectDoesNotExist: pass super(Profile, self).save(*args, **kwargs) Problem: I want to assign data to the AddressProfile field by getting it from the foreign keyword AddressIDProfile. But when AddressLine is None, an error occurs. I tried to test it first but with no success. Please give me the solution.Thanks!!! -
Django Formsets - this field is required error
I am getting this error. I am using django formsets and whenever when I post data, the formsets shows this field is required error in everyfield in formset's form Each of them are errors displayed as by my views.py file Views.py def company_allocation_pot(request, company_name): company = Company.objects.get(company_name=company_name) qs=CompanyPotAllocation.objects.filter(company = company) or None if request.method == 'GET': # formset = CompanyPotAllocationFormset(queryset=None) formset = CompanyPotAllocationFormset(queryset=qs, form_kwargs = {"company_name": company_name}, auto_id = "id_%s") return render(request, 'company/create-company-pot.html', {'company_allocation_pot_formset': formset, 'company': company}) if request.method == 'POST': # formset = CompanyPotAllocationFormset(request.POST) formset = CompanyPotAllocationFormset(data=request.POST,queryset=qs,form_kwargs = {"company_name": company_name}, auto_id = "id_%s") if formset.is_valid(): for item_form in formset: item = item_form.save(commit=False) item.date_created = datetime.now() item.company = company item.save() return redirect('charity_app:company_allocation_pot', company_name=company) else: print("\n") print(request.POST) for error in formset.errors: print("\n") for k,v in error.items(): print(f"{k} {v}") return render(request, 'company/create-company-pot.html', {'company_allocation_pot_formset': formset, 'company': company}) Forms.py class CompanyPotForm(forms.ModelForm): fields = ['allocation_amount'] def __init__(self,company_name,**kwargs): super(CompanyPotForm,self).__init__(kwargs) self.company_name = company_name company = Company.objects.get(company_name=company_name) roles = company.company_jobroles or None if roles is None: return choices = tuple((role,role) for role in roles.split(",")) self.fields['grade'] = forms.ChoiceField( choices = choices, label="Specify Grade" ) def cleanRoles(self,value): company = Company.objects.get(company_name= self.company_name) if value in company.company_jobroles: return value else: raise forms.ValidationError("That role is not provided") class Meta: fields = ['allocation_amount',"grade"] model … -
Where do I setup django database credentials?
I've been trying to upload a pandas dataframe into a django database using to_sql, though I see content suggesting that I need to set up some credentials to make it work, such as: from django.conf import settings user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] # host = settings.DATABASES['default']['HOST'] # port = settings.DATABASES['default']['PORT'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) My questions are, where do I set up those configurations user, password, and database_name? and is there a way to not expose sensitive data such as user and password? -
Restricting the url parameter values in Django URL
I have a Django web app that has 2 types of users, say customers, and business. I need to get the type of user trying to login. So I defined a url pattern as folows: path('login/<type>/', LoginView.as_view(), name='login'), But how can I restrict the url patten to match only the following patterns login/customers/ login/business/ -
Inheriting OneToOneField results in TypeError: __init__() got an unexpected keyword argument 'related_name'
I 'm using Django 2.2, Python 3.7 and my attempt was to setup some common kwargs (say, on_delete and related_name) to the OneToOneField, by a sub class like the following class MyOneToOneField(models.OneToOneField): def __init__(self, to): super().__init__(to, on_delete=models.CASCADE, related_name='extra_data') And the model class is like class UserExtraData(models.Model): entity = MyOneToOneField(USER_MODEL) However it results in TypeError: Couldn't reconstruct field entity on UserExtraData: __init__() got an unexpected keyword argument 'related_name' when running makemigrations. ( I tried removing all other fields so pretty sure this is the field that caused the issue ). Any ideas are appreciated!