Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
should django modal have a separate view?
I am working on an application that has a page with a table that is a list of users. Each user has a button which pops up a modal that does something. I am trying to create the modal that will get the user information when the button in clicked, additionally, I need in that modal some logic based on the user information and some more data. I am thinking that it makes sense to create a separate view for it but since each view must be on a different url, the concept of the modal does not makes sense (for me), because I want it to be on the same url. Is it possible to have a modal with a different view that will have a separate logic? Since the modal is included in the template and it is basically just one template, then, can one template have 2 views? What is the best way to implement the modal using django? And how to pass data to it, I need the data from the row that was selected + some more data from db. I have the data from the context but manipulating that using JQuery for me is … -
Django: save history of all changes of a model to Splunk
I have the model Item. Whenever I update data in Item, I would like to send the data to Splunk (for tracking history of all changes). Would anyone suggest me how to deal with this? Thank you so much. -
How to assign a rule in django
I am working on a django project. where there's two table one is developer table and another one is Jira table. developer table and jira table are connected with m2m relation. here's my model.py class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) Now my query is how to set a rule where if Dx4c object is changing then automatically one developer will assign based on the rule? here's my view.py def dependency_management(request): jira_story = jira.objects.all() return render(request, 'hello/Dependency_Management.html', {'JIRA': jira_story}) I want to make that dynamic. I mean if everytime I add any new DX4C object then without the code change that particular developer will assign based on the rule -
Django static file not loading. Bad error message
I tried loading style.css in static file but it wouldn't work. I made sure to configure STATIC files in settings.py like this STATIC_URL = '/static/' STATICFILES_DIR = [str(BASE_DIR.joinpath('static'))] All my paths are correct and I loaded static. I cleared my cookies and the CSS still wouldn't work. -
How to resolve url to method or view in flask
Coming from django background I'm trying to get method for a specific url in flask. In django, from django.urls import resolve resolve("/hello_world/") # returns view asssociated /hello_world/ Is there is simlillar kind of functionality is available with flask that can return method against url? -
ImportError while importing models in a different file in same directory
I am new to Django and I am enjoying it a lot. But, yesterday I tried splitting views into different files, but importing the model in that new file shows ImportError: attempted relative import with no known parent package. I am using the same statement as in view from .models import Email And they are in the same directory. I even tried from models import Email but it says the same ImportError: attempted relative import with no known parent package -
why am I getting a 404 when looking for the id of an object django
I cannot get the liftview to work, the test page is working fine. Am I missing an import into the views? I have data in the database with an id of 1 (picture included to show). #polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('test', views.test, name='test'), path('<int:lift_id>/', views.liftview, name='liftview'), ] #views.py from django.http import HttpResponse def liftview(request, lift_id): return HttpResponse("lift id") def test(request): return HttpResponse("test") #models.py import datetime from django.db import models from django.utils import timezone class Lift(models.Model): lift_name = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') def __str__(self): return self.lift_name ==traceback== Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/liftview Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ polls/ [name='index'] polls/ test [name='test'] polls/ <int:lift_id>/ [name='liftview'] The current path, polls/1/liftview, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. there is data w/an id of 1.. database contents -
How to add raw_id_fields in Content Type object model : Django
I want to add raw_id_fields in django admin for a ContentType object model.How to do it ? models.py class TestList(models.Model): title = models.CharField(max_length=20) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="content_type") object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') -
Django Moving Models
I have a django application I'm trying to refactor. There's a million and five ways it seems to migrate models from an existing django app to a new one however I wanted to run by what seems like the easiest solution. Let's say my current application is called 'main-app' in said application i have a model 'user'. This would create a table called 'main-app_user' or something similar. Let's say I want to move the user model to a new app 'core', some tutorials state this is as easy as pointing the new model to the old table like so class User(models.Model): ... class Meta: db_table = 'main-app_user' I was curious if there was any catch to this I suppose? Many tutorial make this way more complicated so I'm curious why this isn't just the de-facto solution or if there are any drawbacks to this vs others. Thank you in advance! -
I don't know what is wrong but my Django app isn't working I was studying a new course so any help please
this my view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('hello world') this my sub-app URLs from . import views from django.urls import path urlpatterns = [ path ('', views.index,name='index'), ] This my Django-main App urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('food/',include('food.urls')), ] and browser is displaying this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/food Using the URLconf defined in firstapp.urls, Django tried these URL patterns, in this order: admin/ The current path, food, didn’t match any of these. I am using Django -- 3.2.4 but the course that I am studying is using the 2.2.2 version