Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate stripe payment with existing django form, and only save form on payment success
I have what I imagine is a pretty standard setup, an eCommerce application with a shopping cart, and the ability to store orders in a local database (needed to know what items to order from wholesaler and where to deliver them to). At the moment, all this functionality is working perfectly. My 'checkout' at the moment allows a customer to enter their details, and then an order is saved, with each order having several order items. What I want to do, is use this form to send some of the information to stripe, and if a token is received back indicating success, save some (but not all) fields to the local db. I am not trying to save CC data locally or anything like that, I'm well awawre of security risks and legal obligations like PCI compliance. I simply want to have one form that customers can use to input their data, and click pay (like most eCommerce sites have), rather than having one form to enter data, and another form to pay with. The django-stripe documentation is sorely lacking, and the Stripe API documentation seems only have examples for ruby frameworks and javascript, nothing for django. Is what I … -
Django DetailView vs CreateView.get()?
I am trying to wrap my head around a CBV thing. CreateView has a get() method that, as far as I can tell, is supposed to return info about the model just created. Is that better served by using a DetailView? -
update() not working for filefields in django
I tried to upload a file using filefield in the database and it worked correctly and uploaded the correct file creating the record for the first time. like this new_criteria1 = criteria1.save(commit=False) new_criteria1.Criteria1_active_checker = Criteria1_active_get #foreign key assigning new_criteria1.save() Later to update the uploaded file(along with other file fields from the template) I used something like this m.Criteria1.objects.filter(Criteria1_active_checker=Criteria1_active_get).update(**criteria1.cleaned_data) Here is my model class Criteria1(models.Model): Criteria1_active_checker = models.ForeignKey(Criteria1_active_checker, on_delete=models.CASCADE) semester = models.IntegerField() trimester = models.IntegerField() annual = models.IntegerField() feedback_analysis = models.FileField(upload_to='documents/') my forms class Criteria1Form(ModelForm): class Meta: model = m.Criteria1 exclude = ['Criteria1_active_checker'] But the filefield in the database only picks the name of the updated file rather than uploading the new file This error occurs only when trying to update the uploaded file but works fine when uploading the file for the first time. Need a solution to work around this error and update the new file Thanks in advance -
How to override attrs of ImageField (sorl-thumbnail)
I am using sorl-thumbnail in Django. I tried to override attrs of the forms.ImageField because I couldn't find a widget version of sorl.thumbnail.ImageField. It worked, but the thumbnail field stays empty. sorl.thubnail.ImageField solves that problem, but it doesn't support the attrs parameter. My question: How can I change attrs of sorl.thumbnail.ImageField? I think Model: thumbnail = ImageField(upload_to=upload_folder, blank=True) ModelForm: thumbnail = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-input-file', 'id': 'thumbnail-upload-button'}), label='Thumbnail', label_suffix='', required=False) -
Populate data from file and table from foreginkey
I have that models.py and i populated class Words from populate.py . I dont know how populate User_answer model from existing table Words and current login user and where to put add_data_words() to work on the first start . Sorry models.py class Words(models.Model): word = models.CharField(max_length=30,default = '') def __str__(self): return self.word class Meta: ordering = ('word',) class User_answer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.DO_NOTHING,null=True, blank=True, db_column = 'username' ) words = models.ForeignKey(Words,on_delete = models.DO_NOTHING,null=True, blank=True , db_column = 'word') answer = models.BooleanField(default = False) def __str__(self): return ('USER:-----{} WORD----- {}'.format(self.user ,self.words)) class Meta: ordering = ('user',) populate.py def open_from_file(): path = r'stemplates\words.txt' with open (path,'r') as file: file = [i.replace('\n','') for i in file.readlines()] return(file) @login_required def add_data_words(request): [Words.objects.get_or_create(word = str(i)) for i in open_from_file()] -
Django: how to annotate inside prefetch_related
I'm still working on optimization Django queries and struggling with annotation inside prefetch_related function. Models: class Car(models.Model): title = models.CharField(max_length=255) class RepeatServiceType(models.Model): title = models.CharField(max_length=255) cars = models.ManyToManyField(Car) class RepeatService(models.Model): service_type = models.ForeignKey(RepeatServiceType) car = models.ForeignKey(Car) mileage = models.BigIntegerField(default=0) View: cars = Car.objects.all().prefetch_related('repeatservicetype_set') for car in cars: services_types = car.repeatservicetype_set.all()\ .annotate(service_mileage=Max('repeatservice__mileage', filter=Q(repeatservice__car=car))) #this hit DB query for each car iteration! print(services_types.service_mileage) I've tried to prefetch something like that, but no luck: prefetch_related(Prefetch('repeatservicetypes', queryset=Subquery(RepeatServiceType.objects.annotate(service_mileage=Max('repeatservice__mileage', filter=Q(repeatservice__car__pk=OuterRef('pk'))))))) How to annotate inside prefetch_related function? Django 2.0, can be upgraded to 2.1 if needed. Thanks! -
Force django to reopen database connection if lost
In my Python-Django web application, sometimes the database it will disconnect (problems related to my test environment, not so much stable...) and my web-app give me this error: File "/usr/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 222, in create_cursor, django.db.utils.InterfaceError: connection already closed, cursor = self.connection.cursor() Now, how i can tell django to retry to open the connection and continue? it seems that django remains stuck at this point... Thanks. -
Django Model and blog author permisson problem
I am trying to build a Django blog and the problem is, when a new user registered, it does not appear in add blog section until it is add in the blog as blog author. Here is my model: from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) profile_picture = models.FileField() detail = models.TextField() def __str__(self): return self.name.username class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() image = models.FileField() posted_on = models.DateTimeField(auto_now=False, auto_now_add=True) updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title I am showing my admin here: and this is my article posting form: I need when a user registered and logged in the register only appear in name section (3rd Screenshot) Even the problem is, in name section, it asks me to register a user as blog author name, but i dont need this. I need all the registered user should go in article name section and only they can post if they logged in -
Appending dictionaries when in a for loop
Sorry if this has been asked, I've searched a ton and not finding what I'm looking for. Lots of ways to combine dictionaries, but haven't found anything for combining in a loop that applies. I have a function (masternodes()) that will return a filtered queryset. With each object returned from that queryset, I loop through and query another function (masternodeDetail()) to get some details about that object. The function (masternodeDetail()) returns a dictionary. I'd like to combine the dictionaries returned in to a single dictionary so I can pass that to my template. Here's my code I've been working with: def masternodes(request): user = request.user mn = {} queryset = Masternode.objects.filter(created_by=user) for n in queryset: mn = masternodeDetail(n.wallet_address, n.coin_symbol) print(mn) args = {'masternodes': queryset, 'masternodetail': mn} return render(request, 'monitor.html', args) def masternodeDetail(wallet, ticker): monitorinfo = MonitorInfo.objects.get(coin_symbol=ticker) coin_symbol = monitorinfo.coin_symbol daemon = monitorinfo.daemon rpc_user = monitorinfo.rpc_user rpc_password = monitorinfo.rpc_password rpc_port = monitorinfo.rpc_port coin_name = monitorinfo.coin_name notes = monitorinfo.notes masternode_reward = monitorinfo.masternode_reward coingecko_id = monitorinfo.coingecko_id json_output = monitorinfo.json_output headers = {'content-type': 'text/plain'} payload = {"method": "masternodelist", "params": ['full', wallet], "jsonrpc": "1.0", "id": "MN Monitoring v0.1"} response = requests.post("http://" + daemon + ":" + rpc_port, json=payload, headers=headers, auth=(rpc_user,rpc_password)).json() res = response["result"] if json_output … -
Django Template Language Not Rendering
I am brand new to Django and following along with the tutorial. I'm hoping this is just an obvious mistake, but I am unable to get my web browser to render anything written in the Django template language and I can't figure out why. Here is my directory structure for some context: https://imgur.com/dGNIiDa project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('budget/', include('budget.urls')), path('admin/', admin.site.urls) ] budget/urls.py: from django.urls import path from . import views urlpatterns = [ path('<int:account_id>/', views.get_account, name='detail'), ] budget/views.py: from django.shortcuts import render from django.http import HttpResponse from budget.models import Account, Transaction def get_account(request, account_id): accts = Account.objects.filter(pk=account_id) context = {"test": accts} return render(request, 'budget/detail.html', context) budget/templates/budget/detail.html: <p>This is a {{ context.test }}</p> When I visit localhost:8000/budget/1 in my browser this is all that is rendered: https://imgur.com/j2Vh0yb Clearly Django is finding the template file and sending it to the browser, but anything that is written inside of {} does not get recognized or rendered at all. I've followed along exactly with the tutorial and I have no idea why it's not working. Any ideas? Thank you! -
Django API test: expected status code 200, instead recive 301
I'm trying to create tests for my API views but I'm receiving status code 301 which mean redirection instead status 200 and 201. In first test help adding follow=True, but If I'm right "follow" just force my url response so this is pointless. This is my code: test_api.py from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile from rest_framework.test import APITestCase, APIClient from ..models import Category, Product, Comment class CreateCommentAPI(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(username='test', password='test123') self.user.save() @classmethod def setUpTestData(cls): Category.objects.create(name='PC', slug='pc') Product.objects.create( category=Category.objects.get(id=1), name='Laptop', slug='laptop', description='here is description', photo=SimpleUploadedFile("file.jpeg", b"file_content", content_type="image/jpeg"), price=1999, available='available' ) def test_logged_in_access_to_view(self): product = Product.objects.get(id=1) login = self.client.login(username='test', password='test123') response = self.client.get(f'/api/add_comments/{product.id}') self.assertTrue(login) self.assertEqual(response.status_code, 200, f'expected Response code 200, instead get {response.status_code}') def test_post_logged_in(self): product = Product.objects.get(id=1) self.client.login(username='test', password='test123') comment = { 'nick': self.user.username, 'rate': '1/5', 'comment': 'here is comment', } response = self.client.post(f'/api/add_comments/{product.id}', comment) self.assertEqual(response.status_code, 201, f'expected status code 201, instead get{response.status_code}') views.py class CreateComment(APIView): def get_object(self, id): try: return Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 def get(self,request, id): product = self.get_object(id) serializer = ProductSerializer(product) return Response(serializer.data) def post(self, request,id): serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save(nick=request.user, product=self.get_object(id)) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Two print buttons with different css styles
I am developing an app in Django. I have an HTML page in which I need to print the receipt. There are 2 print buttons say print_btn and print_btn_new (for using 2 different styles). I have defined 2 stylesheets say, print.css and print_new.css. In the head section <link rel="stylesheet" href="{% static 'css/print.css' %}" id="printCss" media="print"> It works fine. But when the print_btn_new is clicked, the print comes like no CSS is applied to it. For the print_btn_new <button id="print_btn_new" onclick="printNewOnClicked();" name="button">Print New</button> printNewOnClicked() function : function printNewOnClicked(){ document.getElementById('printCss').href = '{% static 'css/print_new.css' %}'; alert(document.getElementById('printCss').href); window.print(); } The alert displays the valid URL to print_new.css. When I copy paste the URL form alert box to the address bar, it shows the correct file. -
Django - FilterSet - foreignkey loop
I have a Django FilterSet that shows per investor the investments. The problem is that in my template (html browser) the investors that have 0 investments are not displayed. I'm pretty sure the problem lies in how I filter through the investment.set_all Who can help me out :)?? many thanks to all ! models.py: class Fund(models.Model): feeder = models.CharField(max_length=100) def __str__ (self): return self.feeder class Investor(models.Model): first_name = models.CharField(max_length = 100) last_name = models.CharField(max_length = 100) def __str__ (self): return '%s %s' % (self.first_name, self.last_name) class Investment(models.Model): feeder = models.ForeignKey(Fund, on_delete=models.CASCADE) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) commitment = models.DecimalField(max_digits=20, decimal_places=2, default="1") def __str__ (self): return '%s %s' % (self.feeder, self.investor) html: <tbody> {% for investor in investorfilter.qs %} {% for investment in investor.investment_set.all %} <tr> <td> {{investor.first_name}} </td> <td> {{investor.last_name}} </td> <td> {{investment.feeder}} </td> <td> {{investment.commitment}} </td> </tr> {% empty %} <tr> <td colspan="5"> No such investor exists</td> </tr> {% endfor %} {% endfor %} <p></p> </tbody> -
Django TIME_ZONE value is set, but templates still rendering in UTC
I have some datetime fields on my Django app that are auto filled with auto_now_add=True created_at = models.DateTimeField(auto_now_add=True, verbose_name='created') In my settings.py I have the following two lines (as I want my dates to be displayed in CST): USE_TZ = True TIME_ZONE = 'America/Chicago' When I go into the shell and view the datetime object, I can see it is being stored in UTC, which I believe is the desired behavior: datetime.datetime(2019, 3, 10, 18, 3, 15, 906770, tzinfo=<UTC>) However, when I render the date in my template using {{order.created_at}}, it is rendering in UTC. My understanding is the TIME_ZONE setting should render all dates in CST based on my settings. March 10, 2019, 6:03 p.m. Am I missing an extra setting? -
How to use slice with if statement in Django?
The following code is causing error {% if product_category == 'Hotel' %} {% for p in post | slice:":12" %} .... .... {%endfor%} {% endif %} This code shows an error like: 'for' statements should use the format 'for x in y': for p in post | slice:":12" I want to limit the number of posts only for hotels, not for all the posts. How can I do this? -
Call a Django View function on button click in Html form, using form action
I'm trying to make a basic function in Django, but I don't know how to call the function in views.py from the template when a button is clicked. I did find a similar question here. But actionUrl confused me a lot, and I am not sure how to implement it. Button code in template: <form action ="{% check1 %}" method = "POST"> {% csrf_token %} <button type='submit'> True</button> </form> Currently I have commented out the actual logic of the function and am just trying to get it to respond so it's here: def check1(request): return HttpResponse("why u no work") urls.py: urlpatterns = [ path('', Posts, name='Posts'), path('', index, name = 'index'), path('', check1, name = 'check1'), #path(actionUrl, views.check1), ] -
Django get Ajax Request
I'm trying to get some data from my database with Ajax call. I think something goes wrong when with jsonresponse. View.py def requestAjax(request): customerList = Customer.objects.all().values("id", "customer_number","postcode","NRP","ip_address", "latitude","longitude","color","status") data = { 'customer': customerList,} return JsonResponse(data) enter code here function ajaxCall() { $.ajax({ url: '/maps/my_ajax_request/', datatype: 'json', type: 'GET', success: function (data) { alert("Data OK"); }, failure: function(data) { alert("Got an error dude"); } }); } The url.py works fine. If I use this one it works!!! def requestAjax(request): data = { 'is_valid': False,} return JsonResponse(data) please let me know if there is a better way of doing this!!! -
I can not see the saved image in the database name 'user' is not defined
I'm using Class Gallery, to slavar an image, or more than one image, as a gallery, but I can not see the images saved in the perfil.html I'm desperate, I do not know where I went wrong, I'm new to python erro in shell name 'user' is not defined thanks for the help views.py def gallery(request): gallery = Gallery.objects.all() form = GalleryForm() data = {'gallery': gallery, 'form': form} return render(request, 'gallery.html', data) def gallery_novo(request): if request.method == 'POST': form = GalleryForm(request.POST, request.FILES) if form.is_valid(): my_novo_gallery = form.save(commit=False) #save no commit my_novo_gallery.user=request.user #set user my_novo_gallery.save() #save to db return redirect('sistema_perfil') else: form = GalleryForm return render(request, 'gallery.html', {'form': form}) def perfil(request): usuario = Usuario.objects.all() form = UsuarioForm() data = {'usuario': usuario, 'form': form} gallery = Gallery.objects.all() form2 = GalleryForm() data2 = {'gallery': gallery, 'form2': form2} return render(request, 'perfil.html', data, data2) models.py class Gallery(models.Model): gallery = StdImageField( blank=False, variations={ 'large': (600, 400), 'thumbnail': (100, 100, True), 'medium': (300, 200), }) titulo = models.CharField(max_length=50, blank=False) usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) forms.py class GalleryForm(forms.ModelForm): gallery = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': 'True'})) titulo = forms.CharField() class Meta: model = Gallery fields = ( 'gallery', 'titulo') def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) return super(GalleryForm, self).__init__(*args, … -
A page protected by Card pin and Card Serials in django
I am really confused on how to go about this. I am on a school project, where i have a page for students bio registration but the page should only be accessed with the use of card details(card pin and card serials). Please any insight on how to go about this in the right way, would really help me. Thanks. -
Why Django-Admin Panel did not show css and javascript?
I have django admin panel working on a vps ( Windows Server 2012 ) , Why it is not showing any css styles or boostrap ? it is showing just html and nothing else . -
Error in generating checksumhash(Paytm Gateway) on Django
I am working on django rest framework project,I am trying to integrate PayTm gateway but program is encountering error in generating checksumhash. Below are my code Snippets: models.py from django.db import models class TrxnDetail(models.Model): MID = models.CharField(max_length=20) ORDER_ID = models.CharField(max_length=50) CUST_ID = models.CharField(max_length=64) TXN_AMOUNT = models.CharField(max_length=10) CHANNEL_ID = models.CharField(max_length=3) WEBSITE = models.CharField(max_length=30) INDUSTRY_TYPE_ID = models.CharField(max_length=20) MOBILE_NO = models.CharField(max_length=15) EMAIL = models.CharField(max_length=50) def __str__(self): return self.ORDER_ID views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from gateway.models import TrxnDetail from gateway.serializers import TrxnSerializer from gateway.Checksum import generate_checksum from django.conf import settings @api_view(['GET', 'POST']) def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = TrxnDetail.objects.all() serializer = TrxnSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TrxnSerializer(data=request.data) if serializer.is_valid(): serializer.save() sdata=serializer.data mid,order_id,cust_id, txn_amount,channel_id, website,industry_type_id, mobile_no,email=sdata.get('MID'),sdata.get('ORDER_ID'), sdata.get('CUST_ID'),sdata.get('TXN_AMOUNT'), sdata.get('CHANNEL_ID'),sdata.get('WEBSITE'), sdata.get('INDUSTRY_TYPE_ID'),sdata.get('MOBILE_NO'), sdata.get('EMAIL'), param_dict = dict() param_dict['MID']=mid param_dict['ORDER_ID']=order_id param_dict['CUST_ID']=cust_id param_dict['TXN_AMOUNT']=txn_amount param_dict['CHANNEL_ID']=channel_id param_dict['WEBSITE']=website param_dict['INDUSTRY_TYPE_ID']=industry_type_id param_dict['MOBILE_NO']=mobile_no param_dict['EMAIL']=email print(generate_checksum(param_dict,settings.PAYTM_MERCHANT_KEY)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Im using ModelSerializer and CheckSum.py I am getting following error:Error Image -
Multiple filter parameters in API endpoint - DRF
I am using Django rest framework for my REST API. I have endpoint where are some parameters for filtering, something like this: # in my view from_date = self.request.query_params.get('from', None) to_date = self.request.query_params.get('to', None) category = self.request.query_params.get('category', None) color = self.request.query_params.get('color', None) Then I have if/else code where I am selecting the data. For the first time there was only a two parameters so it was ok, but then I added more parameters for filtering and now I think this code is not looking very good and I think there is a need for some optimization. Moreover combination of different parameters is not working now. Actual code (in my view): if from_date is not None and to_date is not None: something = Something.objects.filter(send_date__range=(from_date, to_date)) elif category: something = Something.objects.filter(values__something__category__name__iexact=category) elif color: something = Something.objects.filter(values__something__color__name__iexact=color) else: something = Something.objects.all() Is there any option, built-in to the DRF or some type of combined filtering in Django how can I combine parameters into one big query taking into account that values can be None? Something like (but if one of the values is None query will work without this value): Something.objects.filter(send_date__range=(from_date, to_date)) .filter(values__something__category__name__iexact=category) .filter(values__something__color__name__iexact=color) -
Django Shell ForeignKey
I'm struggling to do a reverse search via the shell for a foreign key models.py: class Investor(models.Model): first_name = models.CharField(max_length = 100) last_name = models.CharField(max_length = 100) def __str__ (self): return '%s %s' % (self.first_name, self.last_name) class Investment(models.Model): investor = models.ForeignKey(Investor, on_delete=models.CASCADE) feeder = models.ForeignKey(Fund, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=20, decimal_places=2, default="1") def __str__ (self): return self.investor class Fund(models.Model): feeder = models.CharField(max_length=100) def __str__ (self): return self.feeder If I enter the shell: a = Investment.objects.get(pk=1) a.investor.first_name -> this works On the other hand : b = Investor.objects.get(pk=1) b.investment doesn't work... b.investor doesn't work b.investment.feeder neither.. Always got the error 'Investor has not attributed '....' -> How can i search through the reverse relationships? Thanks !! -
Is it possible to change posts view as category wise in django
I am trying to make post with category featured view as carousel and rest of them in different view. Is it possible to do that. something like on this website So far i have made post to render as category on home page but here i want to make carousel too with posts and i don't have any idea how to do that. this is my code views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin #from django.contrib.auth.models import User # Create your views here.posts = [ from django.shortcuts import redirect, render,get_object_or_404 #class based view from django.views.generic import ListView, DetailView from .models import Post, Category class PostView(ListView): template_name = 'posts/home.html' model = Category context_object_name = 'all_categs' def get_queryset(self): if self.request.user.is_authenticated: return Category.objects.all() else: return Category.objects.all()[:6] def get_context_data(self): if not self.request.user.is_authenticated: context = super(PostView, self).get_context_data() context['latest_posts'] = Post.objects.order_by('-date_posted')[0:6] return context else: context = super(PostView, self).get_context_data() context['latest_posts'] = Post.objects.order_by('-date_posted') return context # def get_success_url(self): # return reverse('home') #add your path class PostDetailView(LoginRequiredMixin,DetailView): model = Post template_name = 'posts/post_detail.html' home.html i did not added carousel here but i want to add that on the top of the home page. {% extends "posts/base.html" %} {% block content %} <div class="contianer"> <div class="latest_post-title row"> <div class="col-lg-6"> <h3>Latest</h3> <p>Lorem … -
Django Moderation System
So I am creating a Django application where users can register and also create posts. I want to be able to moderate this and have it so when a user creates a post it has to be approved by an Admin before it can go live. I tried using https://github.com/dominno/django-moderation but it just wasn't working for me. Any suggestions?