Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
delete and modify comments by users
i've added to my Blog post comments now the problem is that i'm trying to create remove function for that and i have one but now eve uset thak is logged in can remove all the comments how can i fix this that user can delete only their own comments?? the funnyiest thing is that i have this function on my posts and it wokres and if i'm trying to do the same on my comments then i've get 404 error. Ive tried a few different ways but nothing worked You are my only hope:) views.py from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.models import User from .models import Post, Comment from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .forms import CommentForm from django.contrib.auth.decorators import login_required # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): model … -
Django ORM - How to order objects by sum of three highes scores?
Suppose my Django users participate in different contests, where they score points. Every User has around 100 different contests in which he participated. How can I query the users model in a view to retrieve the list of users, ordered by the sum of their three heights contest scores? As I want to pass on certain filters from the view to the contest (country, year), I am trying to avoid writing raw SQL. -
Spotipy on Django authorization without copy-paste to console
I have a Django site in which I want to use spotipy to look for statistics of the song like popularity and views. I have this code right now: import spotipy import spotipy.util as util #luxury import json import webbrowser username = 'dgrqnco2rx8hdu58kv9if9eho' scope = 'user-read-private user-read-playback-state user-modify-playback-state' token = util.prompt_for_user_token(username, scope, client_id='08bb526962574a46b359bffc56048147', client_secret='bf6d4184c8ae40aca207714e02153bad', redirect_uri='http://google.com/') sp_obj = spotipy.Spotify(auth=token) ss = 'name of song' if ss.__contains__('('): q = ss[0:ss.index('(')] elif ss.__contains__('['): q = ss[0:ss.index('[')] elif ss.__contains__('['): q = ss[0:ss.index('{')] else: q = ss query = sp_obj.search(q, 1, 0, 'track') #<<<<<<<<<<SONG>>>>>>>>>> #FIND THE SONG URI song_uri = query['tracks']['items'][0]['uri'] track = sp_obj.track(song_uri) track_data = sp_obj.audio_features(song_uri) song_popularity = track['popularity'] song_danceability = track_data[0]['danceability'] song_energy = track_data[0]['energy'] song_loudness = track_data[0]['loudness'] song_tempo = track_data[0]['tempo'] However spotipy redirects me to a page for authorization and I need to paste the url in the console. The regular user however does not have access to this console. So how can I do the authorization in an alternative way or even bypass it? I was thinking about getting a spotify account in which every user will be getting logged in so that the user won't have to do the authorization and won't have to have a spotify account. Is this possible? … -
Unloading Data from Redshift to Amazon S3 | Django ORM
I'm looking for the best approach to work with Amazon S3 and Amazon Redshift. I need to unload the data from amazon Redshift and store it into S3. According to the AWS documentation, is truly simply to save the data to S3 https://docs.aws.amazon.com/redshift/latest/dg/t_Unloading_tables.html But I want to know if there's any way to do this using Django ORM, since also has support to Psycopg2. Thanks regards. -
Python 3 Django Rest Framework - Manager object has no attribute error
My custom EnrollmentManager says object has no attribute "end_date" - except it does!? class EnrollmentManager(models.Manager): def org_students_enrolled(self, organisation): return self.filter(student__organisation__name=organisation).filter(self.end_date.date() >= datetime.date.today()) class Enrollment(TimeStampedModel): objects = EnrollmentManager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) @property def end_date(self): return self.enrolled + datetime.timedelta(days=182) -
Nginx Configuration in Docker
I am trying to configure nginx inside docker container. However I can't reach my server ip without defining port number (8000). It seems nginx can't listen on 80 port or something. I almost tried every solution on internet but it still same. Here is my docker-compose.yml: version: '3' services: app: build: context: . ports: - "8000:8000" env_file: - django.env volumes: - ./app:/app - /static:/static command: > sh -c "python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn app.wsgi -b 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data - pgconf:/etc/postgresql - pglog:/var/log/postgresql nginx: build: ./nginx ports: - "10080:80" - "10443:443" volumes: - ./app:/app - ./config/nginx:/etc/nginx/conf.d - /static:/static expose: - "8000" depends_on: - app volumes: pgdata: driver: local pgconf: driver: local pglog: driver: local and nginx configuration: upstream app { ip_hash; server my_server_ip:8000; } server { location /static { autoindex on; alias /static/ } location / { proxy_pass http://app; } listen 80; server_name my_server_ip; } Thank you for your help. -
How do i fix "Failed to initiate tests: Expected [:url, "https://github.com/heroku/heroku-buildpack-python"] to respond to #to_hash" error?
I'm trying to use CI on Heroku to run automatic testing of my Django app. I am not using any special software just: python manage.py test I had gotten the tests to run a few times, but realized they used sqlite3 (which also caused some errors), and so I found out I need to make an app.json-file to get postgres to work with tests, which I have done. But I must have made a mistake: I'm now completely stuck on the following error: Failed to initiate tests: Expected [:url, "https://github.com/heroku/heroku-buildpack-python"] to respond to #to_hash My app.json file that configures the test-environment looks like this now (but I have tried many variations): { "environments": { "test": { "image": "heroku/python", "buildpacks": { "url": "https://github.com/heroku/heroku-buildpack-python" }, "addons": ["heroku-postgresql:in-dyno"], "scripts": { "test-setup": "python manage.py collectstatic", "test": "python manage.py test" } } } } I'm at the end of my wits. I have no idea what this means. And there are like 8 results in google for "Expected [:url, "https://github.com/heroku/heroku-buildpack-python"] to respond to #to_hash", and none of them seemingly have anything to do with this. -
How can i save same selected name in multiple forms in Django
I created model which have 3 different foreign key and created four forms with same model and i'm trying to store same emplooyeename in multiple form which is not storing. Mentioned all detailed in down hope you can understand. Models.py class UserTimezone(models.Model): employeename = models.ForeignKey(Enrollment,db_column='EmployeeName',related_name="enrollment", on_delete=models.SET_NULL,null=True) on_delete=models.SET_NULL,null=True) doorname = models.ForeignKey(DoorInfo,db_column='DoorName',related_name="doornames",on_delete=models.CASCADE) timezonename = models.ManyToManyField(TimeZone,db_column='TimezoneName', related_name="timezone") Forms.py Here i made four forms with same model. class UserTimezoneForm1(forms.ModelForm): class Meta: model = UserTimezone fields = "__all__" def __init__(self, *args, **kwargs): super(UserTimezoneForm1, self).__init__(*args, **kwargs) self.fields['timezonename'].widget = CheckboxSelectMultiple() self.fields['timezonename'].queryset = TimeZone.objects.all() class UserTimezoneForm2(forms.ModelForm): class Meta: model = UserTimezone fields = "__all__" # widgets = {'employeename': forms.HiddenInput()} exclude = ["employeename"] def __init__(self, *args, **kwargs): super(UserTimezoneForm2, self).__init__(*args, **kwargs) self.fields['timezonename'].widget = CheckboxSelectMultiple() self.fields['timezonename'].queryset = TimeZone.objects.all() class UserTimezoneForm3(forms.ModelForm): class Meta: model = UserTimezone fields = "__all__" exclude = ["employeename"] def __init__(self, *args, **kwargs): super(UserTimezoneForm3, self).__init__(*args, **kwargs) self.fields['timezonename'].widget = CheckboxSelectMultiple() self.fields['timezonename'].queryset = TimeZone.objects.all() Views.py Tried to cleaned employeename data in all form but storing only first form value. def usertimezone(request,*args,**kwargs): user_data = UserTimezone.objects.all() if request.method == "POST": form1 = UserTimezoneForm1(request.POST,prefix='form1') if form1.is_valid(): obj = UserTimezone() obj.employeename = form1.cleaned_data["employeename"] obj.doorname = form1.cleaned_data['doorname'] form1.save() form2 = UserTimezoneForm2(request.POST,prefix='form2') form1 = UserTimezoneForm1(request.POST,prefix='form1') if form2.is_valid(): obj = UserTimezone() #obj.employeename = form2.cleaned_data["employeename"] obj.doorname = form2.cleaned_data['doorname'] form2.save() … -
Tf objection detection API deployment on django
I am currently trying to serve into a webapp build in Django however I am facing some difficulties. 1. I have succesfully trained my model and I have the precious frozen_inference_graph. 2. I am creating the webapp on django. I would like to call my model directly from my webapp folder. However, when using the inference method from my webapp folder, no inference is done: there is not bug and the script does nothing . In my tf folder, the script does the proper inference. Do you have any clues? Also I have not found any tutorial for serving tensorflow on Django, are you aware of some? Thanks, Have a nice day ! -
How can I query over a manyTOmany model field correctly?
Alright so here's what I am trying to do, as a developer noobie. I am attempting to create an inbox for a user. I have a Conversation model that has a many to many field and then I have an InstantMessanger model the has sender_id, date, and a receiver_id field that is a foreign key to Conversation. What I am attempting to do is iterate over Conversation first and display the members whom the user has had convo's with and then display a link to where it takes you to the actual contents of that message. However, I'm stuck at getting the members to even display. I've tried a number of things here and looked around, but I keep getting errors such as 'conversation' model is not iterable or displaying but displaying as 'dating_app.Profile.none`, the object, and so forth. So I'm pretty stuck here and not sure how to do this. What's the right way to do this? views.py def messages(request,profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user)).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) profile = get_object_or_404(Profile,id=profile_id) conversations = Conversation.objects.filter(members=request.user) return render(request, 'dating_app/messages.html', {'messages': messages,'profile': profile,'conversations':conversations,}) messages.html {% for conversation in conversations %} <li class="text-right list-group-item"> {% for members in conversation %}{% if members != … -
Standard Python VS "New Projects" don't work in Azure
I am trying to create a Python Azure App Service. I have created a number of Python projects (using the normal "File, New Project" in Visual Studio). I haven't changed the solutions or projects in any way (except for creating the required virtual environment for each). I've included a number of flavors of Flask, Bottle and Django projects. For each, after using the VS Publish command, I deploy from the Azure Deployment Center using the Azure repo and the Kudu build. I've also tried the same from VS2017 and VS2019. They all work fine on my local computer (showing Hello World or something similar). They all fail in the exact same way after deploying to Azure. Browsing to the site shows: You do not have permission to view this directory or page. The error log shows: HTTP Error 403.14 - Forbidden As a control, I created and published two different flavors of ASP.NET applications. They both worked fine on my local computer AND on Azure. So, it seems like it must be something Python- or Linux-specific. I've been working and searching on this for a couple of days and haven't found anything. Any suggestions would be greatly appreciated. Bill -
How to export local postgres db with schema and contents to production db
I have a local Postgres db, I would like to use this Db along with the contents in a production db for app. How do I migrate the local db to my nginx production server? -
Django on_delete parameter exists on local code but not on server code
For example, here is my actual code. category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) But on the server (I use pythonanywhere to deploy my code) it has some kind of application error. The error messages are: 2020-04-15 07:12:30,651: Error running WSGI application 2020-04-15 07:12:30,669: TypeError: __init__() missing 1 required positional argument: 'on_delete' 2020-04-15 07:12:30,670: File "/var/www/misterfish_pythonanywhere_com_wsgi.py", line 34, in <module> 2020-04-15 07:12:30,672: application = get_wsgi_application() 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,673: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-04-15 07:12:30,673: django.setup(set_prefix=False) 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,673: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-04-15 07:12:30,673: apps.populate(settings.INSTALLED_APPS) 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate 2020-04-15 07:12:30,674: app_config.import_models() 2020-04-15 07:12:30,674: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models 2020-04-15 07:12:30,674: self.models_module = import_module(models_module_name) 2020-04-15 07:12:30,674: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/quiz/models.py", line 45, in <module> 2020-04-15 07:12:30,675: class SubCategory(models.Model): 2020-04-15 07:12:30,675: 2020-04-15 07:12:30,675: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/quiz/models.py", line 51, in SubCategory 2020-04-15 07:12:30,675: category = models.ForeignKey( Clearly the server didnt recognize there is a on_delete method. It took me some time to figure out there might be something wrong with the server code. So I look into it. quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', … -
django how to perform query on two models?
i have two models 'Post' and 'Like' which are in foreignkey relation. if i want to list all post(published=True) with number of likes of each post how to do in django query. Post.objects.filter(published=True).?.....join(count likes) -
Django CRUD - create and update view doesn't work
I'm really new to Django and I want to teach myself by making a simple note. I maked a simple form for creating a new note but I don't know how to make this just for the user is logged in. What I mean is that I want the user field from the creationNoteForm to be removed and the note to be sumbitted automatically for the person who is logged in. Hope that I was clear enough. Here is my "view.py": from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .forms import CreateUserForm, CreateNoteForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * # Create your views here. def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username or pasword is incorrect') context = {} return render(request, 'accounts/login.html', context) def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for '+ user) return redirect('home') context = {'form': form} return render(request, 'accounts/register.html', context) def logoutUser(request): logout(request) … -
making proxy authentication server in Django
I want to make a proxy server in python django (3.0) like the one at the following link: https://blogs.oracle.com/wssfc/handling-proxy-server-authentication-requests-in-java -
Converting HTML to Draft-JS ContentState in Python/Django
I'm migrating from using a html wysiwyg editor (CKEditor) to using Draft-JS and want to be able to convert existing HTML data into Draft-JS ContentState in a Django Migration but I've been unable to find a way to do this. Is this possible? Or is this even the correct approach? -
Choose SendGrid Template in Django
I'm Trying to send email using sendgrid and its sent successfully but when I tried to create template in sendgrib and I use there test to send email I received that email with correct template, I dont know how to select template_id in django mail = EmailMultiAlternatives( subject="Your Subject", from_email="from email", to=["to email"], headers={} ) and i added this line mail.template_id = 'template_id' mail.send() I received empty email , how can i select he template id in django ? many thanks -
Django - Not found error with Daphne and Nginx
I'm trying to deploy a Django/Django-Channels application a VPS. My environment is: django django-channels venv gunicorn nginx My project is called WaitingRoom and it is located at: WaitingRoomVenv |->WaitingRoomEnv |->WaitingRoom (here are the Django files) To deploy my project, i followed this tutorial. Here is my nginx configuration file: upstream app_server { server unix:/tmp/daphne.sock fail_timeout=0; } server { listen 443 ssl http2; server_name 54.39.20.155; client_max_body_size 20M; # this is optionally, I usually put it very big in nginx and do proper size checks in the application location /static/ { sendfile on; location ~* \.(?:ico|css|js|gif|jpe?g|png|svg|woff|bmp)$ { expires 7d; } alias /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { proxy_pass http://54.39.20.155; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header X-Forwarded-Proto "https"; proxy_set_header Connection "upgrade"; add_header Referrer-Policy "no-referrer-when-downgrade"; } } And here is my Daphne service: [Unit] Description=daphne service to run Channels on WaitingRoom After=network.target After=nginx.service [Service] Type=simple RuntimeDirectory=daphne PIDFile=/run/daphne/pid User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/daphne -u /tmp/daphne.sock WR.asgi:application ExecStop=/WaitingRoomVenv/WaitingRoomEnv/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target The problem with my actual code is that whenever i try to reach any part of the site, i get a 404 Not Found Error. Here is how i did it: I uploaded my project to the VPS, … -
Python 3 Django Rest Framework - how to add a custom manager to this M-1-M model structure?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student from django.db import models from model_utils.models import TimeStampedModel class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class EnrollmentManager(models.Manager): def org_students_enrolled(self, organisation): return self.filter(student__organisation__name=organisation).all() class Enrollment(TimeStampedModel): objects = EnrollmentManager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Notice the custom EnrollmentManager that allows me to find all students who are enrolled from a given organisation. How can I add a custom Manager to retrieve all the courses from a given organisation whose students are enrolled? class EnrollmentManager(models.Manager): def org_courses_enrolled(self, organisation): return self.filter ... ? -
Python 3 Django-Rest-Framework - how to create a custom manager for a M-1-M relation?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class Enrollment(TimeStampedModel): objects = models.Manager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Given an Organisation name I would like to add a custom manager for Enrollments, like this: class EnrollmentManager(models.Manager): def org_student_count(self, organisation): return self.filter(student__organisation__name=organisation).count() So I can query like this: Enrollment.objects.org_student_count('AEKI') <- returns 100 The problem is that I always get the same result, regardless of what I pass in: Enrollment.objects.org_student_count('TRUMP') <- returns 100 but should be 0 -
Django get_or_create causing database error
Using get_or_create in Django causes the following error: Traceback (most recent call last): File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\sande\Documents\projects\sbbetting\football\management\commands\scrape.py", line 12, in handle sofa.get_matches() File "C:\Users\sande\Documents\projects\sbbetting\football\common\sofascore.py", line 21, in get_matches country = Country.objects.get_or_create(sofascore_id=country_id, name=country_name, defaults={"sofascore_id": country_id, "name": country_name})[0] File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 538, in get_or_create return self.get(**kwargs), False File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 402, in get num = len(clone) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 256, in __len__ self._fetch_all() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 1098, in execute_sql cursor = self.connection.cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor self.ensure_connection() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.init_connection_state() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\mysql\base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\mysql\features.py", line 81, in is_sql_auto_is_null_enabled with self.connection.cursor() as cursor: File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 225, in _prepare_cursor self.validate_thread_sharing() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 547, … -
renaming file when uploading with django modelform
I'm new to django and currently following a tutorial where it uses a ModelForm for a User Profile where a user can upload an avatar. I want to be able to update the file that they upload to a generated id. I'm just not sure where and how to do capture and update the file. My Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar_default.jpg', upload_to='profile_images') def save(self,*args, **kwargs): super().save() img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.avatar.path) def __str__(self): return f'{self.user.username} Profile' Form class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar'] View @login_required def user_profile(request): if request.method == 'POST': user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f'Your profile has been updated') return redirect('users_profile') else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) context = { 'user_form': user_form, 'profile_form': profile_form } return render(request, "users/profile.html", context) I tried to apply some recommendations online where you do a Commit=False when saving the form and store that in a variable and renaming the file, it was a whole lot of confusion in the end. -
Datetimepicker plus DJANGO not loading correctly
I have been going crazy in order to understand what's going on but I can't seem to figure out what is the problem. It only happens in production, not in dev server. Here is my config: Settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] base.html (the layout im extending) <!DOCTYPE html> <html lang="en"> {% load static %} {% load bootstrap4 %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>WHARFY</title> {% bootstrap_javascript jquery='full' %} {% bootstrap_css %} <!-- Custom fonts for this template--> <link href='{% static "vendor/fontawesome-free/css/all.min.css"%}' rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href='{% static "css/sb-admin-2.min.css" %}' rel="stylesheet"> model_update.html (Im using UpdateView) {% extends 'base.html' %} {% load bootstrap4 %} {% block content %} {{ form.media }} <form method="post">{% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Save"> </form> {% endblock %} While in dev I do not have any problems, in production i get this error from the console Failed to load resource: the server responded with a status of 404 (Not Found) datepicker-widget.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) … -
Python 3 & Django Rest Framework - how to query M-1-M models?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class EnrollmentManager(models.Manager): def org_student_count(self, organisation): return self.filter(student__organisation__name="AEKI").count() class Enrollment(TimeStampedModel): objects = EnrollmentManager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Given an Organisation ID, I understand that I can get the enrollments for a single student, like so: o=Organisation.objects.get(id=1) o.student_set.all()[0].enrollment_set.all() but how can I retrieve ALL Enrollments for a given Organisation? For example, if I wanted to count how many students from a given organisation have enrolled on courses? Something like this: o.student_set.enrollment_set.count()