Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
make a function return random object from a list when ever it's called
How can I make a function return a random object from a list when ever it's called. Look at the code I already have import random def random_list(): random_obj = random.choice(['she can work', 'we want to go home', 'she said she is not gonna come', 'we need to go']) return random_obj I need when ever I call the function random_list() it will return a random object from random_obj list. for example print('what are you saying, \n I said {}'.format(random_list())) and the output will be a random object from 'random_obj'. I primarily want it to be in a function. -
expected str, bytes or os.PathLike object, not pisaContext
I'm trying to send PDF via email: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return pdf return None in my views: pdf = render_to_pdf('expenses/pdf_report.html', data) mail.attach_file(pdf) mail.send() I get this error: expected str, bytes or os.PathLike object, not pisaContext How can I get str or bytes instead of pisaContext? -
Django Leaflet disable zoom control
I use Django 2.0 to draw maps and add Control Zoom Bar Everything work fine, but now I have 2 zoom control. According to the leaflet tutorial ( I use django-leaflet) I should disable default leaflet zoom control using zoomControl: false but somehow I cant find it where to configure it using Django-leaflet I Tried var map = new L.Map.djangoMap('map', { zoomControl:false }); but still it returns in an error, In Settings for LEAFLET_CONFIG there's only MAX_ZOOM and MIN_ZOOM. Any Idea how to do it? Thanks in advance. -
Django - get all related models related to each object
Basically, I do have few models that refer to each other. I hope I relations between those alright, but I'm not 100% sure. models.py class Table(models.Model): number = models.IntegerField(unique = True) isFree = models.BooleanField(default = True) class MenuItem(models.Model): name = models.CharField(max_length = 200) price = models.DecimalField(max_digits=5, decimal_places=2) quantityInStock = models.PositiveSmallIntegerField(default=10) class Order(models.Model): tableFK = models.ForeignKey(Table, on_delete=models.CASCADE) opened_at = models.DateTimeField('date_created', default = timezone.now) closed_at = models.DateTimeField('date_closed', blank = True, null = True) paid = models.BooleanField(default = False) class Meta: ordering = ('-opened_at',) class OrderDetails(models.Model): STATUS_CHOICES = ( ('CHOICE1', 'choice1'), ('CHOICE2', 'choice2'), ('CHOICE3', 'choice3'), ('CHOICE4', 'choice4'), ('CHOICE5', 'choice5') ) orderFK = models.ForeignKey(Order, on_delete = models.CASCADE) menuitemFK = models.ForeignKey(MenuItem, on_delete = models.CASCADE) quantity = models.PositiveSmallIntegerField(default = 1) status = models.CharField(max_length=5, choices= STATUS_CHOICES, default='choice1') views.py def index(request): orders = Order.objects.select_related("tableFK").filter(paid=False) template = loader.get_template('autowaiter/index.html') context = { 'orders':orders } return HttpResponse(template.render(context)) What I'm achieving now, is that I do have Orders objects. But in index.html I would like to display something like: Table "earliest" order to table ALL orderDetails elements grouped to each orderFK Could you please point me out example and theory which I'm lacking to proceed? -
How to serialize a foreign key from the same model
I have this model: class Player(models.Model): name = models.CharField(max_length=100) partner = models.ForeignKey('self', blank=True, null=True) And in my serializer I have this: class PlayerSerializer(serializers.ModelSerializer): partner = PlayerSerializer() class Meta: model = Player fields = ('id', 'name', 'partner') But of course this returns an error saying PlayerSerializeris not defined. How do I serialize the foreign key. Im using Django Rest API, django 1.10, and python 3.6.3 -
How to get image form another model in djago
I want to get image form Image model for my Product model and show it cart template This is my Code: ecommerce/models.py class Product(models.Model): name = models.CharField(max_length=200) content = models.TextField() excerpt = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) status = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) quantity = models.PositiveIntegerField() author = models.PositiveIntegerField() featured_image = models.CharField(max_length=300) available = models.BooleanField(default=True) def __str__(self): return self.name class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField() cart/views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, pk=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart_detail.html', {'cart': cart}) cart/templates/cart.html <tbody> {% for item in cart %} {% with product=item.product %} <tr> <td> {% for product in products %} <img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/> {% endfor %} </td> <td>{{ product.name }}</td> . . . </tr> {% endwith %} {% endfor %} </tbody> i have read this link but it is no use to me, please help me, I am newby to this Thank you -
How can i call views from Html Templates in Django?
As i'm trying to upload file and send with some functionality i'm getting error while calling view function from views.py to html templates i don't know what i did wrongly Can anyone help me..Thanks in Advance :) here is my views.py: my application name is secondone and my view function name is SavedProfile. from django.shortcuts import render from secondone.forms import ProfileForm from secondone.models import Profile def SaveProfile(request): saved = False if request.method == "POST": #Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = ProfileForm() return render(request, 'last.html', locals()) Here is my Template: <html> <body> <form name="form" enctype="multipart/form-data" action = "{% url 'views.SaveProfile' %}" method = "POST" >{% csrf_token %} <div style="max-width: 470px"> <center> <input type="text" style="margin-left:20%;" placeholder="Name" name="name"> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </body> </html> Here is my url.py: from django.contrib import admin from myapp import views from secondone import views from django.views.generic import TemplateView from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from … -
deploy django application with pipenv on apache
I have created a python web application in Django 2.0 using pipenv virtualenv Now, I have to host it on apache server. I have installed libapache2-mod-wsgi-py3 and python-setuptools in the server. The structure of my application is like myapp_dir |- myapp |- settings |- __init__.py |- production.py |- __init__.py |- urls.py |- wsgi.py |- otherapp |- templates |- static_my_project |- manage.py |- Pipfile |- Pipfile.lock the path of the application to put on /home/user/app.application.com/ I have moved all files to the directory and installed all dependencies from Pipfile by running in the directory pipenv install This has created a virtualenv and installed all required modules and the path of pipenv --venv gives # pipenv --venv /home/user/.local/share/virtualenvs/app.application.com-IuTkL8w_ My VirtualHost configuration looks like ServerName app.application.com ServerAlias app.application.com ErrorLog /home/user/error.log CustomLog /home/user/custom.log combined Alias /static /home/user/app.application.com/static_my_project <Directory /home/user/app.application.com/static_my_project> Require all granted </Directory> <Directory /home/user/app.application.com/pricearbitrase> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/app.application.com/myapp/wsgi.py VirtualInclude contains <IfModule mod_wsgi> WSGIPythonHome /home/user/.local/share/virtualenvs/app.application.com-IuTkL8w_/bin </IfModule> But on accessing http://app.application.com it gives Internal server error and the log file generated contains [wsgi:error] [pid 60730] mod_wsgi (pid=60730): Target WSGI script '/home/amzitrage/app.amzitrage.com/pricearbitrase/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 60730] mod_wsgi (pid=60730): Exception occurred processing WSGI script '/home/amzitrage/app.amzitrage.com/pricearbitrase/wsgi.py'. [wsgi:error] … -
Django ModelForm that uses a combination of two model fields in one charfield
Is it possible to combine two model fields in a ModelForm to be entered in one charfield? My model: class Sample(models.Model): request_number = models.PositiveIntegerField() year = models.PositiveIntegerField() part = models.CharField(max_length=6, null=True, blank=True) class Meta: db_table = "sample" unique_together = (('request_number', 'year', 'part'),) def __str__(self): sample_id = "%s/%s" %(str(self.request_number), str(self.year)[2:]) return(sample_id) A sample is therefore returned from the model as / or, 123/18 However if I make a ModelForm, I dont want two fields to enter request_number and then year. Instead I would like one charfield for the user to enter 123/18, my form to parse the request_number and year, and for the ModelForm to be validated. I have tried this as a normal django form, but it does not validate in my view. Form: class SingleSampleForm(forms.Form): sample_id = forms.CharField( required=True, label='Sample ID:') class Meta: fields = ['sample_id'] def __init__(self, *args, **kwargs): super(SingleSampleForm, self).__init__() self.helper = FormHelper() self.helper.layout = Layout( Field('sample_id', css_class="search-form-label", ), Submit('submit', 'Search sample', css_class='upload-btn') ) self.helper.form_method = 'POST' def clean(self): sample_id = self.cleaned_data['sample_id'] if sample_id: return sample_id raise ValidationError('This field is required') views.py: class SampleView(View): sample_form = SingleSampleForm def get(self, request, *args, **kwargs): sample_form = self.sample_form() self.context = {'sample_form': sample_form,} return render(request, 'results/single_sample_search.html', self.context) def post(self, request, *args, … -
SAML integration with Django
I am trying to integrate a web application with SAML. I have searched on internet for examples but didn't find many. Where can I find a good example on this subject and how can I make a test project? Is there a free Identity Service Provider I can use? -
Django filter form variable string [duplicate]
This question already has an answer here: In Django, how does one filter a QuerySet with dynamic field lookups? 4 answers I want to filter condition from variable string My problem: _filter = "Q(title__startswith='C')" _videos = Post.objects.filter(_filter) print('---------------------------') print(_videos) Error code: ValueError: too many values to unpack (expected 2) Anyone have a solution for this? Thanks! -
django Get Distinct rows which are inserted last
I have a table which same as bellow id|user|datetime|action this table records actions for each user and its time I want to get latest actions which are done by all users. I have tested these methods Entry.objects.order_by('datetime','user').distinct('user') and Entry.objects.latest('datetime').distinct('user') but both of them returns erros. for example the first try says : SELECT DISTINCT ON expressions must match initial ORDER BY expressions How can I filter rows by latest actions which are done by all users? -
Django - from function view to generic class view
I had this function based view and i'm trying to transform it in a generic class view as such: Original: def view_events (request): template ='appform/view_events.html' items = Event.objects.filter(owner=request.user) pages = pagination(request,items, num = 10) print(pages) context = { 'items': pages[0], 'page_range': pages[1], } return render(request, template, context) Generic Class view: class ViewEvents(generic.ListView): template_name = 'app/view_events.html' model = Event context_object_name = 'events' pagination = ??? def get_queryset(self): return Event.objects.filter(owner = self.request.user) In the original function-based view i had a pagination imported from another model which returned items and page range and also had a pagination template, How can i translate that in generic class language? More specific: How do i pass the objects.filter(owner = self.request.user) to the get_context_data: def get_context_data(self, **kwargs): context = super(ViewEvents, self).get_context_data(**kwargs) ##pass it here somewhere so i can include page range in context context['cart_product_form'] = cart_product_form return context -
The Django/Django-Rest-Framework project in the linux server, how can we run it instead of source code?
The Django/Django-Rest-Framework project in the linux server, can we run it instead of source code? I have a Django/Django-Rest-Framework project, in the remote server I can use the uwsgi run source code. But our boss want me do not put source code to the remote server. I know, if we have Java project, we can upload the javac files, after the compiling. How about this type encryption in Python/Django? -
Programming changes not appearing in Django application upon saving in text editor?
This is an extremely peculiar case. I have been working on a Django application for a few weeks now and when I turned on my laptop this morning and begun to work I noticed that none of my changes were saving. I checked, double checked and triple checked I was working on the right files and I was. I was using Atom so I thought it might be a text editor issue so I installed PyCharm for Mac. I am still encountering the same error. I have cleared my cookies a number of times, reinstalled atom, restarted the Django server yet still no code changes are appearing. Anybody any ideas as to what might be causing this? -
Django Admin with mongodb database
Currently I'm working on an admin panel for my application which is written in React and Node.js. I already have a MongoDB database so I want to connect the Django app to this database. I read about Djongo connector and I decided to give it a try. There is a connection to the database, which means I can perform simple CRUD operations. The problem is with the poplation of referenced fields. In my database I have a collection of boxes. Each box has an owner field which contains an ID to a Supplier object. Currently in my django application, when I review the boxes collection, I only see the ID of the Supplier. I want to be able to retrieve information from that Supplier object but I don't know how. I tried embed the Supplier model into my Box model but it gives me this error: https://i.gyazo.com/362857feb2fc75065852a53e1dc4f774.png When I try to use ForeignKey, I'm not getting any errors, but the field is just and id, like this: https://i.gyazo.com/989ccdb3799935b4f308314a9fb6c27c.png Here is my models.py file(I omitted irrelevant parts): from djongo import models from django import forms userStatusEnum = ( ('pending', 'pending'), ('active', 'active'), ('removed', 'removed'), ) userTypeEnum = ( ('buyer', 'buyer'), ('supplier', … -
How to change card amount depending on search result on bootstrap 4?
I recently started a project with Bootstrap 4 and I stuck on something. I'm trying to make a simple search and result page using Bootstrap and decided to use cards for my search results. However, I'm not sure how can I put dynamic number of cards depends on amount of the search result. Should I use a different kind of approach instead of using cards? Or is there a way to do it with cards? By the way I'm planning to use django for back-end. -
Django exclude queryset __in for *every* item in list
This is a bit different from Django filter queryset __in for *every* item in list and Django filter queryset __in for *every* item in list (2.0) Given the following models: class Product(BaseModel): ''' whatever ''' class Customer(BaseModel): blacklist = models.ManyToManyField(Product, blank=True) class Advisory(BaseModel): product_names = models.ManyToManyField(Product) Where a customer maintains a list of Products it's not interested in. How can I get a list of the advisories for a given customer? Let's say I have these in my DB: # Advisory 1 (should be included as Product 1 isn't in the customers blacklist) # product_names # Product 1 # Product 2 # Product 3 # Advisory 2 (should be excluded) # product_names # Product 2 # Product 3 # Customer 1 # blacklist # Product 2 # Product 3 # Product 4 # Product 5 If I use a queryset like this: queryset = Advisory.objects.all() blacklist = Customer.blacklist.all() queryset = queryset.exclude(product_names__in=blacklist).distinct() It will exclude both advisory 1 and advisory 2, as product 2 and 3 are present in the customer blacklist -
Django allauth register button has suddenly stopped working
I have never had any problems with it previously but when I clicked on it just then, it did not do anything. However my login works fine. I'm running a custom signup class (so I can include google recaptcha) - this has already been tried and tested to work: class AllauthSignupForm(forms.Form): captcha = ReCaptchaField() class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass I believe I may have altered the source code in django-allauth/blob/master/allauth/account/forms.py however I can't figure out what I changed. So I tried copy pasting the whole forms.py on github to my forms.py, and that returned this error: Traceback: File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/vorsso/venvor/draft1/views.py" in boxes_view 116. return render(request, 'boxes.html', context) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/base.py" in render 205. with context.bind_template(self): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py" in __enter__ 59. return next(self.gen) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/context.py" in bind_template 263. updates.update(processor(self.request)) File "/Users/zorgan/Desktop/project/app/draft1/processors.py" in everywhere 12. allauth_signup = … -
Django channels error possibly because it cannot find the routes. What am I missing?
I am following this tutorial. However in my console I get the message Connecting to ws://127.0.0.1:8000/chat/stream/ 5WebSocket connection to 'ws:<URL>/chat/stream/' failed: WebSocket is closed before the connection is established. I think this is because it cannot find the route to ws_connect as I have a breakpoint set there which does not get hit.I would appreciate it if someone could check my code and tell me what I am doing wrong.I am trying to get a simple demo app so I could further understand this. I currently have two apps - main one with the settings.py is called multichat and the other is called chat. Now here are the two files multichat/routing.py from channels import include # The channel routing defines what channels get handled by what consumers, # including optional matching on message attributes. In this example, we match # on a path prefix, and then include routing from the chat module. channel_routing = [ # Include sub-routing from an app. include("chat.routing.websocket_routing", path=r"^/chat/stream"), # Custom handler for message sending (see Room.send_message). # Can't go in the include above as it's not got a 'path' attribute to match on. include("chat.routing.custom_routing"), # A default "http.request" route is always inserted by Django at … -
django ajax feeding one form with data from another form
I´m new to Ajax but i read a few examples about how to build form submission, like buttons etc. with Ajax. But i cant find an example of two forms working together so i´d be glad if anyone could help me out =) I have one form where the user can select a start date and end date. The other form then gives the user choices of possible meeting times. Both forms are on the same page so theres no redirection, only the reload of the secound form with the data from the first one. I fail to get the data from the first form and feed it to the other form. If you could give me an example it would help a lot! -
Oauth 2.0 Framework Using DJango drf
i am learning django oauth, but I don't understand how to implement oauth in between two local applications as an consumer and provider. Could someone help me. Thank you! -
Allow individual model fields in Django to be null but prevent all of them from being null
i have a Django model class as follows: class IPGroup(BaseModel): """ Stores IP Groups """ name = models.CharField(max_length=50, unique=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) _ips = models.ManyToManyField(IP, through='connectivity_service.IPGroupToIP', null=True) _cidrs = models.ManyToManyField(CIDR, through='connectivity_service.IPGroupToCIDR', null=True) _ip_groups = models.ManyToManyField('self', through='connectivity_service.IPGroupToIPGroup', null=True, symmetrical=False) def __unicode__(self): return f'{self.name}' class Meta: app_label = 'connectivity_service' As is evident, the fields _ips,_cidrs and ip_groups can be null in the database.However, I want to prevent all 3 of them being null together when the model is saved. In other words, when the model is saved, atleast one of those 3 fields should not be null. -
Otree save static results page
I am using OTree to run a number of different app/games/experiments in a session. Currently the results of each app is displayed within the app as the last page. But I wish to hold of displaying any results until after all apps have been run, in a final results app. Rather than having to create a heap of new participant vars to store the all results and write new code to display them, I was hoping that there was some way that within each app, I could save the results_page.html as a static html page (with all variables displayed at their current values not {{variable}} ) that I could load up later outside of the app at the end in a final results app. I've learnt a fair bit about coding in Otree in the last few months and can understand basic Python, but Django still baffles me (I'm old school). I've found code to read in a html page and save it as a string, but seems not be able to give the value of variables just {{variable}}. I think I saw something about Django module Bakery? I was hoping it might be something easy (who doesn't). Can anyone … -
Django: 'WSGIRequest' object has no attribute 'objects'
In my Django project, I want to make a simple booking system, that works by clicking a button on the main page that redirects you to view named book_cd. In URL we have cd_name (id) that is converted into var named name in mine view. Problem is that I can't use filter() function to find that one record I want to update because something like this happens: 'WSGIRequest' object has no attribute 'objects' in line with: results = CD.objects.filter(CD.info.name == name) my models: class CD(models.Model): pass class CDInfo(models.Model): cd = models.OneToOneField(CD, on_delete=models.CASCADE, primary_key=True, related_name='info') name = models.CharField(max_length=200) class CDBooking(models.Model): cd = models.OneToOneField(CD, on_delete=models.CASCADE, primary_key=True, related_name='booking') user = models.CharField(max_length=50) when_booked = models.DateTimeField(timezone.now()) my view: def book_cd(request, CD, cd_name): name = cd_name results = CD.objects.filter(CD.info.name == name) for CD in results: CD.booking.user = "test" CD.save() return redirect('index') I tried with and without request and CD in function arguments, no idea what to do. Thanks in advance!