Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
prevent sql duplicates by inline formset factory in django 3.0.5
i have a problem with inline formset factory in django 3.0.5. i have models like this: class Resume(models.Model): user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) website = models.URLField(verbose_name=_('Web Site'), blank=True, null=True) ... class Expertise(models.Model): name = models.CharField(_('name'), max_length=100) ... class ResumeExpertise(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='resume_expertise') expertise = models.OneToOneField(Expertise, on_delete=models.CASCADE, verbose_name=_('Expertise'), related_name='resume_expertise_item') score = models.PositiveSmallIntegerField(_('Score')) def __str__(self): return self.expertise.name in this case user must edit the form. i used inline formset factory. my forms.py: class ResumeForm(forms.ModelForm): class Meta: model = Resume fields = ('website',) def __init__(self, *args, **kwargs): super(ResumeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('website'), Fieldset('Expertise', Formset('expertise')), HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) class ResumeExpertiseForm(forms.ModelForm): class Meta: model = ResumeExpertise fields = ('expertise', 'score') ResumeExpertiseFormSet = inlineformset_factory(Resume, ResumeExpertise, form=ResumeExpertiseForm, fields=['expertise', 'score'], extra=1, can_delete=True) for views i used class based views like this: class ResumeEdit(LoginRequiredMixin, UpdateView): model = Resume template_name = "user/resume_form.html" form_class = ResumeForm success_url = reverse_lazy('user:profile') def get_object(self, queryset=None): return Resume.objects.get(user=self.request.user) def get_context_data(self, *args, **kwargs): context = super(ResumeEdit, self).get_context_data(**kwargs) context['title'] = _('Edit Resume') if self.request.POST: context['expertise'] = ResumeExpertiseFormSet(self.request.POST, instance=self.object) else: context['expertise'] = ResumeExpertiseFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() expertise = context['expertise'] with … -
Differentiate access to the post based on a user's type
I'm developing a blog and I need a differentiate access to the post based on a user's type. If the post is a draft only the staff user can read it, otherwise everyone can read it. I've this code into a views.py: geopost_filter = GeoPost.objects.filter(Q(draft=False) and Q(publishing_date__lte=timezone.now())) def single_geopost(request, slug_post): if request.user.is_staff: geopost = get_object_or_404(GeoPost, slug_post=slug_post) else: geopost = get_object_or_404(geopost_filter, slug_post=slug_post) context = { "post": geopost, } template = 'geoblog/single_geopost.html' return render(request, template, context) This function doesn't run because I can read the post whether I'm a staff member or a simple user. Where am I wrong? -
Update ManytoMany relationship in Django Rest Framework
In my django application I have a ManytoMany relationship between Orders and Packages. An order can have multiple packages. I want to know about the update and create methods Models.py class Package(models.Model): prod_name = models.CharField(max_length=255, default=0) quantity = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) class Orders(models.Model): order_id = models.CharField(max_length=255, default=0) package = models.ManyToManyField(Package) is_cod = models.BooleanField(default=False) Serializers.py class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = "__all__" class OrderSerializer(serializers.ModelSerializer): package = PackageSerializer(many=True) class Meta: model = Orders fields = "__all__" Views.py class OrdersCreateAPIView(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = OrderSerializer def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is that sufficient to handle the related data? I am trying to understand ManytoMany relationship both in Django as well as DRF so please explain if I need to change the Models or views in anyway -
How to let users edit images like adding filters or cropping from frontend using Django?
I want to make a webpage using django backend where users can edit images the moment they upload like in Instagram or other similar websites. How to do it? Any suggestions or are there any procedures to follow? Any leads would be appreciated. Thanks in advance! -
Why can't Django class based view access a template?
I have a detailview like this: class PatientDetailView(DetailView): model=Patient template_name = 'patient_detail.html' def get_context_data(self, **kwargs): context = super(PatientDetailView, self).get_context_data(**kwargs) context['form'] = PastLocationForm return context And I get an error as django.template.exceptions.TemplateDoesNotExist: patient_detail however, path to my templates folder is defined in settings.py and I don't have an import issue to any my templates other than here. To solve the problem, I tried to manually import the template as: from ..templates.covidapp import patient_detail and I receive ValueError: attempted relative import beyond top-level package -
Django how to add a timestamp value to a database from a view function?
What i would like to do in the Initial Report Function is to get the timestamp value when the emails are sent and store that value in a database. I would appreciate the help The view function def Initial_Report(request): #Gets email addresses and sends report noc_emails = Employee.objects.exclude(Position__Position__contains='Customer').values_list('Email', flat=True) cs_emails = Employee.objects.filter(Position__Position__contains = 'Customer').values_list('Email', flat=True) initialTime = datetime.now() noc_message = ('Initial Outage Report', 'This is a new outage report, The information is in the document' , 'from@example.com', noc_emails) cs_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', cs_emails) send_mass_mail((noc_message,cs_message), fail_silently=False) return render(request,'InitialReport.html') Models class Outage_Dates(models.Model): Report_ID = models.CharField(max_length=30,primary_key = True, unique =True) Outage_Begining = models.DateTimeField() def __str__(self): return self.Report_ID + ' ' + str(self.Outage_Begining) -
Comment Form not posting on submit in django
I have a blog site in progress, the submit form for the comment is redirecting to /post unexpectedly. error/output: before clicking submit <WSGIRequest: GET '/post/2'> -# my print statement in views.py fail -# my print statement in views.py [01/May/2020 11:28:43] "GET /post/2 HTTP/1.1" 200 14275 on clicking submit Not Found: /post/ [2020-05-01 11:33:39,126] log: WARNING - Not Found: /post/ [01/May/2020 11:33:39] "POST /post/ HTTP/1.1" 404 2795 submit button is type submit and here is everything related to it, I have been stuck on this for a while now. And I have added print() in views.py to find where the problem is. Help would be appreciated post.html <form method="POST" action="." class="commenting-form"> {% csrf_token %} <div class="row"> <div class="form-group col-md-12"> {{ form }} </div> <div class="form-group col-md-12"> <button type="submit" class="btn btn-secondary">Submit Comment</button> </div> </div> </form> views.py def postview(request, my_id): most_recent = Posts.objects.order_by('-timestamp')[:3] category_count = get_category_count() post = get_object_or_404(Posts, id=my_id) form = CommentForm(request.POST or None) print(request) if request.method == "POST": print(form) if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() print(form) return redirect(reverse('postdetail', kwargs={ 'my_id': post.pk })) else: print('fail') context = { 'post': post, 'most_recent': most_recent, 'cat_count': category_count, 'form': form } return render(request, 'post.html', context) models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp … -
How to search items using multiple model fields
My search function currently looks like that: query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) | item_list.filter( bike__brand__name__icontains=query) | item_list.filter( accessory__brand_accessory__name__icontains=query) | item_list.filter( bikepart__brand_part__name__icontains=query) I can filter my items using single fields, but I am looking for a filter that can look up items using multiple fields. My items are divided into 4 different models. Item model is a main model, that holds all titles for other models, that are connected to this main model, which are: Bike, Accessory and BikePart. I am looking for filtering using (title__icontains=query + bike__brand__name__icontains=query), (title__icontains=query + accessory__brand_accessory__name__icontains=query), (title__icontains=query + bikepart__brand_part__name__icontains=query) , but I still wanna be able to look up items by using just a title or just brand. What would be the best way to achieve that? -
I want to show stars based on an array element that is passed as a parameter to my template
So I was trying to loop over an array element which id {{doctor.16}} but I couldn't so I thought I could make it as if conditions but I failed to do this too so can anyone please help me? this is what I have done so far <div class="row"> <div class="col-lg-12"> <div class="single_jobs white-bg d-flex justify-content-between" style="width: 50px"> <div class="single_candidates text-center"> {% for doctor in recdoc %} <div class="thumb"> <img class="img-circle " src="{% static 'static_file/img/candiateds/2.png' %}" alt="" > </div> <a href="" ><h4 >{{doctor.6}} {{doctor.7}}</h4></a> <p> {{doctor.9}}</p> <div class="best-rating"> <div class="text-warning"> {% if{{doctor.16}} == 1 %} <i class="fa fa-star"></i> {% endif %} </div> <div class="best-rating" > <h5>تقييم الدكتور</h5> </div> </div> {% endfor %} </div> </div> </div> </div> </div> what I can't do correctly is this part {% if{{doctor.16}} == 1 %} <i class="fa fa-star"></i> {% endif %} -
Display validation errors in the same style as cripsy error messages
I'm using crispy forms to make my forms look nice and added the following validation: if age < 14: raise forms.ValidationError('Sorry, you must be atleast 14 years old to study with IPC IELTS') elif age > 110: raise forms.ValidationError('You entered a date of birth outside of the accepted range. Please try again') return data My problem is that this error message displays at the top of the page as a flash message, while other messages (which i did not set but are built into crispy, such as when a user leaves a required field blank) are displayed as a pop up message box under the field the errors related to. I am wondering how I can make my added validation error appear the same as other in-built crispy error messages, for consistency. Thank you. -
Filter data on the basis for ForeignKey in django
I've three types of model as show below and now I want to apply filter on them. I want to filter list of all the category from foodItem containing takeaway, dine_in, function separately. I want to filter list of sub_category containing category I want to filter list of food item containing subcategory. For the more clarification, I want to filter food item in hierarchal approach. I've also attached a screenshot, How I want to display my data, and sorry for my poor english. class FoodCategory(TimeStampWithCreator): title = models.CharField(max_length=55) class FoodSubCategory(TimeStampWithCreator): title = models.CharField(max_length=55) class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) sub_category = models.ForeignKey(FoodSubCategory, on_delete=models.CASCADE) title = models.CharField(max_length=55) I want to display data in frontend like this. -
Middleware Setup
I am trying to setup a message middleware for my marketing app,but the method process_request is not returning anything. it is running without errors still though not returning message requests. my middleware.py--- from .models import MarketingMessage class DisplayMarketing(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): def process_request(request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False response = self.get_response(request) return response my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'marketing.middleware.DisplayMarketing', ] -
Django Channels consumer consuming 1 call twice
I am using a combination of DRF 3.11.0 and Channels 2.4.0 to implement a backend, and it is hosted on Heroku on 1 dyno with a Redis resource attached. I have a socket on my React frontend that successfully sends/received from the backend server. I am having an issues where any message sent back to the front end over the socket is being sent twice. I have confirmed through console.log that the front end is only pinging the back end once. I can confirm through print() inside of the API call that the function is only calling async_to_sync(channel_layer.group_send) once as well. The issue is coming from my consumer - when I use print(self.channel_name) inside of share_document_via_videocall(), I can see that two instances with different self.channel_names are being called (specific.AOQenhTn!fUybdYEsViaP and specific.AOQenhTn!NgtWxuiHtHBw. It seems like the consumer has connected to two separate channels, but I'm not sure why. When I put print() statements in my connect() I only see it go through the connect process once. How do I ensure that I am only connected to one channel? in settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { #"hosts": [('127.0.0.1', 6379)], "hosts": [(REDIS_HOST)], }, }, } Consumer: import json from … -
Why can't I inject form into HTML?
I have a form that I want to inject into a class based DetailView. forms.py class PastLocationForm(forms.Form): locations = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) views.py class PatientDetailView(DetailView): model=Patient form_class = PastLocationForm Unfortunately, the form PastLocationForm doesn't appear on the HTML page after injection. I inspected the page and there was nothing. Interestingly, if I pass PastLocationForm to a functional view and render it for another page, the form shows up! I also have other views where I make use of "form_class" for other modelForms and they function correctly. I will switch my view to functional view if I can't find the solution but I would rather keep the class based view. -
How to make Django recognize JSON file in another directory
I'm using a JSON file to store some credentials. I have a file with a function that opens that JSON file and uses the credentials to call the Twitter API using Tweepy. The file structure looks like this: [search]/ ├── [tweepi_api]/ │ ├── __init__.py │ ├── get_tweets.py │ ├── credentials.json └── views.py init.py looks like: from .get_tweets import ApiAuth Views.py looks like: from django.shortcuts import render import json from .tweepy_api import ApiAuth # Create your views here. def search_bar(request): tweetObj = ApiAuth('IBM') tweet_text = tweetObj.get_tweets() return render(request, 'tweets.html', {'public_tweets': tweet_text}) The problem is I get this error: Exception Value: [Errno 2] No such file or directory: 'credentials.json' I'm not sure how to include this file in my project in a different way. Hope this is enough to answer my question. I can share more of the code if needed but my goals is not made the credentials visible when i upload this to Github and keep them as a json file on my machine. Thank you in advance -
Find out the count of Matches from fixtures for individual country in Django Model
I have a model below which has matches_between which returns "Team1 vs Team2" Team1 will be the first country name and Team2 will be the second country name. I'm trying to find out the individual country's match count to represent the same in the points table for the number of matches the country has played. Model class Score(models.Model): matches_between = models.ForeignKey('Match',on_delete = models.CASCADE, related_name ='fixture_between') Team1 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='teamA',default = 0) Team2 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='teamB',default = 0) team1Score = models.IntegerField(default = 0) team2Score = models.IntegerField(default = 0) def team1_count(self): team_count1 = {i["Team1"]: i["count"] for i in order_items.objects.values('Team1').order_by().annotate(count=Count('Team1'))} return team_count1 def team2_count(self): team_count2 = {i["Team1"]: i["count"] for i in order_items.objects.values('Team2').order_by().annotate(count=Count('Team2'))} return team_count2 team1_count and team2_count function give the individual Team count but how to add both and return the individual country count. -
Celery Multiple Database Connections Django
On my project I have 5 workers on running that periodically check or insert data on database (postgress) every 5 seconds . My problem is that celery is opening too many connections to the database. I can see at least 20 connections for the same tasks hitting the database. Is there way to improve this with Django? I tried setting up CONN_MAX_AGE = None on django, to have the database persist the same connection but that didn't help. I also saw a pull request and some comments on reuse the database on previous mentioned issues but they were reverted because they caused regression problems. I wanted to accomplish one connection to Django ORM per worker. -
freeBSD _mysql.c:44:10: fatal error: 'my_config.h' file not found
My env is freeBSD12.1 python2.7.17 django1.11.29 mysqlserver18.0.19,I'v already uninstall python3.7.7 and ln -s /usr/local/python2.7/bin/python2.7 /usr/bin/python,a [root@bsd /home/tl/MySQL-python-1.2.5]# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.freebsd-12.1-RELEASE-p3-i386-2.7/MySQLdb running build_ext building '_mysql' extension cc -fno-strict-aliasing -O2 -pipe -fstack-protector-strong -fno-strict-aliasing -DNDEBUG -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/include/mysql -I/usr/local/include/python2.7 -c _mysql.c -o build/temp.freebsd-12.1-RELEASE-p3-i386-2.7/_mysql.o _mysql.c:44:10: fatal error: 'my_config.h' file not found include "my_config.h" ^~~~~~~~~~~~~ 1 error generated. error: command 'cc' failed with exit status 1 -
Django sqlite3 custom sql operational error when passing more than one parameter
I am trying to run a custom sql query in django on an sqlite3 database and get an operational error when I try and pass more than one parameter into my sql statement. I'm not sure why, I've tried using cursor.fetchall() instead of namedtuplefetchall but that didn't work. My database is named cardholders.sqlite3 and I have a table also name cardholders that I'm trying to pull data out of. below is the relevant code from django.db import connections from collections import namedtuple def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] then some views in between @login_required def databaseTest(request): if request.method == 'POST': postid = request.POST.get("id") with connections['cardholders'].cursor() as cursor: cursor.execute("SELECT * FROM %s WHERE ID = %s",['cardholders',postid]) row = namedtuplefetchall(cursor) cursor.close() return render(request, 'LibreBadge/databaseTest.html', context = {"AlertMessage":AlertMessage.objects.all, "row":row}) row = "none" else: return render(request, 'LibreBadge/databaseTest.html', context = {"AlertMessage":AlertMessage.objects.all}) and the traceback Environment: Request Method: POST Request URL: http://localhost:8000/databaseTest/ Django Version: 3.0.5 Python Version: 3.8.2 Installed Applications: ['LibreBadge', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line … -
In django using jquery how to retrieve user photo from database
''' function setUserResponse(message) { var UserResponse = '' + message + ' '; $(UserResponse).appendTo(".chats").show("slow"); ''' -
Is there an equivalent of 'list_editable' for FileFields in django?
I'm making a website with django where you can basically upload a file to the django admin and download it whenever you need to view it. Very simple (making it for my dad which wants to organize his excel files for his work). This is the problem, I hard coded the download path to the file I uploaded, which makes me have to modify the path every time I upload a new file with the same name (since django adds a random string of digits and characters every time you upload a file with the same name as before). What i'm currently doing is really inefficient, and would like to change that as soon as possible. My idea is to make the FileField name editable in the django admin. I've come across this: list_editable = ['asd']. I thought that might work and so I tried it. The results were interesting. I immediately saw a 'Save' button on the bottom of the admin site, which wasn't there before. But I still couldn't edit the FileField. I've searched this on multiple forums, the django documentation and more forums, only to not find anything useful. This is a picture of how the admin … -
Django models: Access to a multilevel link between tables
I have a problem to access certain data in my models. I have a User model giving its id to a Profile model which is giving its id to a ProfileA model. And when I create a User it automatically creates a Profile. Here is my user_model from django.db import models from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField from .model_custom_user_manager import CustomUserManager class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_e = models.BooleanField('e status', default=False) # objects = CustomUserManager() def __str__(self): return "{} {}".format(self.first_name, self.last_name) My profile_model: from django.db import models from django_countries.fields import CountryField from django.contrib.auth import get_user_model User = get_user_model() from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) And what I'm trying to do is create a ProfileA when a Profile is created AND when a User has is_a==True. Here is my profilea_model: from django.db import models from .model_profile import * from django.db.models.signals import post_save from django.dispatch import receiver class ProfileA(models.Model): profile = models.ForeignKey(Profile, null=True, … -
What's the right procfile / requirements for heroku with django channels?
tl;dr - django channels app runs local with manage.py runserver but not on heroku. I'm new to django channels - trying to deploy a very basic django app using channels to heroku. I initially built the project using the standard django polls tutorial and deployed that to heroku. Then i added in a chat app using the django channels tutorial. Managed to get that running fine locally using docker to run a redis server as they suggested and "python manage.py runserver". I'm getting stuck trying to deploy this to heroku or run it locally using heroku local. I've already added the redis addon in heroku and modified settings.py to point to the REDIS_URL environment variable. I also modified my template to use wss if appropriate (I believe that's necessary for heroku): var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var target = ws_scheme + '://' + window.location.host + '/ws/chat/' + roomName + '/'; const chatSocket = new WebSocket( target ); ... Thus I'm concluding that the problem is with the procfile. I'm not sure what the instructions to use there are. The initial polls tutorial used: web: gunicorn gettingstarted.wsgi --log-file - If I just use that 'heroku local' … -
Django Channels configuration websocket timing out
I have a situation with my configuration in which I am completely lost as to why it is not working. My test code has an issue where the Websocket connection is timing out: WebSocket network error: The operation couldn’t be completed. Operation timed out What is it I could have got wrong in the config for the deployed websocket configuration to not be responding? These are my critical configurations: settings.py ASGI_APPLICATION = 'tracking.routing.application' use_websockets = True CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis://:password@127.0.0.1:6379/0")], }, }, } consumers.py from django.contrib.auth.models import User from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async import json, asyncio class TestConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) await asyncio.sleep(5) await self.send({ "type": "websocket.close" }) .html <script> var loc = window.location console.log(loc) var path = '/ws/channels-test/' var wsStart = 'wss://' var port = ':6379' var endpoint = wsStart + loc.host + port + path console.log(endpoint) var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("open", e) } socket.onerror = function(e){ console.log("error", e) } socket.onclose = function(e){ console.log("close", e) } </script> routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, … -
Django admin: __str__ returned non-string (type int)
I'm working on a homework assignment to create an API in Django. I am getting the following error on two of my models when I click the link in the Django admin framework: TypeError at /officer/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/officer/ Django Version: 3.0.4 Exception Type: TypeError Exception Value: __str__ returned non-string (type int) Exception Location: /usr/local/lib/python3.7/dist-packages/rest_framework/relations.py in display_value, line 221 Python Executable: /usr/bin/python3 Python Version: 3.7.5 Python Path: Error during template rendering In template /usr/local/lib/python3.7/dist-packages/rest_framework/templates/rest_framework/horizontal/select.html, error at line 15 __str__ returned non-string (type int) My other models appear to be working correctly. Here is some code from models.py: class Subscriber(models.Model): subscriberID = models.IntegerField(primary_key=True) username = models.ForeignKey(UserInfo, on_delete=models.CASCADE) subscriptiontypecode = models.ForeignKey(SubscriptionType, on_delete=models.CASCADE) servicecode = models.ForeignKey(Service, on_delete=models.CASCADE) requestdate = models.DateField() startdate = models.DateField() enddate = models.DateField() motifofcancellation = models.CharField(max_length=64) beneficiaryID = models.IntegerField() def __str__(self): return self.subscriberID class TransferredSubscription(models.Model): transferID = models.IntegerField(primary_key=True) transferfrom = models.CharField(max_length=64) transferto = models.CharField(max_length=64) requestdate = models.DateField() transferdate = models.DateField() subscriberID = models.ForeignKey(Subscriber, on_delete=models.CASCADE) def __str__(self): return self.transferID class Officer(models.Model): officecode = models.ForeignKey(Office, on_delete=models.CASCADE) subscriberID = models.ForeignKey(Subscriber, on_delete=models.CASCADE) startdate = models.DateField() enddate = models.DateField() def __str__(self): return self.officecode TransferredSubscription works fine. I tried adding return str(self.officecode) and that still gives the same …