Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Send email for new model object create
I want to send email if user placed a new order. I want to do the send email function from my models.py. Is it possible?? I setup my settings.py for email. I am looking for a easiest way to do this. I don't want to touch my views so is it possible? #this is my Order model class Order(models.Model): PENDING_PAYMENT = 'Pending Payment' ON_HOLD = 'On Hold' status_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] orderstatus_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] Ordinary = 'Ordinary' customer_choices = [ ('Ordinary', 'Ordinary'), ('Police', 'Police'), ('RAB', 'RAB'), ('DGIF', 'DGIF'), ('CID', 'CID'), ('NAVY', 'NAVY'), ('Air Force', 'Air Force'), ('Army', 'Army'), ('DB', 'DB'), ('Administration', 'Administration'), ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) shippingPrice = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) totalPrice = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) isDelivered = models.BooleanField(default=False) deliverAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=220, choices=status_choices, default=PENDING_PAYMENT) orderStatus= models.CharField(max_length=220, choices=orderstatus_choices, default=ON_HOLD, … -
UsZipCode --> Input -> (zipcode, radius) output -> (List of Zipcodes)
This is what I have tried from this search = SearchEngine() search.query(zipcode="74104", radius="30", returns=5) this returns [SimpleZipcode(zipcode='74104', zipcode_type='Standard', major_city='Tulsa', post_office_city='Tulsa, OK', common_city_list=['Tulsa'], county='Tulsa County', state='OK', lat=36.15, lng=-95.96, timezone='Central', radius_in_miles=1.0, area_code_list=['918'], population=12724, population_density=4673.0, land_area_in_sqmi=2.72, water_area_in_sqmi=0.0, housing_units=6606, occupied_housing_units=5794, median_home_value=136200, median_household_income=36848, bounds_west=-95.970417, bounds_east=-95.940281, bounds_north=36.160214, bounds_south=36.13323)] If I specify radius as an int search = SearchEngine() search.query(zipcode="74104", radius=30, returns=5) I get You can either specify all of lat, lng, radius or none of them Not sure what I am doing wrong -
OSError: cannot load library 'gobject-2.0-0'
I am currently implementing code that can print my database outputs to a pdf file. The following error (Title) is given when I do 'manage.py runserver' I have just installed weasyprint and imported HTML from it in the top of my views file , as per the below: Views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum def home(request): return render(request , 'main/home.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink … -
django - How to display a form in a modal window?
On the details page of a particular object (in my case, 'TrimType'), I want to display the create form when I press the 'Create' button, and the update form when I press the 'Update' button in one modal window. Does it need multiple url/view for the modal window that displays the Create or Update form? Or is it possible in single url/view? I implemented it in a single url/view, create works well, but it doesn't work as an update function. How do I implement views.py? models.py: class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True,) typeName = models.CharField(max_length=50, blank=False, null=False) forms.py: class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) detail_view.html: <div class="text-right mt-3 mb-3"> <a href="" id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">add</a> <a href="" id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">modify</a> </div> {% include 'modal_form.html' %} modal_form.html: <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">TrimType</h3> <form method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.errors }}</p> <input type="hidden" name="car" value="{{ carID }}"> <div … -
Increment Integer Field only once per post
I am building a Blog App And I am implemented a feature of , When user edit a post then it will add +1 point in the User Profile's Integer Field. Everything is working fine But Integer Field is increasing every time I refresh the page. And I am trying to add only +1 point in it. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') full_name = models.CharField(max_length=30,default='') edited_count = models.IntegerField(default=0) class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') blog_post_edited_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post_edited_by') views.py def blog_post_detail_view(request,blogpost_id): post = get_object_or_404(BlogPost,id=blogpost_id) post_edited_by = post.blog_post_edited_by if post_edited_by == request.user: request.user.profile.edited_count += 1 request.user.profile.save() context = {'post':post} return render(request, 'blog_post_detail_view.html', context} What have i tried ? I have also tried using Boolean Field if user is awarded +1 point then it will turn to False, But it will create a problem, I mean I am awarding user in every edit But it will only award once every time. I have also tried by awarding +1 point in Edit Form like :- def edit_blogpost(request,blogpost_id): post = BlogPost.objects.get(id=blogpost_id) if request.method != 'POST': form = BlogPostEditForm(request.POST or None, request.FILES or None, instance=post) else: form = BlogPostEditForm( instance=post, data=request.POST, files=request.FILES) if … -
How to write Elasticsearch query in elasticsearch_dsl in python
I am newbie in Python Django and could not get started though I have seen basic documentations at https://www.elastic.co/guide/en/elasticsearch/reference/6.8/query-dsl.html Here is my Elasticsearch query api for aggregation curl -X POST "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d' { "aggs": { "imei_count": { "cardinality": { "field": "imei" } } } } ' Explanation of code block is welcome. Thanks -
Call a specific custom migration operation whenever a model is created
I am trying to implement this, http://docs.citusdata.com/en/v10.1/develop/migration_mt_django.html#:~:text=4.%20Distribute%20data,tenant_migrations.Distribute(%27Task%27)%2C%0A%20%20%5D Since I cannot hard code this operation for hundreds of models, I am wondering whether there is a way to automate this "make migration" whenever a model is created and me specifying the "reference" attribute in the model's meta class. Thank you -
Django unit test taking a long time to run
I tried different approaches like python manage.py test --keepdband creating a separate test database. I'm getting an error -: Using existing test database for alias 'default'... Got an error creating the test database: (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 'CREATE DATABASE IF NOT EXISTS `test_b2b ;\n SET sql_notes = @' at line 2") I'm using MySQL as a database. -
How to add a js without static folder un django
So I have a html template in Django and I want to include it with some js but I don't want my js to be in my static folder and I don't want to let any users in my site view that Javascript by going to any url so it it possible to that in django? -
Django - How to add access token to Client.post in Django test?
So I have some code below. Every endpoint has an authentication process, which is below as well. I want to be able to attach an access token, which is in cls.user to the Client.post so that I can test all the endpoints and ensure they are authenticating properly as well. How can I do this? So ideally I'd be attaching <bearer> <access token> to request.Meta['HTTP_AUTHORIZATION'] test.py import json from cheers.models import * from warrant import Cognito from django.urls import reverse from django.test import TestCase from rest_framework import status from cheers.models import GoalCategory, Post from dummy_factory.Factories import UserFactory, GoalFactory class PostTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.goal_category = 'health' GoalCategory.objects.create(category=cls.goal_category, emoji_url='url') cls.user = UserFactory() cls.goal = GoalFactory() user_obj = User.objects.get(pk=cls.user.phone_number) goal_obj = Goal.objects.get(pk=cls.goal.uuid) Post.objects.create(creator_id=user_obj, goal_id=goal_obj, body='Some text') cls.user = Cognito(<Some login credentials>) cls.user.authenticate(password=<password>) def test_create(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) Test authenticator function def cognito_authenticator(view_func): def wrapped_view(request, *args, **kwargs): # Check the cognito token from the request. token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] try: jwt.decode_cognito_jwt(token) except Exception: # Fail if invalid return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) # Or HttpResponseForbidden() else: # Proceed with the view … -
Django ModelChoiceField initial value is not showing up while editting
I have an form "ModelChoiceField" form field, and when adding the data it works fine ! But how to retrieve the saved data database to get selected when the form is edited ? form = AddForm(owner=pk, instance=data, initial={'course': data.course}) I even tried setting initial value, but still am not getting to selected value to get displayed ! class AddForm(ModelForm(: def __init__(self, owner, *args, **kwargs): super(AddForm, self).__init__(*args, **kwargs) self.fields['course'].queryset = Faculty.objects.filter(owner=owner) And note, that the selected values are correctly getting saved on database ! But its not showing up -
Continuous cycling through all objects in a table with django
As a learner of the django framework, I face the challenge of looping through all primary keys of a table, beginning with the first, and at the end of the sequence, to start all over again. The id field is an auto-incrementing serial field in postgres. A very basic breakdown of the project is as follows: models.py ... class Event(models.Model): id = models.BigAutoField(primary_key=True) event_name = models.BigIntegerField(blank=True, null=False) timestamp = models.DateTimeField(blank=True, null=True) viewed = models.BooleanField(default=False) views.py def home(request, id=None): from .models import Event first_obj = Event.objects.order_by('id').first() my_json = serialize('json', first_obj, fields=('event_name', 'timestamp')) return render(request, 'home.html', {'items': my_json}) def confirm(request): #set viewed=True on current object .save() return redirect('home') #move to next object home.html ... <form method="POST" action="{% url 'confirm' %}"> <button>confirm</button> </form> ... The idea is to send the my_json object to an html template. A user clicks a button, which should then mark the current object as viewed (sets viewed from False to True), then the next object should be fetched (by incremental primary key), and so on. If it has reached the last object, the first object (pk=1) should be fetched next, and the cycle continues. I would like to avoid making ajax requests and think a second url would … -
Is it possible to list out a range of values in the database?
Let's say I have a form that has 2 fields, First and Last. For example, the input for First: 1 and Last : 5. Upon saving: It saves the range: 1, 2, 3, 4, 5 and stored under a single field (Num) in a database table called (Numbers), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 It saves the First and Last values in a table called Range. Using a view (Django) and somehow uses the numbers of 1 & 5 and derive the range of 1, 2, 3, 4, 5 and stored in another table (Numbers) where under the field (Num), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 Which is possible? And how do i do it? Appreciate it for any help provided -
How to use Django rest framework query parameters
I'm trying to create an API with Django and I'm having a hard time understanding how query string parameters work: So far I created an endpoint which gives out a list of products and know I want to be able to filter those products by name like /api/Products/name=guitar or any equivalent of /api/Products?name=guitar I created this view and serializer: serializer_class = ProductSerializer def get_queryset(self): queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) limit 12') name = self.request.query_params.get('name') if name is not None: queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) where name like \'%{name}%\' limit 12') return queryset And this is my urls.py: router = routers.DefaultRouter() router.register(r'Products', views.ProductView, 'Products') router.register(r'Products/(?P<name>.+)/$', views.ProductView, 'ProductsSearch') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] This doesn't crash but for /api/Products/guitar/ I get nothing back. I also tried /api/Products/?name=guitar/ and that throws an error. Thanks! -
django unable to save req body to sqlitedb
I have a nitpicky problem with my Django rest api, I'm using postman to POST in some basic information as raw json then make an instance of the model 'Planet' then store it in the sqlite db that comes with django as standard, I'm getting a 200 response but it is failing the try block for some weird reason?, I have tried changing the param values and also the model data types but it doesn't seem to fix it, there are no errors server side either hoping someone can point out my logic error here :) Model class class Planet(models.Model): name = models.CharField(max_length=20) temp = models.CharField(max_length=20) hrs = models.CharField(max_length=20) mass = models.CharField(max_length=20) diameter = models.CharField(max_length=20) circumference = models.CharField(max_length=20) def add_planet(request): if request.method == 'POST': payload = json.loads(request.body) planet_name = payload['name'] avg_temp = payload['temp'] day_hrs = payload['hrs'] planet_mass = payload['mass'] planet_diameter = payload['diameter'] planet_circumference = payload['circumference'] //data prints out correctly here print(planet_name,avg_temp,day_hrs,planet_mass,planet_diameter,planet_circumference) planet = Planet(name=planet_name,temp=avg_temp,hrs=day_hrs,mass=planet_mass, diameter=planet_diameter, circumference=planet_circumference) try: planet.save() response = json.dumps([{ 'Success': 'Planet added successfully!'}]) except: response = json.dumps([{ 'Error': 'Planet could not be added!'}]) return HttpResponse(response, content_type='text/json') here is my json body being sent in postman, I'm using POST and raw json as my option as I don't have … -
Unable to verify email while using simple JWT in django
The register and login sections are functioning properly in my django application. When someone registers he receives a confirmation email, but on clicking the email confirmation link the account is not verified. I'm using try and except, it's the except that is being executed each time and try never executes. models.py username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) views.py serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: key = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=key['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({'email': 'Your email has been activated'}, status=status.HTTP_200_OK) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'token not valid'}, status=status.HTTP_400_BAD_REQUEST) Please I want to know why the the code in the try section never gets executed even when the token is intact and has not expired. -
How to implement only one user session to perform specific task in my django application
I have a application, in that one page has form submit operation which writes a data to data base, I want this submit operation to perform by only one user session at a time, if other user submitted it must show , please wait some user is performing operation like that, please suggest here. -
Can't access django admin anymore
I can no longer access my admin page after the last migration I made. All I did was add a foreign field connecting two models (Listing and User). I am getting the message: “C:... Django\commerce\media\admin” does not exist I did a lot of searching but all I came up with was to delete 'django.contrib.sites', or to add it instead while setting SITE_ID equal to 1. There was also the suggestion to put: from django.contrib.sites.models import Site Site.objects.create(pk=1, domain='localhost', name='localhost') into python shell. None of these things worked for me. For some reason django seems to be searching in my media folder but I have no idea why it would do that. My settings: """ Django settings for commerce project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Disable image-cleanup in Django
I create a few badge for users. I using django-CleanUp for delete other media objects. When user's score high enough I want change old badge to new badge. But when change images, old image(badge) is deleted. I dont want this. I want keep old badge because is still used other users My Views: def liked_post(request, pk): user_update = get_object_or_404(UserRanks, user = post.username) if user_update.score < 50: user_update.rank_image = "guard.gif" elif user_update.score < 100: user_update.rank_image = "captain1.gif" elif user_update.score < 300: user_update.rank_image = "knight1.gif" user_update.save() my Models: class UserRanks(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) rank_image = models.ImageField( verbose_name="Rank Gif", default="guard.gif", null=True, blank=True) score = models.IntegerField( null=True, blank=True, verbose_name="Score", default=0) def save(self, *args, **kwargs): super(UserRanks, self).save(*args, **kwargs) is there a way to do keep old image without remove the django-clean-up? -
Django email verification link redirect to last page rather than set url
I have a django website where a user can select "sign up" from many different pages with many different urls. I want the authorization link they receive to return them to the page they were at, rather than some set page. My set up is as follows: *** using default Abstract User class urls.py urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('activate/<uid>/<token>/', ActivateAccount.as_view(), name='activate'), ] ***using default django login/registration with custom templates registration/signup.html {% extends 'gitrepo/base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign Up</h2> <p>Register using your username. <br> You will be asked to verify your email.</p> <form method="post"> {% csrf_token %} {{ form.as_p }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next}}"> {% endif %} <button type="submit">Sign Up</button> </form> <p><b> {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div> {% endfor %} {% endif %} </b></p> {% endblock %} *** this queries an ldap to get the user's email in the following views.py User = get_user_model() class SignUpView(View): form_class = UserCreationForm template_name = 'registration/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, … -
how do I get my altair plot from views to render on my html page in Django?
I am trying to get my Altair plot to render from my views to my html page. I have tried everything from stack overflow to get this to work, but every time I try I don't get my plot. This is my code in the different sections. Views.py: def search_site(request): if request.method == "POST": inputSite = request.POST.get('Site') SITES = Ericsson_LTE_1D_Version_Sectir_ID_HOUR.objects.filter(SITE__contains = inputSite).values() data = pd.DataFrame(SITES) chart = alt.Chart(data).mark_line().encode( y ='Avg_Nr_Of_RRC_Connected_Users:Q', x ='PERIOD_START_TIME:T', ).to_json(indent=None) return render(request,'VenueReporting/searchSite.html', {'site':inputSite,'Predictions':SITES,'chart':chart}) else: return render(request, 'VenueReporting/searchSite.html',{}) HTML Page: <head> <script src="https://cdn.jsdelivr.net/npm/vega@[VERSION]"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@[VERSION]"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@[VERSION]"></script> </head> <body> <script type="text/javascript"> var chart = "{{chart}}"; vegaEmbed('#vis1', chart).then(result => console.log(result)) .catch(console.warn); </script> {% if Predictions %} <h2>You Searched for:</h2> <h3>{{site}}</h3> <h2>The activity was:</h2> <div id="vis1"></div> {% else %} <h1>That Venue does not exist or you put the wrong information</h1> {% endif %} </body> -
How to add the valid css class for form field?
Is there an opposite equivalent for error_css_class in forms class/template? I cannot find a way to add a valid class only after validation. -
Django forms retrieve unique list
just wanted to know how to reference a unique list from a models field. Here is the forms: Defect_Area_Associate = forms.ChoiceField(choices=[("%s" % dv['pk'], "%s" % dv['Defect_Area_dv']) for dv in dv_model.objects.all().values('pk', 'Defect_Area_dv')], widget=forms.Select) I want to be able to get only the unique list of "Defect_Area_dv". I tried calling .unique() but cant figure what change to make... Hope someone can help me with that. -
Get Fatal Python error: Module Not Found: No module named encoding
I am trying to get my Apache Web Server to run my Django page using wsgi.py. My virtual environment is at /var/www/myapp/myapp_root/myapp. When I activate the virtual environment I see my user home directory being used. I tried the following wsgi.py changes: """ WSGI config for trackx project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os,sys sys.path.append('/home/myuserid/.local/share/virtualenvs/lib/python3.9/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trackx.settings') application = get_wsgi_application() When I try to start the server - it gives me the following repeating error (over and over): Python path configuration: PYTHONHOME = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/local/bin/python3' sys.base_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.base_exec_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.executable = '/usr/local/bin/python3' sys.prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.exec_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.path = [ '/home/my-user/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python38.zip', '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python3.8', '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f52bfd07880 (most recent call first): <no Python frame> My WSGI settings in the http.conf file look like this... WSGIPythonHome /var/www/myapp/myapp_root/venv WSGIPythonPath /var/www/myapp/myapp_root/venv/lib/python3.9/site-packages WSGIDaemonProcess … -
'NoneType' object has no attribute 'id'. Django Admin
Here is my model and my admin code. Whenever I create a group without a headman I've got this error when Im reaching Groups page in admin -'NoneType' object has no attribute 'id'. What should I change? @admin.register(Group) class GroupAdmin(admin.ModelAdmin): list_display = ("descipline", "hours_to_take", 'link_to_curator', "link_to_headman") list_filter = ("descipline", "hours_to_take") search_fields = ("descipline__startswith", ) list_display_links = ['link_to_curator', 'link_to_headman'] def link_to_headman(self, obj): link = reverse("admin:students_student_change", args=[obj.headman.id]) return format_html(u'<a href="%s">%s<a/>' % (link,obj.headman.last_name)) class Group(models.Model): descipline = models.CharField(max_length=200) hours_to_take = models.IntegerField(default=32) headman = models.ForeignKey('students.Student',blank=True, null=True, unique=False, on_delete=models.CASCADE, related_name="headed_group") curator = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True,)