Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework type error : unhashable type: 'slice' on queryset that contains a dictionary
I am trying to group data by the hour in one end point with the rest API from django. in my viewset I am filtering the queryset and creating a dictionary that contains 24 list items for every hour. When i pass that as the queryset I get the following error: unhashable type: 'slice' I am guessing that it is because the dictionary need to be converted to something that is legible for a JSON format? I really have no clue since this is my first try at creating such an end point. Here is the code: from collections import defaultdict from django.db.models.functions import ExtractHour class JobsByDayViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = (SessionAuthentication, DataAppClientTokenAuthentication) queryset = Job.objects.all() serializer_class = serializers.JobsByDaySerializer def get_queryset(self): day_query = self.request.GET.get('day') today_query = self.request.GET.get('today') if day_query != '' and day_query is not None: queryset = Job.objects.filter(dt_start__week_day=day_query) return queryset elif today_query != '' and day_query is not None: today = datetime.today().weekday() day_query = (today + 1) % 7 + 1 queryset = Job.objects.filter(dt_start__week_day=day_query) return queryset else: jobs_by_hour = Job.objects.annotate(hour=ExtractHour('dt_start')) results = defaultdict(lambda: []) for row in jobs_by_hour: results[row.hour].append(row) queryset = results return queryset -
How to send Data to backend (Django) from React [list, numbers, files]
My question refers to How do I append a list to FormData? However I believe it was not answered well so I am creating another question and elaborating more. I intend to send data to Django backend via axios from React. The data includes images, primary key values and list of primary key values. I understand that FormData cannot pass integers or list of integers and JSON cannot pass a file. What is the best way to achieve both. If I use JSON the image is not passed and I get the error ["The submitted data was not a file. Check the encoding type on the form."] If I use FormData the ForeignKey fields holding integers or list of integers (Many To Many Field) are not passed and I get the error ["Incorrect type. Expected pk value, received str."] Questions What is the best way to send all the data to backend? 1.) Should I make changes to backend so it can parse the strings, that is achievable but does not seem elegant as the backend should be generalised for any client side application and this seems like a particular issue case? 2.) Is there any way to send data … -
TemplateDoesNotExist at /poll/1/ -Django tutorial
I got an error, TemplateDoesNotExist at /polls/1/ I'm supposed to see the result of the vote after I vote. Error is: polls/details.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: polls/details.html Exception Location: C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\Scripts\python.exe Python Version: 3.8.4 Traceback is File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\src\mysite\polls\views.py", line 18, in detail render(request, 'polls/details.html', {'question': question}) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\JohnDoe\Documents\JaneDoe\Django\trydjango\tutorial\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: polls/details.html view.py is import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): """Contains question and publication date.""" question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token … -
django rest framework doesn't accept blob picture file (File extension “” is not allowed)
I am trying to update a User Profile by making a multipart/form-data put request (from my vue frontend using axios) containing a png blob image file. I receive an error message: File extension “” is not allowed. This is the File Field on the Userprofile Model: profile_picture = models.FileField( _("Profile Pictures"), upload_to="profile_picture", max_length=100, blank=True, null=True, ) These are the signals I use in the Userprofile model to save and update the Model. @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I think it may be because of these or something other specific to the Userprofile model that creates the error because on another model the file upload works as intended, although there I am making a post and not a put request. The Userprofile model is connected to the User by a One to One Field. Ther is nothing special in my serializer or views that could be causing the bug. I have no Idea what I could do to fix this. Thanks for all advice. If you need any other information feel free to ask. The image is the formdata sent with the put request... maybe somethings wrong there -
How do I hide the arrows within a numeric input field in Django?
I want to use a [![BigIntegerField][1]][1] in a search function, but I don't want to see those little up and down arrows in the input field. How can I hide them? Is it in Django or in the HTML page? -
Django URLs.py - url not recognized and registered namespaces
My issue is with a template where i build in a url tag. This is the template part which causes the error: 39 <div class="table-data__tool-right"> 40 <button class="btn btn-primary btn-lg active" href="{% url 'doctormonthbilling_export:add' %}/{{ month }}/{{ doctorid }}"> 41 <i class="zmdi zmdi-plus"></i> 42 Rechnung erstellen 43 </button> 44 </div> and this is the error: 'doctormonthbilling_export' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/doctormonthbilling/3/2 Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: 'doctormonthbilling_export' is not a registered namespace Exception Location: C:\mySF\mySF\venv\lib\site-packages\django\urls\base.py in reverse, line 83 Python Executable: C:\mySF\mySF\venv\Scripts\python.exe Python Version: 3.8.4 Python Path: ['C:\\mySF\\mySF', 'C:\\Program Files (x86)\\Python38-32\\python38.zip', 'C:\\Program Files (x86)\\Python38-32\\DLLs', 'C:\\Program Files (x86)\\Python38-32\\lib', 'C:\\Program Files (x86)\\Python38-32', 'C:\\mySF\\mySF\\venv', 'C:\\mySF\\mySF\\venv\\lib\\site-packages'] even though i have the line in my urls.py file like the following: # some paths before with , path('doctormonthbilling_export/<str:month>/<str:doctorid>', views.doctormonthbilling_export,name='doctormonthbilling_export'), #some other paths after i can't figure out what's wrong! Can anyone spot the error? Thanks -
python ImproperlyConfigured
I have following project structure on this place: /Users/username_pc/PycharmProjects/backend in the project: backend/settings/development.py so the path to development.py is: /Users/username_pc/PycharmProjects/backend/backend/settings/development.py So I want to use this backend django project in a non-django python project with: import os, sys, django sys.path.append('/Users/sgerrits/PycharmProjects/backend/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.development") django.setup() When running this I got following error: Traceback (most recent call last): File "<input>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Axios POST sends Nonetype data to Django Rest Framework
I am having difficult time trying to figure out the way to post form data through axios to my Django backend, using DRF. Classic Django forms work correct. Whenever I try to post it using React Modal form, I get a new input in my database, that consists of None's all the way (nulls, I guess?). Serializer doesn't seem to interrupt it and I get a 201 HTTP status. I have no idea where to look for the cause of this problem, I believe I tried almost everything. I'll post my code so maybe a more experienced eye can catch the root of this error. components.js/lookup.js import axios from "axios"; const csrftoken = getCookie("csrftoken"); const api = axios.create({ baseURL: `http://localhost:8000`, headers: { "X-CSRFToken": csrftoken, }, }); function getCookie(name) { // gets csrf cookie var cookieValue = null; if (document.cookie && document.cookie !== "") { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export async function apiLookup(method, endpoint, … -
Put value of function in context
I have tried this context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) return cart_obj return render(request, self.template_name, {'DataPaginated':paginated, 'paginate_by':paginate_by, 'cart':cart_obj}) and this def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context return render(request, self.template_name, {'DataPaginated':paginated, 'paginate_by':paginate_by, 'cart':cart_obj}) Both times I got the error message name 'cart_obj' is not defined I am unsure how to put the value from the function into context. -
502 Bad Gateway while uploading large files in Django on AWS
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I need to get .igs file in one of my forms and save it to S3 Bucket but I was getting 413 Request Entity Too Large error. Then I have created a folder as .platform/nginx/conf.d/proxy.conf and I have added the code below into it. client_max_body_size 50M; client_body_buffer_size 30M; After creating this config file, when user press the submit button, the file I uploaded on the form can now save to S3 Storage, so the 413 Request Entity Too Large error fixed but the page gives a 502 Bad Gateway error. I did some research on it and changed my proxy.conf file such as below. client_max_body_size 8000M; client_body_buffer_size 8000M; client_body_timeout 120; But it didn't work. The nginx error.log file contains the following lines. [error] 15254#0: *17 upstream prematurely closed connection while reading response header from upstream, [warn] 15254#0: *101 using uninitialized "year" variable while logging request [warn] 15254#0: *101 using uninitialized "month" variable while logging request [warn] 15254#0: *101 using uninitialized "day" variable while logging request [warn] 15254#0: *101 using uninitialized "hour" variable while logging request [alert] 15253#0: worker process 15254 exited … -
Using ngrok for stripe webhook in django
i am currently trying to link ngrok url to my app for stripe and i have url error (404 : The current path stripe/webhook ,didn't match any of these). Here is the current structure : Ngrok activate Url in stripe webhook views.py def my_stripe_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the event if event.type == 'payment_intent.succeeded': payment_intent = event.data.object # contains a stripe.PaymentIntent print('PaymentIntent was successful!') elif event.type == 'payment_method.attached': payment_method = event.data.object # contains a stripe.PaymentMethod print('PaymentMethod was attached to a Customer!') # ... handle other event types else: # Unexpected event type return HttpResponse(status=400) return HttpResponse(status=200) urls.py # Webhook path('stripe/webhook/', views.my_stripe_webhook_view, name="webhook"), I've been looking for info for 2 hours and can't find my error, thank you very much for your help! -
Sync postgres database via git
We are 3 students working on a django project with postgres database and we sync our project with eachother via a git repository like gitlab. we have different os (windows 10 and linux ubuntu 20). and we use vscode as IDE. How can we sync our entire database (data entry) via git (like sqlite) ? Is there any way to handle it via kind of converting our db to file ? -
How to return custom json response with Django REST Framework?
Actually i return json from some media files depends on url <str:scene> varialbe is set. I just want to use rest framework interface and token auth so i think that could be easier way to present my data. Here what i do: views.py class Manager(views.APIView): def get(self, request, scene): return JsonResponse({'get': scene}) def post(self, request, scene): return JsonResponse({'post': scene}) urls.py router = routers.DefaultRouter() router.register(r'', views.Manager) urlpatterns = [ path('<str:scene>', include(router.urls)), ] This code requires me to use basename argument in path but since i don't use models i haven't anything to pass in it. So what is the best way to return my custom json data using rest framework interface and it's auth token? -
Django routing - The empty path did not match any of these
[enter image description here][1] Using the URLconf defined in pccb_model.urls, Django tried these URL patterns, in this order: predictive/ admin/ The empty path didn't match any of these. [1]: https://i.stack.imgur.com/1IPKk.png -
Python Django admin getting error while deleteing class Question
I have a class Question and I registered them to Django admin. And when I want to delete some of them, I am getting an error "OperationalError at /admin/f/question/10/delete/ no such column: f_answer.date". here is my models.py file content from django.db import models # ---------- Question ---------- class Question(models.Model): ''' Questions ''' author = models.CharField('Author', max_length=45) title = models.CharField('Title', max_length=300) body = models.TextField('Body') date = models.DateTimeField(auto_now_add=True, db_index=True, null=True, blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Questions' verbose_name = 'Question' -
Generate inline formset in django using javascript
I have used inlineformset_factory for generating multiple instances of a same model. I want to make it dynamic. So I have a + button, when user presses this button same form will be generated. I also want to keep a delete button for deleting. forms.py: WorkExperienceFormset = inlineformset_factory(Employee, WorkExperience, extra=1, fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ], widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } ) WorkExperience model is related with Employee model as ForeignKey. employee_work_experience_form.html.html: <!-- Manage collection of forms --> {{ work_formset.management_form }} <!-- Handle formset errors --> {% for work_form in work_formset %} {{ work_form.non_field_errors }} {{ work_form.errors }} {% endfor %} {% for work_form in work_formset %} <div class="work-form"> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Previous Company Name</label> <div class="col-md-4 col-sm-4 col-xs-12"> <!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> --> {{ work_form.previous_company_name }} </div> </div> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Job Designation</label> <div class="col-md-4 col-sm-4 col-xs-12"> <!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> --> {{ work_form.job_designation }} </div> </div> … -
Django tries to import nonexistent class
I was working in one branch, where I have added few models and used them in inclusion tags. After switching to another branch (which does not contain these models), I am not able to load any page - I get these: Invalid template library specified. ImportError raised when trying to load 'delta.templatetags.shopcart_pack_counters': cannot import name ShopCart in render() function. I have tried to clear caches, but that does not help. If I clone the project again and switch to the second branch, everything works fine (unless I do not switch the first one and back again). What can I do to fix that problem? Thanks. -
How to change max_length of a field on a proxy model in Django
I am working on a bulletin board project. I have two Django model classes: from ckeditor.fields import RichTextField ... class Bulletin(models.Model): # other fields... content = RichTextField('Content (Don\'t use this and content image)', max_length=5000, blank=True, null=True) # other classes... class QuoteManager(models.Manager): def get_queryset(self): return super(QuoteManager, self).get_queryset().filter( bulletin_type=BulletinType.QUOTE.name) class Quote(Bulletin): class Meta: proxy = True objects = QuoteManager() def save(self, *args, **kwargs): self.bulletin_type = BulletinType.QUOTE.name super(Quote, self).save(*args, **kwargs) This allows me to keep all my proxy classes in the same DB and have the same fields as my base "Bulletin" class. What I want to do is modify the Quote proxy class to have a max_length of say 200. How can I do this? What I've tried? I tried adding "content" to the proxy class and this was a name collision. I tried adding a field called "quote_content" to the proxy class as a workaround, but this also failed as you cannot create fields in proxy classes. A perfect solution would allow me to keep my proxy class, but still modify the max_length. Is such a think even possible? -
How to recreate this SQL(ite) query with an inner select and groupby in the Django ORM?
So, I'm trying to run a query and I can't get it to work properly. I have managed to write a SQL query that does what I'm looking for, but I'm struggling to move it into the Django ORM. As a sidenote: even though the SQL query does what I'm looking for, I'm not sure it's the best way of creating such a query anyway. So, for completeness sake I'll recreate a similar situation as I'm in, so please let me know if there's a better way to create such a SQL query (and in turn maybe an easier way to turn it into Django ORM code). Imagine a very simple movie database: class ReleaseType(models.Model): name = models.CharField(max_length=255) # e.g. CD/DVD/BD class Movie: name = models.CharField(max_length=255) # e.g. Harry Potter class MovieRelease: movie = models.ForeignKey(to='Movie', on_delete=models.CASCADE) type = models.ForeignKey(to='ReleaseType', on_delete=models.CASCADE) release_name = models.CharField(max_length=255) # e.g. Harry Potter: Special Edition Now imagine I want to list all movies that have both a DVD and BD movierelease. I've worked out the following SQL (note: I haven't tested this exact same sql because the above is just a simplified fictive example, but it's the same just with other column names): SELECT * FROM … -
Django Rest Framework Optional Image field is not working
I'm trying to make image field optional in serializer. But it still not making the image field optional. My code are as bellow: Photo Uploading file managing class: class FileManager: @staticmethod def photo_path(instance, filename): basefilename, file_extension = os.path.splitext(filename) date = datetime.datetime.today() uid = uuid.uuid4() if isinstance(instance, User): return f'profile_pic/{instance.email}/{uid}-{date}{file_extension}' elif isinstance(instance, BlogPost): print(file_extension) return f'blog_pic/{instance.author.email}/{uid}-{date}{file_extension}' My Model class: class BlogPost(models.Model): ''' Manage Blog Posts of the user ''' author = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING, related_name='blog_author') content = models.TextField(max_length=600, blank=True, null=True) content_image = models.FileField(upload_to= FileManager.photo_path, null=True, blank=True) is_approved = models.BooleanField(default=False) updated_on = models.DateTimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(BlogPost, self).save(*args, **kwargs) img = Image.open(self.content_image.path) if img.height > 600 or img.width > 450: output_size = (600, 450) img.thumbnail(output_size) img.save(self.content_image.path) My Serializer Class: class BlogPostUserSerializer(serializers.HyperlinkedModelSerializer): ''' Will be serializing blog data ''' author = UserListSerializer(read_only=True) content = serializers.CharField(required=False) content_image = serializers.ImageField(required=False, max_length=None, allow_empty_file=True, use_url=True) class Meta: model = BlogPost fields = ( 'url', 'id', 'content', 'content_image', 'author') def validate(self, data): if not data.get('content') and not data.get('content_image'): raise serializers.ValidationError({'message':'No-content or Content image were provided'}) return data The error Text: ValueError at /forum/write-blog The 'content_image' attribute has no file associated with it. I've gone through the Django Rest Framework's Doc but no help. Even the … -
django.core.exceptions.fielderror: cannot resolve keyword 'flight' into field. choices are: first, flights, id, last
Python 3.8.4 Django version 3.0.8 Hey guys, I have started HarvardX's CS50's Web Programming with Python and JavaScript. Following a project there, in lecture 4:SQL, Models, and Migrations exactly step by step, I still got this error > Watching for file changes with StatReloader > Performing system checks... > > System check identified no issues (0 silenced). > August 03, 2020 - 16:29:32 > Django version 3.0.8, using settings 'airline.settings' > Starting development server at http://127.0.0.1:8000/ > Quit the server with CTRL-BREAK. > [03/Aug/2020 16:29:59] "GET /flights/ HTTP/1.1" 200 449 > Internal Server Error: /flights/1 > Traceback (most recent call last): > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", > line 34, in inner > response = get_response(request) > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", > line 115, in _get_response > response = self.process_exception_by_middleware(e, request) > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", > line 113, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) > File "C:\Users\Parth Suthar\Desktop\airline\flights\views.py", line 17, in flight > "non_passengers": Passenger.objects.exclude(flight=flight).all() > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", > line 82, in manager_method > return getattr(self.get_queryset(), name)(*args, **kwargs) > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", > line 912, in exclude > return self._filter_or_exclude(True, *args, **kwargs) > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", > line 921, in _filter_or_exclude > clone.query.add_q(~Q(*args, **kwargs)) > File "C:\Users\Parth Suthar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", > line … -
Change formatting when runserver starts in djagno
Performing system checks... System check identified no issues (0 silenced). August 03, 2020 - 16:56:57 Django version 3.0.5, using settings 'my_project.settings.local' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. I want to write some custom message here, can i do this, just for fun sake i want to use cowpy library here -
def serialize(self) what does it do in django models
so i was working on a project you should know i have just started and was trying to make a login/logout of emails and some stuff and i saw this can someone help me find out what does this def serialize do here. class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "read": self.read, "archived": self.archived } i dont know what this serialize do in this class can someone help me out -
How can i call a list in django template?
Here is my models.py file. from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify import misaka from django.contrib.auth import get_user_model # Create your models here. class Category(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='',blank=True) members = models.ManyToManyField(User, through="CategoryMember") category_pic = models.ImageField(upload_to = 'category_pics', blank=True) def __str__(self): return self.name # WE are saving the model. But before that we are converting # the name using slugify and description using misaka. def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) #get_absolute_url is used because it tell the template # CreateView to go to the page it is directing. # for this example it is directing to go to single page of a category. def get_absolute_url(self): return reverse("categories:single", kwargs={"slug":self.slug}) class Meta: ordering = ['name'] class CategoryMember(models.Model): category = models.ForeignKey(Category, related_name = "memberships", on_delete=models.CASCADE) user = models.ForeignKey(User, related_name="user_categories", on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together= ("category", "user") This is some part of views.py file from django.contrib.auth.models import User from categories.models import CategoryMember, Category class UserPosts(ListView): model = Post template_name = 'posts/user_post_list.html' def get_queryset(self): try: self.post_user = User.objects.prefetch_related("user_of_post_model").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: … -
django-autocomplete-light not working when added on IIS
django-autocomplete-light was working well on localhost but not working when added on IIS. Everything is working fine except dropdown that was added with django-autocomplete. Is there any specific task need to complete??seek your support and thanks in advance