Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send request in certain date and time in django
i want to send one POST request or GET request in certain date and certain time. Those date and time is stored in database. What should be the approach for that? -
I am getting a 2026, SSL connection error when trying to connect my local django to an Amazon RDS MySQL database
Im trying to connect an Amazon RDS MySQL. It works fine when I run it on my terminal. I can connect with ease, but when I try to connect it using my Django app. It give me this error: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') My database config in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'llda_waterquality', 'HOST': '<host_name>', 'USER': '<rds_uname>', 'PASSWORD': '<password>', 'PORT': '3306', } } -
Django ManyToMany relationship with ModelMultipleChoice Error
I am fairly new to Django. So trying to use inbuilt functionalities instead of overriding the functions. I have established ManyToMany relationship between user and service. Means a user can have many services and a service can be obtained by many users. (Not sure if I am correct) Following are my models Userdata from django.db import models from django.contrib.auth.models import User from services.models import Services class Userdata(models.Model): username=models.OneToOneField(User,on_delete=models.CASCADE) tel=models.CharField(max_length=10,unique=True) address=models.CharField(max_length=100,null=True,blank=True) city=models.CharField(max_length=10,null=True,blank=True) zipcode=models.CharField(max_length=6,null=True,blank=True) services=models.ManyToManyField(Services,through='dashuser.UpcomingUserServices') Services from django.db import models class Services(models.Model): sname=models.CharField(max_length=20) scost=models.IntegerField() def __str__(self): return self.sname UpcomingUserService from django.db import models from services.models import Services from log.models import Userdata class UpcomingUserServices(models.Model): userdata=models.ForeignKey(Userdata,on_delete=models.CASCADE) service=models.ForeignKey(Services,on_delete=models.CASCADE) name=models.CharField(max_length=20) phone=models.CharField(max_length=10) date=models.DateField() address=models.CharField(max_length=100) zipcode=models.IntegerField() remarks=models.CharField(max_length=100,null=True,blank=True) ServiceForm from django import forms from .models import UpcomingUserServices class ServiceForm(forms.ModelForm): service=forms.ModelMultipleChoiceField(Services.objects.all(),widget=forms.CheckboxSelectMultiple()) class Meta: model=UpcomingUserServices exclude=['userdata'] view def book(request): if request.method=='POST': serlist=[] f=ServiceForm(request.POST) if f.is_valid(): s=f.save(commit=False) u=request.user u1=Userdata.objects.get(username_id=u.id) s.userdata_id=u1.id f.save() f.save_m2m() return HttpResponse('Done') else: return render(request,'ns.html',{'f':f}) else: u=request.user u1=Userdata.objects.get(username_id=u.id) i={ 'name':u.first_name+" "+u.last_name, 'phone':u1.tel, 'email':u.email, 'address':u1.address, 'zipcode':u1.zipcode } f = ServiceForm(initial=i) return render(request,'ns.html',{'f':f}) # ns.html is where the form is rendered When the form is submitted, I get following error ValueError at /user/book Cannot assign "<QuerySet [<Services: Lawn Mowing>, <Services: Lawn Fertilization>]>": "UpcomingUserServices.service" must be a "Services" instance (/user/book is view's URL) … -
Django dependent dropdowns along with backend api calls
I'm using Python 3.5.2 and with latest Django version installed. I'm writing a view which consists of dependent dropdowns. When user selects the value from first dropdown, corresponding value should be passed in backend to make an API call and the data obtained, is to be displayed in the next dropdown. I want to create it in the same view. Can it be done in django without using any other technology (like ajax, jquery etc.)? If yes then how? -
Django Unique Together Combination
My scenario is this: class Partnership(models.Model): partner_a = models.ForeignKey( "Person", on_delete=models.CASCADE, related_name='%(class)s_partner_a', ) partner_b = models.ForeignKey( "Person", on_delete=models.CASCADE, related_name='%(class)s_partner_b', ) class Meta: unique_together = (partner_a, partner_b) This works just fine at refusing a duplicate partnership if a=a and b=b: Ex: >>> a = Person('a') >>> b = Person('b') >>> Partnership.objects.create(person_a=a, person_b=b) >>> Partnership.objects.create(person_a=a, person_b=b) # IntegretyError as expected However, it does not correctly refuse the following >>> a = Person('a') >>> b = Person('b') >>> Partnership.objects.create(person_a=a, person_b=b) >>> Partnership.objects.create(person_a=b, person_b=a) # Allowed Is there some class Meta I am missing? Or is there another way to ensure this? (I know I can override the save class, but I'm asking if there is a way to do this without doing that). -
Django test command fail after changing models.py to a directory structure
This is in Django 2.0 , python 3.6.5 I have an app called posts, and I changed models.py to a folder structure, i.e., create a directory models and move the file models.py insid. Also config __ init__.py file, as explained next. The project runs ok, but my test suite fails. In my settings, installed apps i have the app as: 'myproject.apps.posts.apps.PostsConfig' My app config (posts/apps.py) from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' verbose_name = 'posts' I have move posts/models.py to a directory structure. So I have posts/models/models.py posts/models/proxymodels.py posts/models/__init__.py inside models/__ init__.py I do import my models as explained in doc from .models import Job from .proxys import ActiveJob The project works well, but when trying to run tests: python manage.py test I have this error: RuntimeError: Model class tektank.apps.posts.models.models.Job doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The model is a normal one, with fields, nothing extrange. The thing is that if I declare in the meta class Meta: app_label = 'posts' I got the following error: RuntimeError: Conflicting 'job' models in application 'posts': <class 'posts.models.models.Job'> and <class 'tektank.apps.posts.models.models.Job'>. Note: If I use pytest, I run the command: pytest It runs OK -
bootstrap 3 modal - buttons are not working?
I ran This fiddle finely using chrome.(By this i'm meaning that "The button that closed the modal is:" pop-up can work well.) However, I copy-paste the codes to my .js and .html files and they don't work.(the browser remained silence after I click any buttons.) $('#delete-file-modal').on('hide.bs.modal show.bs.modal', function(event) { var $activeElement = $(document.activeElement); if ($activeElement.is('[data-toggle], [data-dismiss]')) { if (event.type === 'hide') { // Do something with the button that closed the modal alert('The button that closed the modal is: #' + $activeElement[0].id); } if (event.type === 'show') { // Do something with the button that opened the modal alert('The button that opened the modal is: #' + $activeElement[0].id); } } }); I'm using Django 2.1.5 and I have customized the bootstrap. In my .html header: {% load staticfiles %} <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <link rel="stylesheet" href="{% static "css/font-awesome/css/all.css" %}"> <link rel="stylesheet" href='{% static "css/bootstrap.css" %}'> <link rel="stylesheet" href='{% static "css/bootstrap.min.css" %}'> <link rel="stylesheet" href='{% static "css/button.css" %}'> <script type="text/javascript" src='{% static "js/createchapter.js" %}'></script> -
Downloading 40,000+ row csv with Django fails with "Network error"
I have a paginated table that consumes data from an endpoint that returns JSON with Django ReST Framework (DRF). Table filtering is achieved through passing URL parameters to DRF. I'm building a button that let's the user download the filtered data as a CSV. The button works with around 10K rows, but failing when the number of results is above 20K. The download is saying Failed - Network error, but I can see in the network tab of Chrome dev tools that the request I made for the csv data is succeeding with a 200 response code. Here is the function that returns the CSV response: def download_csv(data): pseudo_buffer = Echo() writer = csv.DictWriter(pseudo_buffer, fieldnames=fieldnames) rows_to_write = [ {'col1': 'a', 'col2': 'b', 'col3': 'c'}, {'col1': 'e', 'col2': 'f', 'col3': 'g'}, # 40K more rows here that are calculated # from the data parameter which is # serializer.data (a DRF serializer) ] # setup streaming http response response = StreamingHttpResponse( (writer.writerow(row) for row in rows_to_write), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="download.csv"' return response I started by trying to use Django's HttpResponse. This was working for 10K rows, but was failing with 20K+ rows. I switched to StreamingHttpResponse as described in this example … -
Migration - Create table from models to PostgreSQL
In my project of Django, i have four applications. I created a folder named databasemodels. In this folder i created a file: models.py; in wich i implemented all the classes. And after, in the settings.py of the project, i putted the name of the folder "databasemodels" in the INSTALL_APP, to facilitate the migrations. Is it a good idea to work like this ? -
request.POST.get('username') returns NONE
def profile(request): if request.method != 'POST': update_username = request.POST.get('username') u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): p_form.save() #Other if conditions .... else: update_u_form.save() return redirect('/users/profile/') This is the html template: <form method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {{ u_form.as_p }} {{ p_form.as_p }} <button name="sumbit" class="btn btn-primary" >Update</button> </form> {{update_username}} My forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] As I type in updated username, and press submit. However The {{update_username}} always print NONE. What is going on? I thought UserUpdateForm should inherit from User model. So request.POST should have a dictionary key-value pair 'username':username. -
How to implement the moderation of new posts at Django 2.1
I want to moderate new posts created. That is, that it was possible to put a tick in the admin panel, and only after that the post would be published. But ideally, of course, so that the administrator could see the new entries right on the site and allow them to publish right there. models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() moderation = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) forms.py from .models import Post class PostForm(forms.ModelForm): title = forms.CharField(required=True) body = forms.CharField(widget=forms.Textarea) class Meta: model = Post fields = ['title', 'body'] views.py from .forms import PostForm class PostCreateView(FormView): form_class = PostForm template_name = 'blog/post_form.html' success_url = reverse_lazy('posts') def form_valid(self, form): response = super(PostCreateView, self).form_valid(form) form.instance.user = self.request.user form.save() return response admin.py from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('title', 'user', 'moderation') admin.site.register(Post, PostAdmin) urls.py urlpatterns = [ url(r'^posts/$', views.PostListView.as_view(), name='posts'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post-detail'), ] I want it to be like in the picture. Or you can watch and moderate the post right away on the site. enter image description here -
Django Built In AuthenticationForm Not Validating User
I'm trying to build a login system with the Django framework. I extended the UserCreationForm to add names and emails. Now that I have users in the database, I'm trying to authenticate them and log them in. However, when I call the built in AuthenticationForm class, create an instance with the post data, and try to authenticate the user, I get no user returned and authentication fails. All the code for the views.py file is below. I have tried reading the AuthenticationForm source code, but none of that is helping. Any suggestions? from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.db import models from django import forms from django.forms import EmailField from django.forms import CharField from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = EmailField(label=_("Email address"), required=True, help_text=_("Required.")) class Meta: model = User fields = ('email', 'username', 'first_name', 'last_name',) def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.firstName = self.cleaned_data["first_name"] user.lastName = self.cleaned_data["last_name"] user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user def signup(request): if request.method == 'POST': # if sending data to the server form = SignUpForm(request.POST)# creates form from request data if form.is_valid(): user = form.save() … -
Call gRPC Client Stub from External Django Application
I'm following https://blog.codeship.com/using-grpc-in-python/ to use gRPC with Python. Has anyone used the client wrapper (client_wrapper.py ) with an external Django application? I need a way to call the client or client wrapper from an external Django application and obtain a stub to make the RPC calls. Is this possible? Any help would be appreciated. Thanks. -
Django assigning a remote file to a FileField without download and reuploading
I'm using django-storages as my default file storage. I have a script that uploads videos directly from the client to google cloud storage. Is there any way to associate this file to a FileField without downloading and reuploading the file. Thank you for any help! -
Is there a better way to move between Django's views aside from pasting new url?
I'm learning to use Django to build my web application. I want to access another page through a link on the index page, but the browser keeps appending the file and app name to the request. How do I get the browser to switch through links without appending the directory name each time ? I've tried using reg exp with the old url method but it doesn't seem to work # My project # urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), ] # My app # urls.py urlpatterns = [ path('index/',include([ path('', views.index,name="index"), path('theteam', views.theteam,name="theteam"), path('services',views.services,name="services"), path('quotes',views.quotes,name="quotes"), path('insurance',views.insurance,name="insurance"), path('contact',views.contact,name="contact"), path('thanks', views.thanks,name="thanks"), ])), ] # Views def index(request): return render(request, 'index/index.html') def theteam(request): return render(request, 'index/theteam.html') def services(request): return render(request, 'index/services.html') def quotes(request): form = ContactForm(request.POST or None) if request.method == 'POST': return redirect(request, '/thanks/') return render(request, 'index/quotes.html', { 'form': form }) def insurance(request): return render(request, 'index/insurance.html') def contact(request): return render(request, 'index/contact.html') def thanks(request): return render(request, '/thanks.html') #My Views HTML <div class="menu-bar "> <ul> <a href="{% url 'services' %}"> <li>Services</li></a> <a href="{% url 'theteam' %}"><li>The Team</li> </a> <a href="{% url 'quotes' %}"><li>Quotes</li> </a> <a href="{% url 'insurance' %}"> <li>Insurance</li></a> <a href="{% url 'contact' %}"><li>Contact Us</li></a> </ul> </div> So far I've … -
Which platforms to use for backend and Android frontend
I plan to write a service that should communicate both with Android app and Desktop app and send various data (login data, images, texts etc.) My questions are: 1) What to use for backend, on server side I have an experience with Django and MySql but should you recommend something else cause this is a large project and I don't mind learning new stuff 2) What to use for frontend for developing Android app that will communicate with server Here I don't have the any clue, all I ever tried to develop any app but that was very primitive was some previous versions of Delphi XEs; I heard that new Delphi Seattle has great stuff for cross compiling, is it any worth or to complete forget about Delphi? Thanks. -
Django project, I need advice about my model
I need to do opportunity for users to save body# and slug field from Post model in data base, but i have issue i have 10 fields named body1, body2 e.t.c in Post model. User self make choice wich field need to save. How better to save some body# field in data base user ? How to do it in my html code ? class PostDig(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dig') slug = models.SlugField(max_length=150, blank=True) body = models.TextField(blank=True) date_save= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-date_save'] models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = VersatileImageField( 'Image', upload_to='media_my/',null=True, blank=True ) title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True, blank=True) tags = models.ManyToManyField('Tag', blank=True, related_name='posts') body1 = models.TextField(blank=True) body2 = models.TextField(blank=True) body3 = models.TextField(blank=True) body4 = models.TextField(blank=True) body5 = models.TextField(blank=True) body6 = models.TextField(blank=True) body7 = models.TextField(blank=True) body8 = models.TextField(blank=True) body9 = models.TextField(blank=True) body10 = models.TextField(blank=True) date_pub= models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug':self.slug}) def get_update_url(self): return reverse('post_update_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('post_delete_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug= gen_slug(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['-date_pub'] HTML code .. {% extends 'face/base_face.html'%} {% block title %} {{ post.title }} - … -
python web app, trigger async function without separate server
How should I trigger async functions during django/flask views? In node.js, I can easily bypass an async function, like so: module.exports.myView = function (request, response) { myVerySlowFunction(function (nonsense) { console.log('handle triggered nonsense', nonsense); }); response.json({ message: 'ok' }); } This is very typical to do in node, but I've never seen it done in django. I'm wanting to translate it like so: def my_view(request): apply_async(my_very_slow_function) return Response({'message': 'okay'}) I have used Celery in the past for this, but it feels like overkill to have a separate server running just so I can trigger async functions. I know I can trigger async functions like so: https://stackoverflow.com/a/1239252/4637643, but have never seen them in the context of a web application. Is this a bad idea? should I look for another solution? -
Provide lists as required arguments to function (Python)
I'm using a python wrapper to access an api and in the docstring it says that you can provide a lists as required arguments. Here is the function I'm using to call send_orders wrapper function def send_orders(self, runner_id, odds, side, stake, temp_id=None, session=None): """ Place an order(s) on a runner, multiple orders can be places by providing lists of the required arguments. :param runner_id: runner(s) on which to place bets. :type runner_id: int :param odds: odds at which we wish to place the bet. :type odds: float :param side: The type of bet to place, dependent on exchange. :type side: MatchbookAPI.bin.enums.Side :param stake: amount in account currency to place on the bet. :type stake: float :param temp_id: A helper ID generated by the client to help understand the correlation between multiple submitted offers and their responses. :type temp_id: str :param session: requests session to be used. :type session: requests.Session :returns: Orders responses, i.e. filled or at exchange or errors. :raises: MatchbookAPI.bin.exceptions.ApiError """ date_time_sent = datetime.datetime.utcnow() params = { 'offers': [], 'odds-type': self.client.odds_type, 'exchange-type': self.client.exchange_type, 'currency': self.client.currency, } if isinstance(runner_id, list): if isinstance(temp_id, list): for i, _ in enumerate(runner_id): params['offers'].append({'runner-id': runner_id[i], 'side': side[i], 'stake': stake[i], 'odds': odds[i], 'temp-id': temp_id[i]}) else: for … -
How to pass created object in createview right to updateview in django
I have a createview view in my django app: class GroupCreateView(CreateView): ..do tons of stuf def get_context_data(self, **kwargs): ..do more stuf context['group_id'] = None #added this def post(self, request, *args, **kwargs): if self.request.POST.has_key('submit'): ..DO LOTS OF STUFF.. #below I REALLY want to take the object created automagically by the django submit form etc, and pass it right to the update view return HttpResponseRedirect("") I really want to load the page with the created object but as an updateview Anyway to do this from the create view? -
Django get values with point field
I want to get x and y by this queryset: user = User.objects.values('id', 'email', 'username', 'point').first() But I get the following result: {'id': 85270, 'email': 'username_0@email.com', 'username': 'username_0', 'point': <Point object at 0x7f8e061cc2b8>} How can I get an x and y, making an queryset with values ? I want to get something like this: {'id': 85270, 'email': 'username_0@email.com', 'username': 'username_0', 'point__x': '-4.266398314110177', 'point__y': '-39.39432682357033'} -
Tags for relationship in Django
I'm working on an inventory tracking application. Barebones, just for learning. One issue I'm running into is how products can be related. Categories works fine, but a Logitech G35 Mouse could be nested under Peripherals, but Peripherals will be populated with mice, keyboards, headphones, Waacom pads, etc. To help find what we need faster I wanted to incorporate tags of some sort, but I've noticed there's something called Tags native to Django which keeps hijacking my search. Here's my Item model: class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) part_number = models.CharField(max_length=50, blank=True, null=True) introduction = models.DateField(auto_now=True) category = models.ForeignKey('Category', default='Uncategorized', on_delete=models.SET_DEFAULT) quanity = models.IntegerField(default=0) is_retired = models.BooleanField(default=False) def __str__(self): return self.name def add(self): pass def remove(self): pass def retire(self): # Rex came up with this, roll credits. pass def count(self): pass So if I were to add a Logitech G35 Mouse as an item, I'd like the tag(s) to be mouse, mice, wireless and so forth. Where might I find the information needed to implement this? -
register 4 arguments on django admin - TypeError: register() takes at most 3 arguments (4 given)
here is my code.. and I know that I am not alowed to give 4 arguments to register() in django admin.py, but I want to use ProductAdmin and ProductExportImportAdmin together for Product model.. is there possible I am doing that? Is there a way? # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Supplier, Customer, Product, PoOrder from import_export.admin import ImportExportModelAdmin from import_export import resources class ProductResource(resources.ModelResource): class Meta: model = Product exclude = ('id', 'created_at', 'edited_at',) class ProductExportImportAdmin(ImportExportModelAdmin): resource_class = ProductResource class ProductAdmin(admin.ModelAdmin): search_fields = ['code','name'] admin.site.register(Supplier) admin.site.register(Customer) admin.site.register(Product, ProductAdmin, ProductExportImportAdmin) admin.site.register(PoOrder) -
How to pass a table data from and HTML front end to the server side in Django through JSON?
I have multiple tables in the front end. Based on the information provided in the table an oracle database needs to be updated at the back end. The server side is coded in Django and the front end is the typical HTML, Javascript, Bootstrap, Jquery etc. The data is needed to be passed as JSON request since the application sends data to the server side in a JSON format. The question is how to parse the table in the front end, encompass it in an object and send it through JSON and parse it in Python( Django )? My plan is to store the values in a javascript object and then pass it in json format. By I am unable to iterate over the values of the table itself. var exclScoreObj = new Object(); $("#exclTable tr").each(function() { $(this).find('td').each(function(){ console.log($(this).val()) }) }) -
How to make a portfolio page in django
I would like to know what to use on this page for models from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) enter image description here I put a pic of what I'm going for