Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After i write form media in html template, i cannot upload everything
I want to add ckeditor5 in my template ,so i add {{form.media}} to my template. After writing {{form.media}} code , i cannot upload everything. It seems input tag not fuction it. Please help me to figure out what happened!! THX~~ my code is down below: view def post(request): Form = PostForm() if request.method == 'POST': Form = PostForm(request.POST) Form.save() return render(request, "Upload_done.html") else: return render(request, "upload.html", {'Form': Form}) html <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ Form.media }} {{ Form.as_p }} <input type="submit" value="Upload"> form class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] model class Post(models.Model): title = models.CharField(max_length=100) content = CKEditor5Field(config_name='extends') created_at = models.DateTimeField(auto_now_add=True) -
How to change form field label in Django using template language only?
I have tried using django-widget-tweaks to override default form field attributes, where you can set various form field attributes like this: {{ form.username|attr:"name:email"|as_crispy_field}} but when I inspect the element in the Chrome Dev Tools I can see that the element still has the default username name attribute. I was trying to change the name attribute so that the label for this field would display "Email" instead of "Username". So I was wondering if there is a way to change Django form field label using Django template language only? 3rd party tools are OK too. -
Group by specific attribute in Django using ORM
I have a model as below: class Revenue(BaseModel): revenue_type = models.ForeignKey(RevenueType, blank=True, null=True, max_length=256, on_delete=models.SET_NULL, related_name='revenue') external_account_id = models.CharField(blank=True, null=True, max_length=256) external_user_id = models.CharField(blank=True, null=True, max_length=256) Now I want to get all the revenues ids but grouped by similar external_account_id. Suppose the below are the model instances details: revenue1 = Revenue("external_account_id": 1, "external_user_id": 1) revenue2 = Revenue("external_account_id": 1, "external_user_id": 2) revenue3 = Revenue("external_account_id": 1, "external_user_id": 3) revenue4 = Revenue("external_account_id": 1, "external_user_id": 4) revenue5 = Revenue("external_account_id": 2, "external_user_id": 5) revenue6 = Revenue("external_account_id": 2, "external_user_id": 6) revenue7 = Revenue("external_account_id": 3, "external_user_id": 7) revenue8 = Revenue("external_account_id": 3, "external_user_id": 8) revenue9 = Revenue("external_account_id": 4, "external_user_id": 9) revenue10 = Revenue("external_account_id": 5, "external_user_id": 10) I want the queryset or dict like this: {1: [1, 2, 3, 4], 2: [5, 6], 3: [7, 8], 4: [9], 5: [10]} Where the keys are the external_account_id and the values are either external_user_id or ids of the model instances. How can I query for the same? -
How to add custom fields to Registration form in django
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django.contrib.auth.models import User from django.forms.widgets import Widget from django.utils.translation import gettext, gettext_lazy as _ from .models import Post class SignUpForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] labels = {'first_name': 'First Name', 'last_name': 'Last Name', 'email': 'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True, 'class':'form-control'})) password = forms.CharField(label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'class':'form-control'})) class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'desc'] labels = {'title':'Title', 'desc':'Description'} widgets = {'title':forms.TextInput(attrs={'class':'form-control'}), 'desc':forms.Textarea(attrs={'class':'form-control'}), } This is my forms.py file from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=150) desc = models.TextField() This is my models.py file Now I want to create a table for SignUpForm and add some extra fields to it like gender and standard and save it to database I try to and gender and std but it didn't save the values to database what should I do ? from django.shortcuts import render, HttpResponseRedirect from .forms import SignUpForm, LoginForm, PostForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .models import Post … -
"Change password system" does not work in user authentication.(Django)
I'm trying to configure Django app with a user authentication model(django-allauth). It almost works well but when a user tries to change his password, a problem occurs. Let's say when a user want to change his password, he goes to Password reset page Example http://3.129.xx.xxx/accounts/password/reset/ He put his Email address on the form and submit, then he recieve a "Password Reset E-mail" with a link to reset the password. Example https://u22207100.ct.sendgrid.net/ls/click?upn=EGpFlOkd4a3JZnFjHjqKqsCiiinSf51vqFvV..... Cliking above link, the user redirected to http://3.129.xx.xxx/accounts/password/reset/key/1-set-password/ But that page has only links "Sign In" and "Sign Up". It does not have any form to put new password the user want to set. Change password page's image In this situation, the user can not change password. should I set something to allauth system?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How to save a form and call an URL with one button in Django?
I created a form in my Django project. I want to save and call an URL with the same submit button. Firstly, I used action method in my form, when I click the send button it calls the URL but it do not save the form and when I remove the action, it saves the form. I do not know why. How can I call an URL after/when saving the form? ocr/views.py def approval_page(request, id): ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() redirect('approvals:approve_pending', pk=approval.pk) else: form_approval = LeadApprovalForm() ... return render(request, 'approval_page.html', context) approval_page.html <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" action="{% url 'approvals:approve_pending' pk=approval.pk%}" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <button type="submit" class="btn btn-success btn-xs" onclick=" window.open('{% url 'approvals:approve_pending' pk=approval.pk%}', '_self');">Submit</button> <a href="{% url 'approvals:decline_pending' pk=approval.pk%}"> <button class="btn btn-danger btn-xs" id="approve-btn">Decline</button> </a> </form> approvals/views.py def approve_pending(request, pk): pending_approval = ApprovalProcess.objects.get(pk=pk) customer = pending_approval.doc_id.owner pdf = pending_approval.doc_id priority_number = 0 if request.user.rank.rank_name == 'Analyst': priority_number = 1 if request.user.rank.rank_name == 'Senior Analyst': priority_number = 2 if request.user.rank.rank_name == … -
Django on IIS WinServer 2012R2 with python 3.9 WSGI Handler error
I'm trying to setup an IIS website following this guide I'm getting the following error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Python39\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Python39\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Python39\Lib\site-packages\wfastcgi.py", line 586, in get_wsgi_handler raise Exception('WSGI_HANDLER env var must be set') Exception: WSGI_HANDLER env var must be set StdOut: StdErr: I believe the error might be on the web.config, which is the following: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python39\python.exe|C:\Python39\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django_project.wsgi.application" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\django_project" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="django_project.settings" /> </appSettings> </configuration> my folder structure is the following: C:\Python39\python.exe C:\Python39\Lib\site-packages\wfastcgi.py C:\inetpub\wwwroot\web.config C:\django_project that has the following: and I have created the FastCGI settings with: and Handler Mapping with: (the request restriction has the invoce box unticked) I don't know what else could I be missing to set here. -
Paypal Integration Django Rest Api/ Android Client
i am trying to implement a Paypal payment system. I am working with a Django Server API and my client is an android Kotlin app. My question is, where is the best spot to implement the paypal integration. Is it secure to implement it on the client side, because hackers could change the amount of money for example. But on the other hand how could I implement it server-side logically and the customer could use it on his mobile device. Thanks for help. -
how to perform some expression in django project
I am New In This python and Django i want to make some expression quary in my project active expire or expire soon how can i do that please help me here is my mosel class > def status_active_dactive(self): > recived_date = self.received_date > user_rec_date = recived_date.strftime("%m/%d/%Y") > time_today = datetime.datetime.now().date() > one_month = time_today + datetime.timedelta(days=30) > five_day = time_today + datetime.timedelta(days=1) > day_five = five_day.strftime("%m/%d/%Y") > month = one_month.strftime("%m/%d/%Y") > expire = "Expire in" > Active = "Active" > expire_soon = "Expire Soon" > if day_five >= user_rec_date != month: > return Active > elif day_five == user_rec_date != month: > return expire_soon -
How do I change the CheckboxSelectMultiple in django admin as side to side instead of stacked on top of each other?
I had to convert the default representation of Many-to-many fields from being represented as HTML to CheckboxSelectMultiple using : from django.forms import CheckboxSelectMultiple # Register your models here. class UserPreferenceAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {"widget": CheckboxSelectMultiple}, } admin.site.register(UserPreference, UserPreferenceAdmin) However the checkboxes are places on top of each other and I would like to stack them side to side. -
ValueError at /akolaprofile/ The view akola.views.akolaprofile didn't return an HttpResponse object. It returned None instead
I am trying to modify a user's username in his profile. I'm not using Django's User model and had created a custom user model (MyRegistration) by inheriting AbstractBaseUser. I have also assigned my custom user model to AUTH_USER_MODEL in the settings.py. But when I try to modify the user's profile details, it throws a ValueError stating that The view akola.views.akolaprofile didn't return an HttpResponse object. It returned None instead. What could possibly be wrong? Also, I want to understand why is_valid() function has been ditching me every time ever since I created my own user model. It just doesn't work in any form. Below are my codes: models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils import timezone from .manager import FirstManager #Making custom User model class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('Solapur', 'Solapur'), ('Latur', 'Latur'), ('Dhule', 'Dhule'), ('Akola', 'Akola'), ('Nashik', 'Nashik') ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default='Latur') designation=models.CharField(max_length=70) is_active=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username views.py: Line no. 7 here, print(fm.is_valid()) returns True in the terminal, still the code returns None. def akolaprofile(request): if request.user.is_authenticated: if request.method=='POST': print(request.POST) fm=ProfileForm(request.POST, instance=request.user) if fm.is_valid(): print(fm.is_valid()) fm.save() else: return HttpResponse('Not … -
Problem Overriding the save() method in Django
I have a peculiar type of model where table_fields needs to set to default depending on the value of its report_type field. class Report(models.Model): ALL_TABLE_FIELDS = ( 'local_ordered_date', 'card', 'country', 'customer', 'supplier', 'amount', 'currency', 'quantity', 'quantity_unit', 'invoice_total', 'payment_total', 'balance', 'owner', 'lost_reason', 'lost_description', 'result', 'local_result_updated_at', 'local_delivery_deadline', 'board', 'stage', 'order_number', 'product', 'incoterms', 'destination_port', 'loading_port', 'payment_terms', 'other_terms' ) DEFAULT_TABLE_FIELDS = { 'OrderTrendReport': ('card', 'board', 'customer', 'amount', 'currency', 'stage', 'owner', 'country', 'local_ordered_date', 'local_delivery_deadline', 'order_number'), 'RevenueTrendReport': ('card', 'customer', 'invoice_total', 'payment_total', 'balance', 'currency', 'owner', 'order_number', 'board'), 'DealSuccessRateReport': ('card', 'board', 'customer', 'amount', 'currency', 'owner', 'result', 'local_result_updated_at'), 'DealLostReasonReport': ('card', 'board', 'customer', 'amount', 'currency', 'owner', 'local_result_updated_at', 'lost_reason', 'lost_description'), 'OrderByCategoryReport': ('card', 'board', 'customer', 'amount', 'currency', 'stage', 'owner', 'country', 'local_ordered_date', 'local_delivery_deadline', 'order_number') } """ The proper way to set a field's default value to a function call/callable is to declare a function before the field and use it as a callable in default_value named arg https://stackoverflow.com/questions/12649659/how-to-set-a-django-model-fields-default-value-to-a-function-call-callable-e """ class ReportType(models.TextChoices): # hard-coded in order to avoid ImportError and AppRegistryNotReady OrderTrendReport = 'OrderTrendReport', 'Order Trend report' RevenueTrendReport = 'RevenueTrendReport', 'Revenue Trend report' DealSuccessRateReport = 'DealSuccessRateReport', 'Deal Success Rate report' DealLostReasonReport = 'DealLostReasonReport', 'Deal Lost Reason report' OrderByCategoryReport = 'OrderByCategoryReport', 'Order By Category report' user = models.ForeignKey(User, on_delete=models.CASCADE) report_type = models.CharField(choices=ReportType.choices, max_length=50, default=ReportType.OrderTrendReport) table_fields … -
How do I pass the " # " in url? Python, DRF [duplicate]
I have rest api that takes discord username as an query parameter, example: http://127.0.0.1:8000/api/users/?name=user#1236 And everything after " # " is ignored http://127.0.0.1:8000/api/users/?name=user#1236 is interpreted as http://127.0.0.1:8000/api/users/?name=user How do I fix this? Code: Discord command handler: @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$rank'): leaderboard = get_ranking(message.content, message.author) await message.channel.send(leaderboard) Function that is getting response from api def get_ranking(message, author): msg = message.split(' ') print(msg) leaderboard = '' link = None print(author) author.replace('#', '') if len(msg) > 1: link = f'http://127.0.0.1:8000/api/users/?name={author}&param={msg[1]}' else: link = f'http://127.0.0.1:8000/api/users/?name={author}' print('link', link) response = requests.get(link) json_data = json.loads(response.text) print('json_data', json_data) position = 1 if len(json_data) > 1: for user in json_data: leaderboard += str(position) + '. ' + user['name'] + ' points: ' + str(user['score']) + '\n' position += 1 else: leaderboard += str(position) + '. ' + json_data[0]['name'] + ' points: ' + str(json_data[0]['score']) + '\n' return leaderboard ModelViewSet returning queryset to api class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer def get_queryset(self): count = self.request.query_params.get('param', None) name = self.request.query_params.get('name', None) print(count) print(name) if count is not None: if count.isdigit(): queryset = UserProfile.objects.all()[:int(count)] else: queryset = UserProfile.objects.filter(name=name) elif name is not None: queryset = UserProfile.objects.filter(name=name) else: queryset = UserProfile.objects.all() print('dziala?', queryset) … -
'str' object has no attribute 'socialaccount_set' django allauth
I am trying to change my function based views to class based views I have this profile view as function based: @verified_email_required @login_required def profile(request, username): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid and p_form.is_valid(): u_form.save() p_form.save() message = messages.success(request, f'Your profile has been updated') return redirect('profile', username=username) else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) try: profile = User.objects.get(username=username) except User.DoesNotExist: message = messages.warning(request,f'Profile not found for {username}') return redirect('home') profile = '' all_post_by_user = Log.objects.filter(author__username=username) context = { 'u_form' : u_form, 'p_form' : p_form, 'profile' : profile, 'all_post_by_user' : all_post_by_user } return render(request, 'users/profile.html', context) And this is my class based for the same : class ProfileDetailView(DetailView): model = Profile template_name = "users/profile.html" context_object_name = 'profile' def get_object(self): username = self.kwargs.get('username') view_profile = Profile.objects.get(user__username=username) So, I am getting this error: profile.html: {% extends 'log/base.html' %} {% block content %} {% load socialaccount %} {% get_social_accounts profile as accounts %} {%load crispy_forms_tags %} <title>Error logger - Profile {{ profile.username }}</title> <div id='profile' class="content-section card p-4"> <div class="media"> {% if profile.username == user.username %} {% if accounts %} <img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" /> {% else %} <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url … -
Failing to build a Docker image from a Django project
I'm on Windows 10 Pro using Docker desktop, I'm NOT using Windows containers. ── Django_project ├── app │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt # < Python module list ├── Dockerfile # < Dockerfile used to build the image └── django_main # < Django main settings ├── settings.py ├── urls.py └── wsgi.py My Dockerfile: FROM python:3.8.8-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] CLI (Windows Power Shell): PS C:\Users\ATI\pycharmprojects\Django_project> docker build --tag django_project:latest . Requirementes.txt: asgiref==3.3.4 certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.7 defusedxml==0.7.1 Django==3.2 django-allauth==0.44.0 django-crum==0.7.9 django-extensions==3.1.3 django-invitations==1.9.3 idna==2.10 oauthlib==3.1.0 Pillow==8.2.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==20.0.1 python3-openid==3.2.0 pytz==2021.1 requests==2.25.1 requests-oauthlib==1.3.0 six==1.16.0 sqlparse==0.4.1 urllib3==1.26.4 Werkzeug==2.0.1 At step 5/6 RUN pip install -r requirements.txt I get the error, it fails to install crypthograpy Complete Traceback: #10 33.43 Collecting cryptography==3.4.7 #10 33.47 Downloading cryptography-3.4.7.tar.gz (546 kB) #10 33.89 Installing build dependencies: started #10 41.09 Installing build dependencies: finished … -
Django alluth DafaulAccountAdapter
I have a 1-1 model between custom user and profile. I use a default signup form with Django Alluth and have field from both user and profile model. The problem i have i that i want to raise a form validation if user pid is not unique. But when i try to override the DefaultAccountAdapter i cant manage to reference the field Pid. My question is, how can i reference the custom signup form field pid and use it in my custom AccountAdapter code? Custom signup form class CrewSignupForm(SignupForm): def __init__(self, *args, **kwargs): # Call the init of the parent class super().__init__(*args, **kwargs) self.fields[_("first_name")] = forms.CharField(required=True) self.fields[_("last_name")] = forms.CharField(required=True) self.fields[_("pid")] = SEPersonalIdentityNumberField(required=True) self.fields[_("org_nr")] = SEOrganisationNumberField(required=True) # Put in custom signup logic def custom_signup(self, request, user): # Set the user's type from th form reponse user.profile.pid = self.cleaned_data[_("pid")] user.first_name = self.cleaned_data[_("first_name")] user.last_name = self.cleaned_data[_("last_name")] user.profile.org_nr = self.cleaned_data[_("org_nr")] user.save() return user Default account adapter class CheckUniquePid(DefaultAccountAdapter): def clean_pid(self, user): pid = user.profile.pid data = User.objects.filter(profile__pid=pid).count() if data > 0: raise ValidationError('This user exists') return pid -
Charts.js Integration with Django having data in postgresql
I have data in postgresql database and I have made the connection with django by updating the settings.py file . I want to make a dashboard in which graphs can be displayed by charts.js. How can I make this integration possible that charts.js can pick the from django postgresql and display in charts.js? Looking for some smart solution. Thank you -
django class based view not rendering class based form
I have a simple app which asks a user if they have completed their hour task (such as getting up from the desk and streching) however, my form is not rendering and I'm non the wiser to why after debugging for a good while. models.py from django.db import models from django.contrib.auth import get_user_model class StrechesTracker(models.Model): id = models.AutoField( primary_key=True, editable=False ) excercise = models.BooleanField( choices=( (True,'Yes'), (False,'No') ) ) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True) def __str__(self) -> str: return self.excercise forms.py from django import forms from .models import StrechesTracker class StrechForm(forms.ModelForm): class Meta: model = StrechesTracker fields = '__all__' views.py from typing import Any, Dict from django.views.generic import CreateView from .models import StrechesTracker from .forms import StrechForm class TrackerView(CreateView): model = StrechesTracker form_class = StrechForm template_name = 'home.html' def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) return context def form_valid(self, form: StrechForm): return super().form_valid(form) home.html {% extends "_base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="jumbotron"> <h1>Done Hourly Streches?</h1> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" type="submit">Yes</button> </form> </div> {% endblock content %} -
Creating a xlsx file by using rest-pandas in DRF
I have rendered data in 3 format like (Xlsx,txt & Json) now I want if the client required data in Excel(.xlsx) format then the file has some predefined formating like column width or Headercolor and all. I tried to set column width like this but it doesn't work..please help **def get_pandas_args(self, data): import pdb; pdb.set_trace() writer = ExcelWriter(self.get_pandas_filename()) # Initialize with temp file # (Custom chart commands...) workbook = writer.book worksheet = writer.sheets['Sheet1'] worksheet.set_column('B:B', 50) writer.save() return [writer]** -
how can i do dynamically column in Django model ? can you provide one full simple example of this questions
column1 column2 column3 column4 column5 column6 user add in text box in our database insert column 7 -
django models, NOT NULL constraint failed on foreignKey, even tough i put null=True in my model class
I implemented the user model and authentication first and added some users to the database. Then i added two more fields to the models, "city" and "Company", and set foreignKey relations among them. It's ok if a user i create through admin site has no company/city, but if the user is created with a form, i want the field to be required. So i set null=True and blank=False. This is my complete models.py file: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import MinLengthValidator class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, rollNo, password=None): if not email: raise ValueError("Users must have an email") if not rollNo: raise ValueError("Users must have a roll number") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") user = self.model( first_name=first_name, last_name=last_name, email=self.normalize_email(email), rollNo=rollNo ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, is_current, password): user = self.model( is_current=is_current, first_name=first_name, last_name=last_name, email=self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.set_password(password) user.save(using=self._db) return user class Company(models.Model): name = models.CharField(max_length=50, default="NAME") people = models.ManyToManyField('Person', default=None, related_name='employes', null=True) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=50, default="NAME") companies = … -
How to save Username instead of Object name(None) automatically while saving the model in django
When I save the model, The object name is None, but I need to save the username instead of object name (None) automatically while I saving the Model here is pic of admin site Models.py class solo_21_6_2021(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) player1_pubg_id = models.PositiveIntegerField(null=True,blank=True) player1_pubg_name = models.CharField(max_length=15,null=True,blank=True) def __str__(self): return str(self.user) Views.py def solo(request): form = SoloForm() if request.method=="POST": form=SoloForm(request.POST) if form.is_valid(): form.save() return render(request, 'bgmiapp/solo.html',{'form':form}) Forms.py class SoloForm(forms.ModelForm): class Meta(): model = solo_21_6_2021 fields=['player1_pubg_id','player1_pubg_name' Admin.py class SoloAdmin(admin.ModelAdmin): list_display = ('user','player1_pubg_id','player1_pubg_name') admin.site.register(Profile) admin.site.register(solo_21_6_2021,SoloAdmin) -
why my remote server not able to connect to postgres instance on another Django server?
I have two Ubuntu server A and B. Initially I had Django, postgres, celery on single server A. Everything was working fine. Now A has Django, postgres, and B has celery and Django project installed. DB migrations are done on A, and database connectivity is proper on A. This I can say that because when I am trying to start the celery server on server A, I am able to successfully launch the celery through the command prompt. No problem. As per the requirements, I have to only run Django and postgres on server A, and Celery on server B. Since I am using the same Django server settings on server B that I have in A, so the Django settings.py has the same DB connectivity settings as shown below. i.e. the DB settings are same on A and B DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xyz', 'USER': 'smthing', 'PASSWORD': 'smthing', 'HOST': 'some_IP', 'PORT': '5432', } } To see if the postgres is running or not on server A. I executed the service command $ service postgresql status ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Thu 2021-06-10 10:57:11 IST; … -
TypeError: string indices must be integers django
I want to know what kind of data should I send to django-rest-framework and dont get the string indices must be integers ? the function is @permission_classes((IsAuthenticated,)) def update_interests(request): user_profile = request.user.userprofile interests = request.data user_profile.interests.set( TopicTag.objects.get(name=interest['name'])[0] for interest in interests ) user_profile.save() serializer = UserProfileSerializer(user_profile, many=False) return Response(serializer.data) the error is typeError: string indices must be integers and the data I have send is a json { "name": ["news"] } just in case the models.py looks like this class TopicTag(models.Model): name = models.CharField(primary_key=True, max_length=150, null=False, blank=False) def __str__(self): return self.name maybe you need the serializers so here you are class TopicTagSerializer(serializers.ModelSerializer): class Meta: model = TopicTag fields = '__all__' help me :) -
Sending data and query to 'base.html' for an app in Django
How can I pass data from db in base.html in Django? My example view: def staff_base(request): messages_count = Message.objects.filter(read=False).count() ctx = {'messages_count':messages_count} return render(request, 'staff/base.html', ctx) It doesn't work