Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe payment in django form wizard
Does anyone have any experience with requesting a Stripe payment as part of a form wizard in Django? As far as I can tell, the only way to show the user an error when their card is rejected (for instance) when using the wizard is to create the charge in the clean() method of the form - but the wizard calls clean() on the form twice, causing even a valid card to be rejected because the charge is using the same token each time. Obviously it's not ideal to be creating the charge in the form's clean() method but I can't see how to do it outside of there and still be able to show any errors on the individual step in question. Any ideas? -
Does django-sorcery support connection pooling?
I'm playing around with django-sorcery, and so far it looks to me like I'm only getting one persistent connection into the database. Does django-sorcery support connection pooling? If so, how do I control the number of open connections available in the pool? -
Using two different serializer in one endpoint django rest framework
I'm trying to use two different serializers in endpoint but the second serializer that i assign(UserSerializer) is the one that is getting used. Is there a way to have one specific serializer being used for one specific model so that i can use userSerializer for creating a user and the CategorySerializer to create a category. class UserSignup(generics.CreateAPIView): model = Category serializer_class = CategorySerializer model = User serializer_class = UserSerializer def create(self, request): data = request.data category_serializer = self.get_serializer(data=request.data, many=True) user_serializer = self.get_serializer(data=request.data, many=True) -
Django Two Factor Authentication And Twilio
I've been playing with variations of this code for a couple days now....I have successfully set up django two factor authentication on my Windows 10 Pro OS so that it's successfully passing codes in my system log so that I can leverage the fake gateway defined in my settings.py file as shown below. TWO_FACTOR_CALL_GATEWAY = 'two_factor.gateways.fake.Fake' TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.fake.Fake' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'two_factor': { 'handlers': ['console'], 'level': 'INFO', } } } This works flawlessly. The challenge has surfaced when I'm trying to use Twilio to essentially get two factor to work through Twilio. Here is the django two-factor instructions that I used to get two-factor working fine on my Windows machine...https://django-two-factor-auth.readthedocs.io/en/stable/configuration.html I have also set up a test Twilio account...as well as an Authy account on my device...but something seems to be a miss...I can't quite figure out how to pull this all together. The Twilio quickstart instructions that I found here...https://www.twilio.com/docs/authy/quickstart/two-factor-authentication-python-django Seem to be lacking when it comes to cloning and installing the application. Apparently a pip install isn't an option? I feel like this is where the lack of information or lack … -
Displaying date in a required format in django Modelform
I have the following: Model: class customer(models.Model): cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35) ageyrs=models.IntegerField(blank=True) agemnths=models.IntegerField(blank=True) dob = models.DateField(null=True, blank=True) gender_choices = (('male', 'Male'), ('female', 'Female'), ('other', 'Something else'), ('decline', 'Decline to answer')) gender = models.CharField( choices=gender_choices, max_length=10, default='male') maritalstatus_choices = (('unmarried', 'Unmarried'), ('married', 'Married')) maritalstatus = models.CharField( choices=maritalstatus_choices, max_length=10, default='Unmarried') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) email = models.CharField(max_length=50, default='', blank=True) address = models.CharField(max_length=80, default='', blank=True) city = models.CharField(max_length=25, default='', blank=True) occupation = models.CharField(max_length=25, default='', blank=True) bloodgroup_choices = (('apos', 'A+'), ('aneg', 'A-'), ('bpos', 'B+'), ('bneg', 'B-'), ('opos', 'O+'), ('oneg', 'O-'), ('abpos', 'AB+'), ('abneg', 'AB-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=5, default='-', blank=True) class Meta: unique_together = ["name", "mobile", "linkedclinic"] My ModelForm: class RegisterPatientMetaForm(ModelForm): class Meta: dob = forms.DateField(input_formats=['%d-%m-%Y']) model = customer fields = [ 'name', 'ageyrs', 'agemnths', 'dob', 'gender', 'maritalstatus', 'mobile', 'alternate', 'email', 'address', 'city', 'occupation', 'bloodgroup' ] In my template, I have: <div class="col-md-8"> <label for="gender">Date of Birth</label> {{ form.dob }} </div> The issue is that the date is being displayed as %Y-%m-%d, while I want it to display as %d-%m-%Y. What's wrong with how I am doing it? How can I fix this? -
Get all fields when making a innerjoin queryset in django
im trying to obtain all the fields when making a inner join queryset like this one: querysetd = MenuResponseModel.objects.select_related('option').filter(MenuID=menuCreateId) But it keep responding me with the main table fields only. {'id': 2, 'option_id': 7, 'userName': 'miguel', 'MenuID_id': UUID('057e4185-c79d-40ff-b90d-0bee254754c8'), 'comments': 'sin cebolla por favor', 'date': datetime.date(2019, 3, 13)} These are my models class MenuResponseModel(models.Model): option = models.ForeignKey(Menu, blank=False) userName = models.CharField(max_length=50, blank=True ) MenuID= models.ForeignKey(MenuCreateModel, blank=False, on_delete=models.CASCADE) comments = models.CharField(max_length=200) date = models.DateField(auto_now_add=True, blank=True) class Menu(models.Model): option = models.IntegerField(unique=True) description = models.CharField(max_length=100) date = models.DateField(auto_now_add=True, blank=True) MenuID= models.ForeignKey(MenuCreateModel, default=uuid.uuid4, on_delete=models.CASCADE) Thanks for the help- -
Django abstract model inheritance - make all fields nullable in one child
I have an AbstractModel, Model and DraftModel. I need DraftModel to inherit from AbstractModel, but all inherited fields should be null=True. I can't change Model fields to null=True since there is too much logic built on that. I prefer not overriding manually all fields. I tried: def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self._meta.fields: field.null = True Which does not work, do you have any idea? -
invalid literal for int() with base 10: 'user'
Am new to django and i created a model and a signal, on change of a field, it should triger the signal and create a new record in another model with the user_id, but its giving me this error... When i change the status to approved the signal is suppose to create a new object in he ApprovedArticle object but it's showing an error, i don't know what i did wrong Model.py from django.db import models from article.models import Article from adminactivities.models import User, ApprovedArticleStatus from django.utils import timezone DEFAULT_STATUS = 2 class ApprovedArticle(models.Model): user = models.ForeignKey(User, on_delete=models.SET('Unknown')) article = models.ForeignKey(Article, on_delete=models.CASCADE) link = models.CharField(max_length=150) views = models.CharField(max_length=150, default=0) link_views = models.CharField(max_length=150, default='NIL') approved_status = models.ForeignKey(ApprovedArticleStatus, on_delete=models.SET('Uncategorized'), default=DEFAULT_STATUS) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) added_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.article.title def __init__(self, *args, **kwargs): super(ApprovedArticle, self).__init__(*args, *kwargs) self.original_views = self.views DEFAULT_STATUS = 1 class Article( models.Model ): title = models.CharField( max_length = 250 ) category = models.ForeignKey( ArticleCategory, on_delete = models.SET( "Uncategorized" ) ) status = models.ForeignKey( ArticleStatus, on_delete = models.SET( "Pending" ), default = DEFAULT_STATUS ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET( "Unknown" ) ) document = models.FileField( upload_to = 'documents/', null = False ) … -
How to change viewset retrieve response in Django Rest Framework?
I'm currently developing a Web App that uses an API as the backend for a University Project. And I've read that DRF is the fastest and easiest way to develop and deploy an API, I already followed through their entire official documentation and I don't seem to understand how I could the following in their ViewSet and Serializer. Here's one endpoint of my API called airports. All airports available in the USA Returns json/csv list of links to the available airports in the USA. URL /airports Method: GET Success Response: Code: 200 Content: [ { "airport": { "code": "PHL", "name": "Philadelphia, PA: Philadelphia International", "id": 123, "url": "/airports/123" }, { "airport": { "code": "AHR", "name": "American Hour Rapid", "id": 125, "url": "/airports/125" } . . . ] Show Airport Informations Returns all links to the carriers operating at a specific airport, a link to the related statistics on a specific month and year and also a link to the airport routes. If in case neither the year or the month are specified, the default will be the one with the most recent date. URL /airports/:id Method: GET URL Params Required: id=[integer] Success Response: { "airport": { "code": "PHL", "name": "Philadelphia, … -
itertools.imap manipulation Python 2
Context: I have a Django server and the response object to a request is of type: type(response) -> itertools.imap I need to check the size using a custom method. The size check is successful but the response object, or maybe it's contents, get consumed/ emptied out even though my method doesn't alter it. casting the response as a list: list(response) also consumes/ empties it - but the list if filled. Question(s): How do I get the contents of an itertools.imap without consuming/ emptying it? Can I turn the list back into an itertools.imap? -
Django 2.1.7 How to use a decorator on a package view
I would like to know how to use a decorator on a function view.py which do not find it directly in my application, but in a pakage (venv / lib / ...) For more details, I'm going to build an application that uses django-allauth. I create a decorator that asks the user to confirm their password before accessing certain page. All goes well but I would like to use this constructor on the function of aullauth that can manage emails. I do not know how to proceed... enter image description here -
how filter unicode textfield django
i have a model as bellow class CommentOfPost(models.Model): comment_text = models.TextField() comment_text data is unicode('utf-8') looklike 'سلام علیکم' and 'Хороший результат!' some data is 'السلام علیک' and 'سلام علیکم' and 'اسلامی' and 'مرحبا سلام علیک' i want filter looklike CommentOfPost.objects.filter(comment_text_contains='سلام') and result just be queryset<'سلام علیکم','مرحبا سلام علیک'> not be queryset<'سلام علیکم' ,'اسلامی' , 'اسلام علیک','مرحبا سلام علیک',> another word i want regex filter in unicode text -
How to make required field optional for super user in django?
I am trying to make required form field optional for super user in my project. But i am stuck as i don't know how to do that. I want to 'is_super' boolean for required field when super user click on 'is_super' required field should become optional. Thanks Here is ScreenShot of form field: -
Django-Admin Panel Wont Show Records that are inserted throw phpmyadmin?
I have a django admin panel , and this django admin panel is connected to mysql and wamp . My problem is when i insert some records in database using phpmyadmin , django-admin panel wont show records , and just show numbers of them . What this problem is for ? Here is My Model in Django : class Orders(models.Model): objects = jmodels.jManager() product = models.ForeignKey('PartoProducts', models.DO_NOTHING) user_phone = models.ForeignKey('PartoUsers', models.DO_NOTHING, db_column='user_phone') order_date = jmodels.jDateField() status = models.CharField(max_length=11) price = models.CharField(max_length=11) count = models.IntegerField() def __unicode__(self): return self.product.title class Meta: managed = False db_table = 'orders' verbose_name_plural = "Orders" def __str__(self): return '%s------- (%s)' % (self.user_phone,self.status) and This is My Admin.py for this model : class OrdersResource(resources.ModelResource): class Meta : model = Orders fields = ('product__title','product__realprice','user_phone__name','user_phone__family','user_phone__city','user_phone__address','user_phone__nationalcode') @admin.register(Orders) class OrdersAdmin(ImportExportModelAdmin): list_display = ('product','user_phone','price') list_filter = ('product','user_phone','price') search_fields = ('product','user_phone','price') resource_class = OrdersResource Why django wont show any records that are inserted throw phpmyadmin ? I searched alot but not found anything . Any Suggestion will be helpfull . Thanks to this great community . -
'Date does not conform to the required format' after changing language in Django app
The specified value "06-03-2019" does not conform to the required format, "yyyy-MM-dd". I use Django internationalisation in a webapplication and for some reason suddenly I get this error in the developer tools on a form date input after changing the language to Dutch. On English everything works fine, the error is not shown and date is saved correctly. I use he standard django forms dateInput. I searched the webs for hours, before turning to your help. Any suggestions would be greatly appreciated! Thanks. -
Django Admin: JSONField default empty dict wont save in admin
in my model defn i have from django.contrib.postgres.fields import JSONField ..... ....... ......... media_data=JSONField(default=dict) I created a default admin When i attempt to save without touching the field, i get a this field is required error. It looks like a form validation issue because I can programatically save the model instance from code without issue. Why is this happening? have i missed something silly? -
using two parameters in the url while using DeleteView
I was making a blog and I wanted the confirm delete comment to be on the following url route post/<int:id>/comment/<int:pk>/ but when I do this the browser show the following error Reverse for 'comment' with arguments '(38,)' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/comment/(?P[0-9]+)/$'] the code to the programme is given below views.py class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = comment success_url = '/' def test_func(self): comment = self.get_object() if self.request.user == comment.user: return True return False models.py class comment(models.Model): post=models.ForeignKey(Blog, on_delete=models.CASCADE) user=models.ForeignKey(User, on_delete=models.CASCADE) content=models.TextField(max_length=160) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username)) def get_absolute_url(self): return reverse('post-detail', kwargs={"pk": self.pk}) urls.py path('post/<int:id>/comment/<int:pk>/', views.comment_detail, name='comment'), path('post/<int:id>/comment/<int:pk>/delete', views.CommentDeleteView.as_view(), name='comment-delete'), -
Django group by distinct count and convert to d3.js json format
I am attempting to get some data into the following format as a d3.js input: [{'day': 2018-08-09, 'delivered': 29, 'received': 19, 'undelivered':5}, {...}, {...}] I'm running the following which produces the following queryset: messages_by_day = (messages .annotate(day=Cast(TruncDate('msg_date_time'), CharField())) # Truncate to month and add to select list .values('day') # Group By day .order_by('day') .annotate(c=Count('id')) # Select the count of the grouping .values('day', 'c', 'msg_status') ) Is there a better query to run or a good way to reformat the data with the existing query? Thanks! -
How can I embed Django REST API documentation on the Angular landing page?
Any ideas how can I embed Django Swagger Documentation or built-in documentation on the Angular frontend? I mean by clicking documentation button on the landing page the user will be routed to the swagger documentation in the area of the same domain. At the moment I can redirect the user for instance from frontenddomain to backenddomain/doc but it may be bothersome because new tab will be opened in the web browser. Maybe you could recommend other solution than Swagger? I just to want display the user all the endpoints of the api in my landing page. Any ideas? -
Serializing an SQL Function in Django REST
I'm using Django and Django Rest Framework to build an API. I have a custom PostgreSQL function like this: myfunction(from_date, to_date) It simply calculates a figure from records in the date range in reviews table. How can I (safely!) take from_date and to_date from URL query parameters, pass them to the function, and return the (float) result via the API? I have made a simple model to hold the float, like this: class Result(models.Model): result = models.FloatField(default=0) class Meta: managed = False Alternatively, could I forgo the SQL function and implement this directly in Django/REST itself? I already have a model for reviews. In the view for result can I pull my_records from a date range, calculate it, and return the value as a serialized result response? As an end result, I want to be able to curl http://my.api/result?from=2019-03-01&to=2019-04-01 and get the result. Thank you. -
Optimising django queries to avoid duplicates when using detail view and overriding get_context_data
I'm trying to reduce the number of duplicated queries when using CBVs such as DetailView and then overriding get_context_data to filter a model based on related models. Right now, I have a DetailView for a PatientCase model and want to create two variables in the context for a related model CasePhotos the relationship is via a foreignkey on the CasePhoto model. class CasePhoto(models.Model): ... patient_case = models.ForeignKey(PatientCase, on_delete=models.CASCADE) photo = models.URLField() is_mentor_edit = models.BooleanField(default=False) ... Now, I know this is bad, but I cannot seem to find the correct optimal way to do this. Some guidance and even better some documentation links that I've obviously overlooked somewhere would be even better. class ReviewCaseView(DetailView): model = PatientCase def get_context_data(self, **kwargs): patient_case = self.get_object() context = super().get_context_data(**kwargs) case_photos = CasePhoto.objects.filter(patient_case=patient_case) context['case_photos'] = case_photos.filter(is_mentor_edit=False) context['mentor_photos'] = case_photos.filter(is_mentor_edit=True) return context I know that the duplication is line 5 patient_case = self.get_object() as detail.py calls get_object which is what creates the first query. Is there a way of caching this to reuse in get_context_data or maybe a better way without get_context_data at all? -
redirecting to comment section after login is not working in django
it saves and displays comments on the options.html page if the user is already logged in but when the user logs in after comment section redirects to the login page it displays the value error as this: Request Method: GET Request URL: http://127.0.0.1:8000/rank/best-football-players/comment/ Django Version: 2.1.5 Exception Type: ValueError Exception Value: The view rank.views.comment didn't return an HttpResponse object. It returned None instead. urls.py path('<slug>/',views.options,name='options'), path('<slug>/comment/',views.comment,name='comment'), views.py def options(request,slug): category = Category.objects.get(slug=slug) category.views += 1 category.save() options = category.option_set.all().order_by('-votes') try: for option in options: option.has_voted = option.vote_set.filter(voter=request.user).exists() except: options = category.option_set.all().order_by('-votes') form = CommentForm() return render(request, 'rank/options.html', {'options': options,'form':form,'title': 'options','category':category}) @login_required(redirect_field_name='next',login_url='rank:login') def comment(request,slug): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.category = Category.objects.get(slug=slug) comment.user = request.user comment.save() messages.success(request, 'Comment Posted.') return redirect('rank:options',slug) def my_login(request): if request.method == "POST": form = LoginForm(request.POST) username = form['username'].value() password = form['password'].value() user = authenticate(username=username,password=password) if user: login(request,user) redirect_url = request.GET.get('next','rank:home') return redirect(redirect_url) else: messages.error(request,'Invaid Username or Password') else: form = LoginForm() return render(request,'rank/login.html',{'form':form}) options.html {% extends "rank/base.html" %} <title>{% block title %}{{title}}{% endblock title%}</title> {% load bootstrap4 %} {% block content %} <center><br> <ol type="1"> <center>{% bootstrap_messages %}</center> {% for option in options %} <div class="col-lg-6 col-md-6 mb-6"> <div … -
django 2.0 content management system
I am implementing a blog on my website, thats built using Django. I'm interested in using some sort of content management system (where non developers can edit the text). I've looked into djangocms, mezzanine, wagtail, but none of them are compatible with the latest version of django - althought I am aware they are releasing new versions fairly soon. Does anyone have any recommendations about something I could use? -
how to use certbot certificate on a django app via gunicorn an nginx?
i have a django app running on NGINX and created an ssl certificate successfully, when i run the web, it just time out and i have port 443 enabled. server { server_name example.com www.example.com; access_log off; location / { proxy_pass https://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.com www.example.com; listen 80; return 404; # managed by Certbot } this is my /etc/nginx/sites-available/mysite shown above and running sudo ufw status outputs Status: active To Action From -- ------ ---- Apache Full ALLOW Anywhere 8000 ALLOW Anywhere Nginx Full ALLOW Anywhere 443/tcp ALLOW Anywhere 80/tcp DENY Anywhere 22/tcp ALLOW Anywhere 22 ALLOW Anywhere 443 ALLOW Anywhere 80 ALLOW Anywhere 80 on eth0 ALLOW Anywhere Apache Full (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) Nginx Full … -
the JSON object must be str, not 'list' - TypeError
I am loading JSON data in My Database but is giving me error - TypeError - the JSON object must be str, not 'list' from django.shortcuts import render # Create your views here. import json from .models import Movie def detail(request): with open('movie_data.json', encoding='utf-8') as data_file: json_data = json.loads(data_file.read()) print(type(json_data)) json_dict = json.loads(json_data) for movie_data in json_dict: movie = Movie.create(**movie_data) # movie and genres created Json file - movie_data.json [ { "99popularity": 83.0, "director": "Victor Fleming", "genre": [ "Adventure", " Family", " Fantasy", " Musical" ], "imdb_score": 8.3, "name": "The Wizard of Oz" }, { "99popularity": 88.0, "director": "George Lucas", "genre": [ "Action", " Adventure", " Fantasy", " Sci-Fi" ], "imdb_score": 8.8, "name": "Star Wars" }, ] I think the json should be converted to dictionary. How can i do that. I don't know what is the problem. I am reading the json file. It should be string file?