Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I load the first object from a result set?
I'm using PyCharm 2018.2 and Python 3.7. I want to load an object from my database. It doesn't matter, which one, so I just figured the first one that is returned by a query for all objects. I thought I could do this in the console by running obj = Article.objects.first() but this is spawning a bunch of errors taht I can't quite interpret. How do I load the first object from my db? /Users/davea/Documents/workspace/articleclip_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) manage.py@articleclip_project > obj = Article.objects.first() bash -cl "/Users/davea/Documents/workspace/articleclip_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py obj = Article.objects.first() /Users/davea/Documents/workspace/articleclip_project" bash: -c: line 0: syntax error near unexpected token `(' bash: -c: line 0: `/Users/davea/Documents/workspace/articleclip_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py obj = Article.objects.first() /Users/davea/Documents/workspace/articleclip_project' Process finished with exit code 2 -
Django test case loop for all url_patterns for anonymous users
My webapp requires a login, and I want to test that all url_patterns in a django app, badges, redirect to the login/home page. I have a loop here that can handle simple urls: def test_all_badge_page_status_codes_for_anonymous(self): ''' If not logged in then all views should redirect to home page ''' for path in urlpatterns: name = 'badges:%s' % path.name self.assertRedirects( response=self.client.get(reverse(name)), expected_url='%s?next=%s' % (reverse('home'), reverse(name)), ) However, this fails for any path that requires a keyword argument, such as: path('<int:badge_id>', views.detail, name='badge_detail'), How can I automagically, insert arguments for paths so I don't have to write a separate line for each path in url_patterns? -
Background image in inline style
I need to use static files in my inline styles background-image in my HTML page, but the image won't show. I've found all kinds of solutions, but I'm still not sure how to show a background-image from a stic file. It's used in my home.html template in a holidays app <a href="#" style="background-image:url(../../../../../static/img/kreta.jpg);" title="Kreta" alt="Kreta"> I don't see my image now and I expect to see my background-image -
How to troubleshoot failing connection between cloudsql-docker/gce-proxy and deployed Python Container
I have been working on deploying a simple Django project to Google Cloud Platform. However the deployed app always fails with, basically this: Django Version: 2.1.3 Exception Type: OperationalError Exception Value: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Exception Location: /env/lib/python3.6/site-packages/psycopg2/__init__.py in connect, line 130 Python Executable: /env/bin/python3 Python Version: 3.6.7 I can use exactly the same django project deployment locally - connecting to the same cloud sql instance that the deployed app tries to connect to and it works fine. I can duplicate the error locally by simply terminating the local cloud_sql_proxy. This tells me that the python/django app is working the same both locally and deployed. Also the Cloud SQL Database is working fine, but for some reason either the deployed image gcr.io/cloudsql-docker/gce-proxy:1.05 which I use is not working or somehow my deployed app cannot connect to this proxy. I have run through deploying the Django Polls app a few times [https://cloud.google.com/python/django/kubernetes-engine] which is well known to the community and successfully done this a few times to develop some familiarity, then applied the same steps to my own project as a way of addressing this. My pod … -
Graphene No module named django-filter
So I'm trying to use the filters option from GraphQL (i'm using graphene since i'm developing a django app). The problem is that in order to add my filter fields in the schema class PropertyType(DjangoObjectType): class Meta: model = Property interfaces = (graphene.relay.Node,) filter_fields = { "id": ["exact"], "name": ["icontains"], } I need to have the django-filter package installed which I had pip installed (pip3 install django-filter) but I can't seem to be able to add it to django's INSTALLED_APPS ModuleNotFoundError: No module named 'django-filter' Env: python 3.7, django 2.1.4, django-filter 1.1.0 EDIT: I realized the documentation was asking for django-filter>=2 but it doesn't work even with django-filter 2.0.0 (i'm still getting the same ModuleNotFoundError error) -
FileNotFoundError [Errno 2] No such file or directory: After resizing the images
I am using the below code to resize my images and it works perfectly fine. However when I go to do another activity. Example adding a new post etc I get a error saying FileNotFoundError at /proof/new_proof/i_climbed_this_mountain [Errno 2] No such file or directory: '/home/samir/Samir/do_tasks/src/Task/media/profile_images/admin_big_XkWnEVw_VvyghrW.jpg' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='profile_images/', default='', blank=True, null=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): im = Image.open(self.profile_image) output = BytesIO() basewidth = 300 wpercent = (basewidth/float(im.size[0])) hsize = int((float(img.size[1])*float(wpercent))) im = im.resize((basewidth, hsize)) im.save(output, format='JPEG', quality=100) output.seek(0) self.profile_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Profile, self).save() When I comment out the def save the post starts showing the image correctly. Any Idea what could be causing this -
Multiple Aggregations with grouping in Django
I'm trying to make a dashboard and I have to use django ORM instead of raw queries, but I cannot find the wight equivalent for this SQL query: SELECT * FROM ( SELECT persons.name, SUM(CASE WHEN work_hours.work_type='A' THEN work_hours.count ELSE 0 END) as additional_hours , SUM(CASE WHEN work_hours.work_type='D' THEN work_hours.count ELSE 0 END) as duty_hours, CASE WHEN SUM(CASE WHEN work_hours.stat_type='D' THEN work_hours.count ELSE 0 END) > 0 THEN 1.0*SUM(CASE WHEN work_hours.work_type='A' THEN work_hours.count ELSE 0 END)/ SUM(CASE WHEN work_hours.work_type='D' THEN work_hours.count ELSE 0 END) ELSE -1 END as over_rate FROM daily_work_hours as work_hours inner join personnel as persons on work_hours.person_id = persons.id GROUP BY persons.name order by over_rate desc) stats WHERE duty_hours>100; can anybody help me with this? -
The requested URL was not found on this server hosting Django app with apache and mod_wsgi
I know I am close but I can't figure out what the issue is. This is all quite new to me. I followed this excellent guide https://www.youtube.com/watch?v=Sa_kQheCnds&t=3838s trying to get my Django application up on my Digital Ocean droplet. Also read everything here: https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/modwsgi/ My project works perfectly locally, and even got it working when I opened port :8080 on the server for testing as in the video above, but when I go further and try to host it at the subdomain /expenses I am greeted with the 404: The requested URL /expenses was not found on this server. I am trying to host my django app at: https://example.com/expenses. I believe the issue is something with the SSL configuration and how I have it set up perhaps? I have my working website set up at https://example.com before I attempted to host my django app at: /expenses. Here is the conf file I made when following the video: /etc/apache2/sites-available/expenses_app.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html Redirect / https://example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =www.example.com [OR] RewriteCond %{SERVER_NAME} =example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] Alias /media/ /home/taylor/expenses-app/media/ Alias /static/ /home/taylor/expenses-app/static/ <Directory /home/taylor/expenses-app/static> Require all granted </Directory> <Directory /home/taylor/expenses-app/media> Require … -
What is the best way to generate a table (for Game Report)?
I'm creating a site with Python (Django) that should be able to generate automatically tables for game reports that look like this (This is how I was making them in Numbers for Mac). The template is every time the same, but the names of players and teams should be wrote dynamically. I need the template to be fancy. I just need to write and print the file, so I'm considering every format: .pdf, .numbers, .xml, .xlxs ... -
Filter date by month DRF
I want to filter a model that I've created by month & year. This is my model: class Cotisation(models.Model): date = models.DateTimeField() campagne = models.ForeignKey(Campagne, on_delete=models.CASCADE) class Meta: managed = True db_table = 'cotisations' ordering = ['-id'] This is my view: class CotisationViewSet(viewsets.ModelViewSet): queryset = Cotisation.objects.all() serializer_class = CotisationSerializer pagination_class = StandardResultsSetPagination filter_backends = (filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter,) filter_class = CotisationFilter search_fields = ('organism__name', 'organism__num_onic') ordering_fields = ('date',) And this is my filter class: class CotisationFilter(django_filters.FilterSet): month = django_filters.NumberFilter(field_name='date', lookup_expr='month') year = django_filters.NumberFilter(field_name='date', lookup_expr='year') class Meta: model = Cotisation fields = ['organism__id', 'campaign__id', 'campaign__year', 'month', 'year'] When I try to query by year it works well: GET http://{{URL}}/cotisations/?year=2019 But it doesn't work when I try with month: GET http://{{URL}}/cotisations/?month=10 Thank you in advance. Best, Jeremy. PS: And Happy new year! -
Pre-filling a django form only if object is not 'None'
I have a django form that pre-fills with certain data: def edit_song(request, song_id): """Edit a song.""" song = Song.objects.get(id=song_id) if request.method != 'POST': # Initial request; pre-fill form with current song info. producers = [] for producer in song.producer.all(): producers.append(producer.name) data = {'artist':song.artist.name, 'producer':", ".join(producers), 'label':song.label.name} form = AddSongForm(instance=song, initial=data) This works fine unless the 'label' object is 'None' (which is possible because it's optional), in which case I get the following error message: AttributeError at /great_songs/edit_song/727/ 'NoneType' object has no attribute 'name' How do I make the django form pre-fill label ONLY if it is NOT a 'NoneType' object? -
Best way to chart data in django-tables2 dable
I'm working on my first Django website and have a table setup with a number of filters which more or less follows this tutorial. I'd now like to complement this with a line chart. I have found I could do this with Javascript using the django-chartjs package by capturing the URL params and passing these via javascript to get the data in JSON format similar to the django-chartjs tutorial. This doesn't however seem to be the best way of solving this problem and ideally I'd prefer not to expose a further URL unnecessarily. var urlParams = new URLSearchParams(window.location.search); $.get('{% url "line_chart_json" %}'+"?"+urlParams, function(data) { var ctx = $("#myChart").get(0).getContext("2d"); new Chart(ctx, { type: 'line', data: data, }); }); Can anyone recommend a Django package which would work nicely with tables2, has some documentation available for doing this (or could provide some sample code) and is free for commercial use (so avoids Highcharts). -
Could not able to subscribe the topic by django http endpoint
I tried a lot. I followed the post https://docs.aws.amazon.com/sns/latest/dg/sns-http-https-endpoint-as-subscriber.html also make my ec2 security group inbound change to anywhere http port 80. I have also taken help from the similar question here How can i confirm the subscription request HTTP from amazon SNS also here Cannot get HTTP subscription confirmation request in views.py def unsub(request): content = "" if request.POST: json1 = request.body.decode('utf-8') print(json1) f = open('home/json.py','w') f.write(json1) f.close() f = open('home/json.py','r') content = f.read() f.close() return render(request,'home/json.html',{'content':content}) in urls.py urlpatterns = [ path('unsub2',views.unsubscribe,name="unsubscribe"), ] here is my json.html, <html> <head> </head> <body> <p>{{content|safe}}</p> <form method="post"> <input type="text" name="i1" id="i1"></input> <input type="text" name="i2" id="i2"></input> <button type="submit" >submit</button> </form> </body></html> I have subscribed the sns topic to the http endpoint http://my-ec2-domain.com/unsub2 but I am not getting any response to the page also not any in logs.Please tell me where I did wrong. python 3.5 django 2.1. -
How to fix "server error(500)" of Heroku caused by setting DEBUG to False in Django?
I know this issue has been discussed a thousand times here, but I couldn't stop putting it again as I'd a difficult time finding the cause of this problem and a working solution.So, my problem is when I set DEBUG=True on heroku, everything works, and if it is set to False, it gives server error(500). Please help me! Things I've tried and didn't work: run collectstatic locally and then tried to add, commit and push to Heroku, but didn't work. done ALLOWED_HOSTS = ["herokuapp.com"] Anyhow when nothing worked, switched the database from sqlite to postgres and it is working fine.But somehow, the error still persists! My wsgi.py file looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") application = get_wsgi_application() The heroku logs I see: 2019-01-05T17:41:17.844144+00:00 app[web.1]: [2019-01-05 17:41:17 +0000] [10] [INFO] Booting worker with pid: 10 2019-01-05T17:41:17.857502+00:00 app[web.1]: [2019-01-05 17:41:17 +0000] [11] [INFO] Booting worker with pid: 11 2019-01-05T17:41:18.234497+00:00 app[web.1]: base dir path /app 2019-01-05T17:41:18.240629+00:00 app[web.1]: local settings failed 2019-01-05T17:41:18.357015+00:00 app[web.1]: base dir path /app 2019-01-05T17:41:18.358185+00:00 app[web.1]: local settings failed 2019-01-05T17:41:19.010564+00:00 heroku[web.1]: State changed from starting to up 2019-01-05T17:41:21.230071+00:00 app[web.1]: 10.28.83.116 - - [05/Jan/2019:17:41:21 +0000] "GET / HTTP/1.1" 500 27 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.3; Win64; x64; … -
Access a single serializer (Django Rest Framework)
I might not get understand the concept of serializers right but as I think, serializers are used to represent python objects as json objects. So my question is, I've got a model: class User(AbstractUser): messages = models.IntegerField(default=0) signup_date = models.DateField(auto_now_add=True) last_msg = models.DateField(null=True, blank=True) and a serializer: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ['username', 'password', 'email'] As my API View returns json, I want to pass a serialized username but I don't know how to achieve it. This is a piece of code written without serializers so I'm trying to get the same result using them: chat_session = ChatSession.objects.get(uri=uri) owner = chat_session.owner if owner != user: # Only allow non owners join the room chat_session.members.get_or_create( user=user, chat_session=chat_session ) owner = deserialize_user(owner) members = [ deserialize_user(chat_session.user) for chat_session in chat_session.members.all() ] How can I access my Serializer for a specific user instead of using a custom deserialize_user function -
Django command "django-admin startmyproject" not working?
The above mentioned command is not working. Showing the result after giving command - No Django settings specified. Unknown command: 'startmyproject'. Did you mean startproject? Type 'django-admin help' for usage. -
Django deployment tool
I am looking for ready made deployment tool for django. Looking for tools like following which uses config files value to make deployment. Meteor-up for deployment of meteor.js project. python-lambda for department of python code to AWS lambda. -
Why Django project doesn't load localhost on edge?
I am using Django to create a webapp. I can't load the webapp on Edge. It works normally with Chrome and Firefox. other projects load normally in Edge, but this specific project it is not working, so I think it's something related to the project itself. This happened right after the project was sent to repository in git. I tried the about:flags options, and the internet options. none of those made it work. I also copied the project folder to other directory and still does not work. What could this be? -
Authenticate DRF automatically when request comes from page with user logged in. Request Token auth if api request is made externally
I have overwritten the custom user model such that I can login using email instead of username and such that I can redirect to changepassword on first login. def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() if user.last_login is None: login(request, user) return redirect('accounts:change_password') else: login(request, user) return redirect('home') else: form = AuthenticationForm() if request.user.is_authenticated: return redirect('home') else: return render(request, 'login.html', {'form': form}) I have set up a basic rest API endpoint using DRF class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer When I access the homepage, I need to be logged in: @login_required(login_url="/accounts/login/") def home(request): return render(request, 'index.html', {}) What I would like to do is to authenticate using django.contrib.auth and be redirected to homepage. When the homepage loads, I would like to perform an AJAX call to display all users. $.ajax( { type: "GET", url: '/accounts/users/', success: function(result){ console.log(result); } }); This call should only work if I am logged in with my user already. If I access the endpoint externally, let's say in Postman, It should ask me to authenticate. I should be able to authenticate externally in postman … -
Is there a way run a python script on another server?
I have a Djnago web application on IIS 6 on one server. Is there a way that from this website I call another python script that is on another server in such a way that that script just run itself there? Calling or Runnig that script in the usual way as internet says, is not working. I always get the error of os.getcwd() and it also doesn't allow to change that directory. I just want to run that python script there on that server from this server. Can anyone help? -
How to use Systemd for Django-q daemon
I use Django-Q for task queue and scheduler. I need to keep running the command: python manage.py qcluster. How can I do it with Systemd? I've found this code for .service file but I don't know how to use my Virtualenv for python path: [Unit] Description=Async tasks runner After=network.target remote-fs.target [Service] ExecStart=/usr/bin/django-admin qcluster --pythonpath /path/to/project --settings settings User=apache Restart=always [Install] WantedBy=multi-user.target -
How can I access model fields from a foreign key which is link to another model?
I have a model which contains a user, each user is associated to a club, a club can contain many teams, pitches etc. I want to know how I should design my models so that I can display/edit information on teams/pitches based on the user logged in and the club associated to that user. My ClubInfo model contains a foreign key associated to the user, where as my other models (Team/Pitch) have foreign keys associated to the ClubInfo not the user. class ClubInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) club_name = models.CharField(max_length=50, default='') club_logo = models.ImageField(upload_to='profile_pics', blank=True) club_address1 = models.CharField(max_length=30) club_address2 = models.CharField(max_length=30, default='') club_address3 = models.CharField(max_length=30, default='') club_town = models.CharField(max_length=30) club_county = models.CharField(max_length=30) club_country = models.CharField(max_length=30) def __str__(self): return self.club_name class Player(models.Model): club_name = models.ForeignKey(ClubInfo, to_field='id', on_delete=models.CASCADE, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) dob = models.DateField(max_length=8) email = models.EmailField(max_length=50) phone = models.CharField(max_length=12) mobile = models.CharField(max_length=15) emergency_contact_name = models.CharField(max_length=40) emergency_contact_mobile = models.CharField(max_length=15) address1 = models.CharField(max_length=30) address2 = models.CharField(max_length=30, default='') address3 = models.CharField(max_length=30, default='') town = models.CharField(max_length=30) county = models.CharField(max_length=30) country = models.CharField(max_length=30) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Team(models.Model): club_name = models.ForeignKey(ClubInfo, to_field='id', on_delete=models.CASCADE, unique=True) team_name = models.CharField(max_length=30) manager_name = models.CharField(max_length=20) player_pk = models.ForeignKey(Player, to_field='id', on_delete=models.CASCADE, unique=True) def … -
Django smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. ...)
I've been trying to let users send email to my personal account via form. At first it was showing me "socket.gaierror: [Errno 11004] getaddrinfo failed" error which I solved by installing and configuring hMailServer in my device. Now when I try to send mail by my friend's email it send email by my own account instead. When I removed "MAIL_HOST_USER = 'my_email' from settings file, it shows "smtplib.SMTPSenderRefused" error as mentioned in title. Any suggestions or related links will be appreciated. Thanks. My code is: settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 25 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_email' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_USE_TLS = True views.py class contact(View): def post(self, request): form = ContactForm(request.POST) if form.is_valid(): if send_mail(subject = form.cleaned_data['title'], message = form.cleaned_data['content'], from_email = form.cleaned_data['contact_email'], recipient_list = ['my_email'], fail_silently=False): return render(request, 'index.html', {'form': form, 'message': 'Message delivered successfully', 'error':'', 'email_sent': 1 }) else: return render(request, 'index.html', {'form': ContactForm(), 'error': form.errors}) -
Django mysql client
I am trying to install python mysql client via pip install mysqlclient. but i am getting error like this Command "c:\users\hardik\envs\py1\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\hardik\\AppData\\Local\\Temp\\pip-install-dsz2ubnd\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\hardik\AppData\Local\Temp\pip-record-q472cwk5\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\hardik\envs\py1\include\site\python3.7\mysqlclient" failed with error code 1 in C:\Users\hardik\AppData\Local\Temp\pip-install-dsz2ubnd\mysqlclient\ what should i do to solve it? -
Passing django-recurrence field via REST API
Folks, I am using django recurrence field in my app and its not clear how to format the field when passed via REST API. Any help is appreciated. from recurrence.fields import RecurrenceField class Course(models.Model): title = models.CharField(max_length=200) recurrences = RecurrenceField()