Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create product auto Code generator python django
I have a product class in the Django model. Over there are product name, category and department name (foreign key). so I want to create an automatic code generator that will generate automatically like 2 or 3 alphabets as category name and 3 alphabet department name and 6 digits number. for example: COM-ELC-000001 '''class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) description = models.CharField(max_length=255, blank=True, null=True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics') ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) unit = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) ''' -
is there a way to use due PWA with Django templates?
I am trying to build a PWA application with @vue/pwa and Django. I set up vue with Django with Webpack loader and now when I want to build it it runs the service-worker on static url any ideas? -
Disable gunicorn glogger and use Django LOGGING config
I am having trouble to properly config gunicorn and Django logging to work together. I have managed to make gunicorn pass the errors like 404 /favicon.ico to my Django log however I am not able to catch other levels no matter what I pass as --log-level for gunicorn. Here is the loggers section in my settings.py 'loggers': { 'django': { 'handlers': ['console', 'django_info_file', 'django_error_file'], 'propagate': True, }, 'gunicorn.access': { 'level': 'INFO', 'handlers': ['gunicorn_access'], 'propagate': True, 'qualname': 'gunicorn.access' }, 'gunicorn.error': { 'level': 'INFO', 'handlers': ['gunicorn_error'], 'propagate': True, 'qualname': 'gunicorn.error' } } ... and appropriate handlers 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'django_info_file': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/django/info.log'), 'formatter': 'verbose' }, 'django_error_file': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/django/error.log'), 'formatter': 'verbose' }, 'gunicorn_access': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/gunicorn/access.log'), 'formatter': 'verbose' }, 'gunicorn_error': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/gunicorn/error.log'), 'formatter': 'verbose' } }, So what I have tried so far: --log-level=debug --log-file=- --capture-output --enable-stdio-inheritance --access-logfile=- --error-logfile=- On the Django side I have tried with: 'disable_existing_loggers': True, (both True and False) setting DEBUG=True and False to make sure require_debug_false is … -
Architecture of application using Angular + Django + Flask and How to integrate them?
I am building an application with Angular + Django + Flask, below are the details of the architecture that are finalized for the implementation: We want to read data from MySQL database using flask microservice and show it to the user using angular UI. Django will be used for managing admin functionality. We decided to use flask despite the Django rest framework because of microservices architecture. Jenkins will be used for CI/CD and docker for deployment. What approach should be used if I want my angular UI to be served by Django application as I don't want to run a separate server for it and data in UI to be fed by flask microservice. I am facing a problem with how to integrate them. I have searched a lot but didn't found any good solid solutions. Please guide me on how should I integrate them. -
Django deploy with gunicorn failed
Im trying to dpublish my django App. After uploading this project and setup virtualenvirement testing with runserver and gunicorn --bind 0.0.0.0:8000 mysite.wsgi I can open my testpage on Webbrowser. But, after creating gunicorn_Test_Page.socket and gunicorn_Test_Page.service files, I cant open my testpage. After testing with curl –unix-socket /run/gunicorn_Test_Page.socket localhost I get this error curl: (3) Failed to convert –unix-socket to ACE; string contains a disallowed character curl: (3) <url> malformed access denied. But what kind of disallowed charakter? I cant find any logfiles for gunicorn service [Unit] Description=gunicorn daemon Requires=gunicorn_Test_Page.socket After=network.target [Service] User=localuser Group=www-data WorkingDirectory=/home/websites/Test_Page ExecStart=/home/websites/Test_Page/Test_Page_venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn_Test_Page.sock config.wsgi:application [Install] WantedBy=multi-user.target socket [Unit] Description=gunicorn daemon [Socket] ListenStream=/run/gunicorn_Test_Page.sock [Install] WantedBy=sockets.target what disallowed character is that? how can i find out? -
How to get Django/Wagtail to resolve this url
I feel like a heel asking this because I'm sure the answer is simple. Nevertheless I've spent hours researching and testing possible solutions and I have been left hairless. In the project harmony I have written my own login page and it resides in an app called users. I have another app called your_harmony. To proceed beyond the your_harmony page, users need to login. your_harmony.html {% if user.is_authenticated %} <h1>{{ self.sub_title|richtext }}</h1> You are logged in as: {{ user.username }} &nbsp <a href="/users/logout">Click here to logout</a> ... {% else %} You must login to access this page. <a href="/users/login">Click here to login</a> {% endif %} harmony.urls urlpatterns = [ ... url(r'your-harmony/', include('your_harmony.urls')), url(r'^users/', include('users.urls')), ... your_harmony.urls urlpatterns = [ path('', views.your_harmony, name='your_harmony') ] The url /users/login uses users/views.py to display the login form views.py RETURN_FROM_LOGIN_URL = 'your-harmony' RETURN_FROM_LOGIN_URL = 'your_harmony/your_harmony.html' def login_view(request): form_context = {'login_form': LoginForm,} url = "users/login.html" if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) url = RETURN_FROM_LOGIN_URL else: messages.error(request, 'Your account is not enabled!') context = {} else: messages.error(request, 'Your username or password was not recognized!') context = form_context else: context = … -
How can I make Django mysqlclient package being detected with mod_wsgi and virtualenv?
I have a Fedora 32 workstation with apache2 and Python 3.8 as default. I want to use it as server for my Django 3 app. I've already installed latest version of mod_wsgi (compatible with python3.8) and it's already enabled in apache modules. But I keep getting an error in apache error_log: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? The answer is YES, I've installed mysqlclient with pip install mysqlclient (in my virtualenv). And actually it exists: /var/www/virtualenv/lib/python3.8/site-packages/mysqlclient-1.4.6-py3.8.egg-info I think I have an issue in my .conf file for mod_wsgi. It usually worked in another developments that I've made, but I'm not getting the point of why it's not working now. This is my .conf MOD_WSGI settings: WSGIDaemonProcess myapp python-path=/var/www/myproj:/var/www/virtualenv/lib/python3.8/site-packages WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myproj/myproj/wsgi.py I have made the same configurations in another developments in the past, and it worked fine. I thought it would work. It's not a module version issue because when I run it with manage.py runserver it works fine. Using gunicorn is not an option at the moment. I need to get this working with mod_wsgi. Thanks in advance! -
Compatiblilty between Django rest Framework and Bootstrap
Django 3 Bootstrap 4 I have an Django app I've created (not live) and I've used bootstrap to make it nice and pretty (and mobile responsive). My goal is to end up with a react front end, but I'm not very good with react yet. Is it possible to switch to Django Rest Framework and keep bootstrap 4 or is drf and Bootstrap competing technologies? If I can, it'll let me be ready for react when I feel comfortable implementing it -
How can the super user make some user inactive?
I am trying as a super user to make some user inactive. In the front end I have a drop-down list with all users and a side I have a submit button. In the back-end I wrote this code. The code doesn't work. What is wrong? if request.method=='POST': user = request.user user.is_active = False user.save() messages.success(request, 'Profile successfully disabled.') return redirect('index') -
Django creating ManyToMany relationships
I am building an app where users can add what courses they are taking with their details. My intention is to view all the users enrolled in a course based on course code regardless of the other details of the course (Such as time of enrollment). Currently, my model for course is: class Course(models.Model): class Semester(models.TextChoices): SPRING = '1', 'Spring' SUMMER = '2', 'Summer' FALL = '3', 'Fall' WINTER = '4', 'Winter' NONE = '0', 'None' class Difficulty(models.TextChoices): EASY = '1', 'Easy' MEDIUM = '2', 'Medium' HARD = '3', 'Hard' FAILED = '4', 'Failed' users = models.ManyToManyField(Profile,related_name='courses') course_code = models.CharField(max_length=20) course_university = models.CharField(max_length=100) course_instructor = models.CharField(max_length=100) course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), max_value_current_year]) course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes') course_dislikes = models.ManyToManyField(Profile, blank=True, related_name='course_dislikes') course_semester = models.CharField( max_length=2, choices=Semester.choices, default=Semester.NONE ) course_difficulty = models.CharField( max_length=2, choices=Difficulty.choices, default=Difficulty.MEDIUM ) def __str__(self): return self.course_code def save(self, *args, **kwargs): self.course_code = self.course_code.upper().replace(' ', '') self.course_university = self.course_university.strip().lower() self.course_instructor = self.course_instructor.strip().lower() super(Course, self).save(*args, **kwargs) How can I view all the users with the same course number? Is this database structure appropriate for this use? I am trying to build a method called 'get_users_enrolled' but I am stuck on how should the query be to get the list … -
Storing Multiple Payment Methods + Shipping Addresses
Is there any Django plugin out there that will facilitate the ability for users to add multiple payment methods + shipping addresses to their user profile? Preferably something around the lines of a drop down of all the payment/addresses they have but also the ability to add additional ones. Thanks! -
How to make a comment box in Django for a single page, not a collection of blogs
With the help of Google I have learnt to make a comment system for my Blogs application. But I've few other pages in a separate app and all these pages have some set of tools, I need to get comment system for all these pages as well. I modified my Blogs App code as follows and getting a error. models.py class Page(models.Model): pass #Something more needs to be done here I guess, like some sort of reference to my page class Comment(models.Model): page = models.ForeignKey(Page,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) views.py from .models import Page from .forms import CommentForm from django.shortcuts import render, get_object_or_404 def atool(request): if request.method == 'POST': page = get_object_or_404(Page) comments = page.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = page new_comment.save() else: comment_form = CommentForm() return render(request, 'atool/atool.html', {'page': page, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) else: context= {'somedata': 'data'} return render(request, 'atool/atool.html', context) admin.py from django.contrib import admin from .models import Comment @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', … -
DB credentials for Hasura on Heroku
I've deployed hasura on heroku, how can I get the DB credentials of the same. I would like to use those credentials in a django app --Thx. -
ModuleNotFoundError when trying to use mock.patch on a method
My pytest unit test keeps returning the error ModuleNotFoundError: No module name billing. Oddly enough the send_invoices method in the billing module is able to called when I remove the patch statement. Why is mock.patch unable to find the billing module and patch the method if this is the case? billing.py import pdfkit from django.template.loader import render_to_string from django.core.mail import EmailMessage from projectxapp.models import User Class Billing: #creates a pdf of invoice. Takes an invoice dictionary def create_invoice_pdf(self, invoice, user_id): #get the html of the invoice file_path ='/{}-{}.pdf'.format(user_id, invoice['billing_period']) invoice_html = render_to_string('templates/invoice.html', invoice) pdf = pdfkit.from_file(invoice_html, file_path) return file_path, pdf #sends invoice to customer def send_invoices(self, invoices): for user_id, invoice in invoices.items(): #get customers email email = User.objects.get(id=user_id).email billing_period = invoice['billing_period'] invoice_pdf = self.create_invoice_pdf(invoice, user_id) email = EmailMessage( 'Statement of credit: {}-{}'.format(user_id, billing_period), 'Attached is your statement of credit.\ This may also be viewed on your dashboard when you login.', 'no-reply@trevoe.com', [email], ).attach(invoice_pdf) email.send(fail_silently=False) return True test.py from mock import patch from projectxapp import billing @pytest.mark.django_db def test_send_invoice(): invoices = { 1: { 'transaction_processing_fee': 2.00, 'service_fee': 10.00, 'billing_period': '2020-01-02' }, 2: { 'transaction_processing_fee': 4.00, 'service_fee': 20.00, 'billing_period': '2020-01-02' } } with patch('billing.Billing().create_invoice_pdf', '/invoice.pdf') as p1: test = billing.Billing().send_invoices(invoices) assert test … -
adding detail information to django listview object in template
I have a listview in which I'm hoping to insert additional details about the object (activity duration and average power) in the same row as the link to the object detail (the best way to describe it would be that I want some detailview attributes inserted into the listview). At the moment, the best I can achieve is a separate context dictionary listed below the object_list, as shown in this screen shot: And the following is my listview: class RideDataListView(LoginRequiredMixin, ListView): model = RideData context_object_name='object_list' template_name='PMC/ridedata_list.html' def get_queryset(self): queryset = super(RideDataListView, self).get_queryset() return queryset def get_context_data(self, *args, **kwargs): model = RideData context = super(RideDataListView, self).get_context_data(*args, **kwargs) records = list(RideData.objects.all().values()) actdict2={} id=[] ap=[] actdur=[] for record in records: actdf=pd.DataFrame.from_dict(record) id.append(actdf['id'].iloc[0]) ap.append(actdf['watts'].mean()) actdur.append(str(timedelta(seconds=len(actdf['time'])))) actdf2=pd.DataFrame() actdf2['id']=id actdf2['ap']=ap actdf2['actdur']=actdur actdict2=actdf2.to_dict('records') context['actdict']=actdict2 context['actdur']=actdur return context What I haven't been able to nail down in my research is if there is a way to either a) annotate the queryset with stuff from context or b) loop through the context dictionary 'actdict' within the object_list loop (doesn't seem possible based on some attempts) or c) include individual lists (ap and actdur as additions to to query. Just curious for some additional leads to add some more object … -
I can't filter django by average
I am trying to learn django database transactions, my aim is to get the average of the price based on the month_year value, but all the values in the price column are coming from .models import Arabam from django.db.models import Sum,Avg,Count def pie_chart(request): queryset1= Arabam.objects.annotate(fiyat_ort=Avg('fiyat')).filter(marka="Skoda",model="Rapid",motor="1.6 TDI GreenTec Style ",yeni="90000.0") labels = [] data = [] for city in queryset1 labels.append(city.month_year) #x ekseni data.append(city.fiyat_ort) # y ekseni return render(request, 'verigorsellestirme.html', { 'labels': labels, 'data': data,}) -
Django-How do i get the HTML template to show data from the two models?
So i'm creating a to-do app. How do I get the html view to show the tasks? I tried to show the name of the tasks but it's blank. So far, it only shows the board name and the user who created it. Here is my code so far: Models.py class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board") name = models.CharField(max_length=200) class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30) views.py def board_post_detail(request, board_id): obj = get_object_or_404(Board, id=board_id) taskobj= Task.objects.filter(board=obj) context = {"object": obj, "tasks": taskobj} return render(request, 'boards/board_post_detail.html', context) board_post_detail.html {% block content %} <h1>{{ object.name}}</h1> <p> {{tasks.text}}<p> <p>Created by {{object.admin.username }}</p> {% endblock %} -
Django forms and GeoDjango LeafLets
For my application I'm trying to put locations on the map. Per location I have a latitude and a longitude in my model. Displaying these on a map is piece of cake. models.py class Toursteps(models.Model): tour = models.ForeignKey(Tour, related_name='toursteps', on_delete=models.CASCADE) step = models.IntegerField() title = models.CharField(max_length=50) location = models.CharField(max_length=100) description = models.CharField(max_length=1000) audiotext = models.TextField() latitude = models.FloatField() longitude = models.FloatField() radius = models.FloatField() image = models.ImageField(upload_to=upload_tour_step_image, blank=True, null=True) class Meta: db_table = 'tourSteps' verbose_name_plural = "tourSteps" unique_together = ('tour_id', 'step',) ordering = ('tour_id', 'step',) def __str__(self): return str(self.tour) + "|" + str(self.step) But I have no idea how I can integrate this in my Create-Form and Update-Form. What I want to achieve. toursteps_form.html {% extends 'tour_admin/admin_base.html' %} {% load crispy_forms_tags %} {% load leaflet_tags %} {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} {% block content %} {% if user.is_authenticated %} <div class=""> <h1>Step:</h1> <form enctype="multipart/form-data" class="tour-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% else %} <h1>Not authorised!</h1> {% endif %} {% endblock %} forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget class TourStepForm(forms.ModelForm): class Meta(): model = Toursteps exclude = ('tour',) views.py class CreateTourStepView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = … -
Django uncaught exception when file upload request canceled
I have an async file uploader using Dropzone.js and everything works fine except for a strange server error that appears from time to time when I cancel an upload request. The error is inconsistent, sometimes I get the expected result after canceling the upload request and other times the error shows up in Identical conditions. Please note that I'm using chrome's network throttling so I can cancel uploads before the upload finishes. This is the file upload view : @login_required def media_upload(request): if request.method == 'POST' and request.FILES.getlist('media'): file = request.FILES.getlist('media')[0] fs = FileSystemStorage() try: img = Image.open(file) img.verify() except Exception as exp: return HttpResponse(exp, status=400) # Converting and saving media img = Image.open(file) media_prefix = ('evnt_u' + str(request.user.id)) media_ext = '.jpg' if img.format != 'JPEG': img = img.convert('RGB') buffer01 = BytesIO() img.save(buffer01, format='JPEG') file = InMemoryUploadedFile( buffer01, None, (media_prefix+media_ext), 'image/jpeg', buffer01.tell, None) media = fs.save((media_prefix+media_ext), file) return HttpResponse(media, status=200) else: return HttpResponse(status=400) I receive POST /media/upload/ HTTP/1.1" 400 0 correctly with the code above but that's not consistent. the other times I receive the appropriate response followed by a chain of uncaught exceptions: Bad Request: /fa/media/upload/ [05/Apr/2020 18:36:51] "POST /fa/media/upload/ HTTP/1.1" 400 0 Traceback (most recent call last): File … -
How to return django modal objects through httpresponse?
def search_car(request): if request.method == 'POST': a=request.POST['search_name'] scn=Car.objects.filter(name__icontains=a) In the above defined view I want return the variable scn through the function HttpResponse().So for that I should just return it like: return HttpResponse(scn) Or is there any better and appropriate way is there for doing so?? Also I want receive the sent variable in the template using javascript and that doing this: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } would be correct or is there any better way for doing that?? -
name suggestions while updating data base from another table in django models
I am working on a leaderboard webapp with django. i have created a four teams each having their own own table in sqlite databse. i have another table pointshistor, so whenever i want to update the points of a player i only have to make a new entry in this table. the classes declaration are as below. class team1(models.Model): member_name = models.CharField(max_length=100) employee_id = models.CharField(max_length=40) unique_id = models.CharField(max_length=40) member_type = models.CharField(max_length=50, choices=[('Team Lead, 'Team Lead'), ('Member', 'Member')]) points = models.IntegerField() class team2(models.Model): member_name = models.CharField(max_length=100) employee_id = models.CharField(max_length=40) unique_id = models.CharField(max_length=40) member_type = models.CharField(max_length=50, choices=[('Team Lead', 'Team Lead'),('Member', 'Member')]) points = models.IntegerField() class pointshistory(models.Model): team_name = models.CharField(max_length=40, choices=[('team1', 'team1'),('team2','team2')]) member_name = models.CharField(max_length=100) activity_name = models.CharField(max_length=100) points = models.IntegerField() so what i want to do is when i select team from the team_name choice in the add pointshistory in django/admin and then start typing the name it should give suggestions of the name available in the particular team_name. and if one can help is there a simple way to update the points of the particular member. currently i am updating it by fetching the last entry from pointshistory table and adding the value to points by python script. main objective is … -
How to model an financial accounting system in Django?
The Django application I'm developing for a taxi company has following modules, Trips Customers (who buy products) Vehicles Drivers Each trip is constituted by selecting a customer, a vehicle and a driver along with a few other parameters. I will be recording every single trip, and the revenue generated because of it. I also would like to assign this revenue generated to the individual customer who took the vehicle, and to the vehicle which was used in the trip. Since I would like to have a deeper understanding of the customer's spending and the revenue generated by vehicles. I need to have an Accounts Receivables and a Received statement for each trip. Is there a standard way to achieve this? I believe the similar approach is used in typical e-commerce systems. Any and every help is appreciated. -
Django rest framework, field that is a choice or text
Is there a way to create a field which is A text field, but, with choices. that the choices are the field existing objects? And if the word passed in is not in the existing data, add it? I've looked across all the internet for a field like this or example of it, either in Django or the rest framework, but could not find one. My use for it, for example, would be: class Point(models.Model): location_name = models.TextField(verbose_name="Location name", unique=True, # This would include the existing names. choices=, ) latitude = models.FloatField(name="GDT1Latitude", verbose_name="GDT 1 Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="GDT1Longitude", verbose_name="GDT 1 Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) So, It could be used when making a post request instead of already typing the latitude, longitude It would be fetched from the exsiting object. -
Count events types per day for different timezones using Django ORM
We have a table that holds multiple events and when they were added. The default timezone used for storing the events is UTC. Eg : class Events: event_type = models.CharField(max_length=45, null=False) date_added = models.DateTimeField(auto_now_add=True) Now, we want to get a per day count of different event types between two dates - start_date and end_date. Eg : for start_date = "2020-03-1" and end_date = "2020-03-31", output should be - [{ "date" : "2020-03-1", "event1" : 200, "event2" : 606, "event3" : 595 }, { "date" : "2020-03-2", "event1" : 357, "event2" : 71, "event3" : 634 }, { "date" : "2020-03-3", "event1" : 106, "event2" : 943, "event3" : 315 }, { "date" : "2020-03-4", "event1" : 187, "event2" : 912, "event3" : 743 }, . . . . { "date" : "2020-03-31", "event1" : 879, "event2" : 292, "event3" : 438 }] Since the users are in different timezones (America, Europe, Asia, etc), we want to convert the timezone as per user before counting the events. Counting in UTC will have wrong counts per day in the user's timezone. Eg : an event created on 3 March, 1:30 am in IST will be shown on 2 March, 8 pm in … -
Django - posts.Post.None
I am working on a django project and I have 2 models that look like this: class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='playlist_user') name = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_image_path) genre = models.CharField(max_length=120,null=True,blank=True) track = models.ManyToManyField('Post',related_name='playlist_track') class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_image_path) audiofile = models.FileField(upload_to=upload_image_path,null=True) genre = models.CharField(max_length=120,null=True,blank=True) and this view: def userprofileview(request): own_tracks = Post.objects.filter(user=request.user) playlist_ = Playlist.objects.filter(user=request.user) context = { 'own_tracks':own_tracks, 'playlist_':playlist_ } return render(request,'userprofile.html',context) but when I try to query the posts from the playlist like this: {% for object in playlist_ %} {{ object.track }} {% endfor %} I get: posts.Post.None Thank you for any suggestions