Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect Django app on DigitalOcean to domain with insecure
I am making a small app that deals with processing files, making static data and allowing users to view and download the new static data. I have not learned how to do this with python manage.py runserver and I currently run this with python manage.py runserver --insecure (I am also not entirely sure who will hack my website or how is this insecure). I am using digitalocean to host the website and I have setup the DNS from Google domains already. However, I am stuck on what to do next. A few searches say that gunicorn and/or nginx, but how do I configure this so that the --insecure part remains? If this is not possible, is there a way I can maintain a tunnel forever? Ngrok seems to close after some time, but if there a tunnel that I can maintain forever, I can simply redirect this website to the tunnel's url. -
Add group to user
I have created 3 groups 1. Staff, 2. Admin, 3. Operational Manager and assigned permission. Now whenever I wanted to add new user I wanted to show the choice field of the group and able to select the group. As per the framework the User and Groups have many-to-many relations and I am trying to implement nested serializer. And as per documentation to add nested data I need to implement create or update method in the serializer but here I am not getting the choice field in group and the data is null. GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) UserSerializers: class UserSerializers(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = User fields = ('first_name', 'last_name','address','contact', 'email', 'date_of_birth', 'branch', 'groups') def create(self, validated_data): groups_data = validated_data.pop('groups') user = User.objects.create(**validated_data) for group_data in groups_data: Group.objects.create(user=user, **group_data) return user when I wanted to make a post request I am getting : { "first_name": "", "last_name": "", "address": "", "contact": null, "email": "", "date_of_birth": null, "branch": null, "groups": [] } here groups fields are empty. If I try to make a post request it says { "groups": [ "This field is required." ] } -
UNIQUE constraint failed when trying to use ForeignKey
I have the following models.py: from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return self.name class MenuSection(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, ) food_type = models.CharField(max_length=50) def __str__(self): return self.food_type + " - " + self.restaurant.name class MenuItem(models.Model): MenuSection = models.ForeignKey( MenuSection, on_delete=models.CASCADE, ) food_item = models.CharField(max_length=50) def __str__(self): return self.food_item + " - " + self.restaurant.name When I try to migrate these changes I get the error: " no such column: core_menuitem.id" at the command line and when I try and access /admin it says: "no such column: core_menuitem.id". Does anyone know what the issue is? Thanks in advance -
pdf file doesn't save in Django
I use Django 2.1.4 and use Django sample for create pdf report def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. return FileResponse(buffer, as_attachment=True, filename='hello.pdf') It started dowloaded but never finished. What is wrong? Old version works properly def some_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response -
Django Social Media Home page architecture
I am making a facebook style webapp. Where if you friend someome (In my case follow someone) you will see all the activity that the person who you are following does. Example He likes a post. He creates a new post.He joins a group. There are 10 to 15 different things that the user can do.I want all his followers to see on their homepage what he does. If the user is folowing 2 different people. I want all the activities to show in chronological Order Example Today at 6pm Alpha liked this post Jasjdajkd sjjdhaskdh sahjkkdhkahskdh Today at 7pm Beta joined this group The gardening Group Today at 8pm Alpha commented on this post Is climate change for real Below is my monkey patch in models.py for my user follow/following class Contact(models.Model): user_from = models.ForeignKey(User, related_name='suppporter') user_to = models.ForeignKey(User, related_name='leader') def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) Can someone recommend a way in which I can achieve this -
What do you use for the Host name when trying to connect to a local MSSQL database in Django?
My database settings look like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Test', 'USER': 'Dev1', 'PASSWORD': '******', 'HOST': 'Compname\\TESTDB', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, }, } I'm not entirely sure what I am doing wrong. Any help would be greatly appreciated. -
Django: How do I refer to app templates that are in a separate templates/app folder succinctly?
In the Django documentation, one is instructed to create templates folders within each app AND then another folder within the templates folder with the name of the app. So if my appname is 'orders', then the template path for 'index.html' would be: /some_project/orders/templates/orders/index.html If I am trying to refer to that template in views, how can I refer to it as just index.html rather than orders/index.html? The one solution that works is putting all the templates into the orders/templates/ folder, but that goes against django recommendations. -
Cannot create multiple objects of same name using ForeignKey
I am creating a website to host different menus from restaurants in my town. In the code below Restaurant is the establishment, MenuSection is a section such as Appetizers, Entrees, Desserts, etc... and FoodItem is a dish you can order belonging to one of the sections on the menu. I am trying to connect each MenuSection to a Restaurant and each FoodItem to a MenuSection and Restaurant. I thought this could be achieved using a ForeignKey since it is a many-to-one relationship. Obviously, food sections and food items are going overlap between restaurants. I thought this would not be an issue but in my db I have two Restaurant objects, one already has a MenuSection named "Appetizers", I tried to give the second Restaurant a MenuSection named "Appetizers" and it will not let me do so, saying: "MenuItem with this MenuSection already exists." How can I fix this? Thanks in advance for any help. from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return self.name class MenuSection(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, primary_key=True, ) food_type = models.CharField(max_length=50) def __str__(self): return self.food_type class MenuItem(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, primary_key=True, ) MenuSection = models.ForeignKey( MenuSection, on_delete=models.CASCADE, … -
Django-storages & boto3 - "Could not load Boto3's S3 bindings"
Recently had an issue where i had to rebuild my local environment. in doing so, for some reason django-storages and boto3 aren't working anymore. I'm looking for any help as to why. (I had custom locations for the Media and Static following these instructions, these have been removed hoping that normal settings would work but to no avail: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ - yet i can't find any documentation to find out why these may or may not work any more) AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com:443' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' getting out this error consistently and not sure why. Am i missing some kind of dependency to work with these plugins? File "/Users/daniel/Library/Python/2.7/lib/python/site-packages/storages/backends/s3boto3.py", line 22, in <module> raise ImproperlyConfigured("Could not load Boto3's S3 bindings.\n" django.core.exceptions.ImproperlyConfigured: Could not load Boto3's S3 bindings. See https://github.com/boto/boto3 Any help appreciated! -
How Iterate in a folder on s3 by using boto3?
In my instance in the s3 I have a folder with N files, I need to iterate in this using this script bellow, I need to get all files and convert it, this script is hosted on a ec2 instance working with django. I tryed a lot, by using the boto3 function get_object but all I get is nothing. Can someone tell please how can I do something like that?, I'll need to download this files before convert or can I do it directly? def upload_folder_to_s3(local_folder, destination_folder, s3_bucket): ''' Function to upload a specific local folder to S3 bucket. Parameters: local_folder (str): Path to local folder. destination_folder (str): Path to destination folder on S3. s3_bucket (str): Bucket name on S3. Return: ''' # Global variables global client # Iterate over files on folder for root, dirs, files in os.walk(local_folder): for filename in files: print(filename) # construct the full local path local_path = os.path.join(root, filename) # construct the full Dropbox path relative_path = os.path.relpath(local_path, local_folder) s3_path = os.path.join(destination_folder, relative_path) # relative_path = os.path.relpath(os.path.join(root, filename)) print('Searching "%s" in "%s"' % (s3_path, s3_bucket)) try: client.get_object(Bucket=s3_bucket, Key=s3_path) print("Path found on S3! Skipping %s..." % s3_path) # try: # client.delete_object(Bucket=bucket, Key=s3_path) # except: # print … -
Executing a looping python script via a Django web page
Looking for some guidance or advice. I am running a Django app on a Raspberry Pi that serves it locally. The purpose of this project is to run a looping python script on the raspberry pi that records data from a scale (Load cell) twice every second using the GPIO pins on the raspberry pi. The goal is to have a django webpage where a user can start and stop the python script and view the live weight data that is measured by the script. How do I run this python script from django and have it communicate with django view? Django channels, Websockets, supervisor? Any help is appreciated. -
What is the best approach for making view with editable multiple objects?
I want to create editable object list view(without Django admin panel) where staff users can easily manage their objects. What is the best approach to do this? -
This is a small function to delete an object.. i wanted to ask that how instance.get_another_url() works even though instance got deleted?
def post_delete(request,id): instance= get_object_or_404(Post , id=id) instance.delete() messages.success(request , "Post deleted!") return HttpResponseRedirect(instance.get_another_url()) -
Message order in a chat box without javascript using bootstrap 4
I was wondering if there is a way to adjust my chat box so that messages appear coming form the bottom, as any chat app work. I am using Django and bootstrap 4, here is my code: <div class="list-group flex-column-reverse " id="Chatting" style="transform: rotate(-180deg);"> {% for message in object.messages.all %} <a class="list-group-item list-group-item-action border-white " {% if message.user == user %} style="background-color: rgba(190,229,235,0.1);"{% endif %}> <div class="row text-lowercase" style="height: 15px;"> <div class="col text-left"> <p style="font-size: 10px;">{{ message.user.first_name }} {{ message.user.last_name|slice:":1" }}</p> </div> <div class="col"> <p class="text-right" style="font-size: 10px;">{{ message.date|date:"SHORT_DATETIME_FORMAT" }}</p> </div> </div><span> {{ message.text|linebreaks }} {% if message.attachment %} <img src="{{ message.attachment.url }}" width="50%" ></img> {% endif %} </span> </a> {% endfor %} The id list of name has overflow: auto on it. If I use the code without The rotation part and without flex-column-reverse, the list of messages begin from the top of the box, which is counter-intuitive. If I use only flex-column-reverse I get the ordering correct but when the page loads it loads with the oldest message and the user has to scroll down, it also means everytime he writes a message he has to scroll down again. The hack that I am using works by showing … -
Simplify url patterns according to methods
I am starting my journey with Django. As my first project with it i decided to create Shopping List API with use of django-rest-framework. I notice a significant expansion of the code when i start write url patterns with according methods to them. So my question is How can i simplfy my code? Is it possible? Code: from django.urls import re_path from rest_framework.urlpatterns import format_suffix_patterns from shopping_list.views import RegisterUser, LoginUser, LogoutUser, Users, ShoppingLists, Items # binding shopping_lists = ShoppingLists.as_view({ 'get': 'get', 'post': 'post', 'put': 'put', 'delete': 'delete' }) shopping_list_id = ShoppingLists.as_view({ 'get': 'get_by_id' }) shopping_list_name = ShoppingLists.as_view({ 'get': 'get_by_name' }) items = Items.as_view({ 'get': 'get', 'post': 'post', 'put': 'put', 'delete': 'delete' }) item_id = Items.as_view({ 'get': 'get_by_id', }) item_name = Items.as_view({ 'get': 'get_by_name' }) urlpatterns = format_suffix_patterns([ re_path('^auth/register/$', RegisterUser.as_view()), re_path('^auth/login/$', LoginUser.as_view()), re_path('^auth/logout/$', LogoutUser.as_view()), re_path('^users/$', Users.as_view()), re_path('^shoppinglists/$', shopping_lists), re_path('^shoppinglists/(?P<id>[0-9]+)/$', shopping_list_id), re_path('^shoppinglists/(?P<id>[a-zA-Z]+)/$', shopping_list_name), re_path('^items/$', items), re_path('^items/(?P<id>[0-9]+)/$', item_id), re_path('^items/(?P<id>[a-zA-Z]+)/$', item_name), ]) -
Stripe: Card not being declined on charge attempt (0341)
I'm using the card 4000000000000341 in testing mode on Stripe. This card supose to behave like this: Attaching this card to a Customer object succeeds, but attempts to charge the customer fail Despite this, when I try to charge this source it succeeds. What could be happening? -
Django - Disable form select field validation for a drop down
How do I disable the form field validation for the drop down list? In .js file I use Ajax return the json data from database and populate it to the drop down list. When I try to save the form it gave me this validation error. In the forms.py: class CreateAForm(forms.ModelForm): DUMMY_LIST =[] ptvb_dept= forms.ChoiceField(choices= DUMMY_LIST) -
Django Json Field Query
I've a JSONField in my model which is storing below types of data. [ { "name":"Name A", "type":"Type1", "class_type":"Class A" }, { "name":"Name B", "type":"Type1", "class_type":"Class A" }, { "name":"Name C", "type":"Type2", "class_type":"Class A" } ] I've tried with the example of django documentation. But still return Null I've tried with SampleCategory.objects.filter(books__name = 'Name A') -
django-registration with password containing special chars
I would like to create a sign in/registration page. I saw that the default django library does not provide such function (any reason why?), however it seems that the library django-registration can help me. However, I don't like the default settings for the password's allowed chars: Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. Indeed, I don't see any reason why a website would force the users to have a password without special chars others than @/./+/-/_... Can I change this setting so that the user can use any char he wants? Thanks! -
How to Query Elasticsearch via URL in Python Django Application
I am brand new to both Elasticsearch and Django. I have been tasked with automating a report to be downloaded by the user who will type an Elasticsearch query into a URL and it will then produce a downloadable document. So far, I have been able to get it working by running a simple query through the url where the piece of the url is hard-coded into models.py and urls.py. However, I have more complex queries that need to run through but I'm not sure how to have the user type it into the url and then pull from there to populate my Elasticsearch query. I have looked at the official documentation on URI and API but I'm at a loss as to how to actually implement anything I've read. url user currently types to get the info http://localhost:1234/download/user123/ sample simple query {"query": {"match" : {"Username" : "user123"}}} sample complex query { "query": { "bool": { "must": [ {"match_phrase": { "Username":"user123"}}, {"bool": { "should": [ {"match": {"Action":"action1"}}, {"match": {"Action":"action2"}} ] }}, {"bool":{ "must_not":{"multi_match":{ "type":"phrase", "query":"deleteme", "lenient":true}}}}, {"range" : { "EventDateTime" : { "gte": "1513555200000", "lte": "1545091200000" } }} ] } } } models.py (only relevant sections included) # Import libraries … -
Django form not creating object
Django newbie, so sorry in advance! Form shows all the fields, but the form.is_valid() returns false always. The thing is that a form with exact same procedure works, but not this. Code is attached view.py def signup(request): form ="jugar" if request.method =="POST": form = UserForm(request.POST) if form.is_valid(): userform = form.save(commit=False) userform.save() return redirect('minerva:login') else: form = UserForm() return render(request,'minerva/signup.html',{'form':form},) signup.html {%extends 'minerva/base.html'%} {% load staticfiles %} {% block title %}Sign Up{% endblock %} {%block slider %} {%endblock%} {% block body %} <h2>Sign up</h2> <form method="POST" id="contact-form" class="post-form, contact-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default, button button-mini">SignUp!</button> </form> {% endblock %} Forms.py from .models import Post, Comment, Message, CustomUser from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'content',) class MessageForm(forms.ModelForm): class Meta: model = Message fields = ('sender' , 'receiver', 'msg_content',) class UserForm(forms.ModelForm): class Meta: model = CustomUser fields = ('username' , 'email' , 'password' , 'ProfileImage' , 'MasterOf', 'intro',) Models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone import datetime class CustomUser(models.Model): username = models.CharField(max_length=250) email = models.EmailField(max_length=250) password = models.CharField(max_length=250) ProfileImage = models.ImageField() MasterOf = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) intro = models.TextField() … -
How to Configure IIS to run a FastCGI application
I am trying to get a django app to run using IIS. These are the versions in use: django: 1.9 python: 2.7 Windows: Server 2016 IIS: 10 I am following the directions from this site: https://www.toptal.com/django/installing-django-on-iis-a-step-by-step-tutorial I am up to this point Configuring IIS to run a FastCGI application Click OK on the handler information dialog. IIS will then ask you to confirm the creation of a matching FastCGI application entry which you will need to confirm. This entry will be visible in the FastCGI Settings feature, accessible at the root screen of the IIS Management Console. But when I go to the CGI settings that application is not listed. Can anyone offer any advice on what I may be missing or doing wrong or how I can debug this further? -
ValueError: not enough values to unpack (expected 3, got 2) with Django's path() and Heroku
My urls.py code on Heroku keeps having issues, path() (presumably) is throwing this error ValueError: not enough values to unpack (expected 3, got 2) urls.py from django.conf.urls import url, include from django.urls import include, path from thinkster_django_angular_boilerplate.views import IndexView from django.contrib import admin from rest_framework_nested import routers from authentication.views import AccountViewSet from authentication.views import LoginView, LogoutView admin.autodiscover() router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = [ path('admin/', admin.site.urls), # ... URLs path('api/v1/', router.urls), path('api/v1/auth/login/$', LoginView.as_view(), name='login'), path('api/v1/auth/logout/$', LogoutView.as_view(), name='logout'), path('^.*$', IndexView.as_view(), name='index'), ] I tried adding the name to the first two urls to no avail. It looks like I'm passing all the necessary arguments. What is the problem? -
Using Reveal.JS Nothing is showing from the slides
I'm trying to build something with Reveal. I have the content in place, it's structured correctly. I can see that the reveal css and the theme css are in place. The JS is working, I can see the pages increment. There is no content showing though. Nothing. I can see all the parts moving but no changes in the content. Anyone else ever run into this with Reveal? Code setup (In a Django Template) {% block wrapper %} <div class="reveal"> <div class="slides"> <section><h1>Landing Slide</h1></section> <section></section> <section> {% comment %} The wolott section {% endcomment %} <section></section> <section></section> <section></section> <section></section> <section></section> </section> <section> {% comment %} The coldfire section {% endcomment %} </section> <section> {% comment %} The opus section {% endcomment %} </section> <section> {% comment %} The porter section {% endcomment %} </section> <section> {% comment %} The wsecu section {% endcomment %} </section> <section> {% comment %} The siete section {% endcomment %} </section> <section> {% comment %} Testimonails {% endcomment %} </section> <section> {% comment %} The navigation section {% endcomment %} </section> <section> {% comment %} The contact form {% endcomment %} </section> </div> </div> {% endblock wrapper %} {% block core_js %}{% endblock core_js %} … -
Django : content_type_id in GenericForeignKey
I wrote this class according to documentation to be able to vote on anything with an id in the application : class Vote(models.Model): class Meta: unique_together = ('voted_id', 'voter_id', 'content_type', 'vote_type') voted_id = models.PositiveIntegerField() vote_type = models.BooleanField(null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) voter_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'voter_id') def __str__(self): return self.content_object Then in the database table, I have 5 columns : id, voted_id, vote_type, voter_id, content_type_id I don't really understand what is content_type_id referring to : is it a virtual id ? Because in my understanding, when I wrote : from forum.models import User, Vote kdelanyd = User.objects.get(username='kdelanyd') v = Vote(content_object=kdelanyd, voted_id=1, vote_type=False) v.save() I thought that content_type was holding 'kdelanyd' reference and then, somewhat its id : it does not.