Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django Deploy Stripe Issue - No module named 'stripe'
When I run my app locally, everything works, but when I try to deploy to Heroku, I get this error: ModuleNotFoundError: No module named 'stripe' I've read some other answers to similar issues and it seems like maybe my virtual environment is running a different version of Python than the one on Heroku, or something along those lines? My Python version is 3.6.5 I do have a runtime.txt file with the following in it, which I thought was setting the python version for my Heroku app: python-3.6.5 I read this SO thread, but I didn't really understand the part about the PYTHONPATH - Importing Stripe into Django - NameError If anyone can help steer me in the right direction or has an idea of what I could try, I'd really appreciate it! Thanks! -
How do I read what PayPalIPN contains?
I have PayPalIPN standard integration on my website working. Now what I'm trying to figure out is how to use the signal of valid_ipn_received to update a model. First, how can I read what information is sent to me from PayPal? # handlers.py @receiver(valid_ipn_received) def show_me_the_money(sender, **kwargs): """Do things here upon a valid IPN message received""" ... I have this code ready, so I assume it'd be something along the lines of: print(valid_ipn_received) but I don't know what value to tell the print function. BTW my app is pushed to heroku, and following a successful payment the heroku logs tell me nothing. Next, where does a signals.py file play into this? Do I need one? And finally, I need to pass some information to PayPal about the item that was bought, and I have been doing so through the dictionary that goes through the payment form: def payment_process(request): bid_id = request.session.get('bid_id') bid = get_object_or_404(Bid, id=bid_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'neighborhood': bid.neighborhood, 'team': bid.team, 'amount': bid.amount, 'item_name': 'Bid {}'.format(bid.id), 'invoice': str(bid.id), 'currency_code': 'USD', 'notify_url': 'https://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'https://{}{}'.format(host, reverse('payment:done')), 'cancel_return': 'https://{}{}'.format(host, reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/process.html', {'bid': bid, 'form': form }) I need the … -
Django Templating Language HTML Filter
I'm trying to pass some variables from my view to my javascript. I cannot seem to find any thing online about converting python lists and dicts to JS. <script> var list = '{{area_dict}}' console.log(list) </script> the console returned: {&#39;9&#39;: [[&#39;Walls2&#39;, &#39;20&#39;], [&#39;asd&#39;, &#39;21&#39;]], &#39;22&#39;: [[&#39;BD 1&#39;, &#39;6&#39;]]} while i just need {'9': [['Walls2', '20'], ['asd', '21']], '22': [['BD 1', '6']]} It seems to convert my python into HTML; I need it to be the same style as my original python. Are there any django filters for this? -
Allow HTML in admin fields, Django. Is this possible?
I can't seem to find the answer to this anywhere. Is it possible to allow HTML tags in the Admin site of Django 2.0? Thanks all! -
Django Block Code doesn't render
doing a site and i need some help with the block tags. It seems that django doesn't render {% block home %} {%endblock home %}. Let's suppose in my block code i have this div and if i put the div inside my base.html as per below example it doesn't appear. It appears only when i put the source code inside the base.html, so is not including my tags. What should i do? PS i have the extended code in my block e.g. {% extends "base.html" %} <div> <H1>Aici trebuie adaugat restul</H1> </div> My base.html: {% load staticfiles %} <!--DOCTYPE html --> <html> <head> <title>{% block head_title %}Advancing the Blog{% endblock head_title %}</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' > <link rel='stylesheet' href='{% static "css/base.css" %}' /> <style> {% block style %}{% endblock style %} </style> {% block head_extra %} {% endblock head_extra %} </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> {% include "messages_display.html" %} <div class='container'> <ol class='breadcrumb'> … -
ValueError: cannot assign using Mock()
I'm learning how to use Mock for testing in django (2.0.6 <= it can make the difference) but I'm stuck following a tutorial. Here my test_views.py: User = get_user_model() #I use this in other tests, I hope it don't interfere @patch('lists.views.NewListForm') class NewListViewUnitTest(unittest.TestCase): def setUp(self): self.request = HttpRequest() self.request.POST['text'] = 'new list item' self.request.user = Mock() def test_passes_POST_data_to_NewListForm(self, mockNewListForm): print('self.request', self.request.user) new_list2(self.request) mockNewListForm.assert_called_once_with(data=self.request.POST) [...] And here my error on testing: self.request <Mock name='mock()' id='80288792'> #print result E ====================================================================== ERROR: test_passes_POST_data_to_NewListForm (lists.tests.test_views.NewListViewU nitTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "d:\python\Lib\unittest\mock.py", line 1179, in patched return func(*args, **keywargs) File "D:\progetti\superlists\lists\tests\test_views.py", line 149, in test_pas ses_POST_data_to_NewListForm new_list2(self.request) File "D:\progetti\superlists\lists\views.py", line 42, in new_list2 list_.owner = request.user File "C:\Users\fabio\.virtualenvs\superlist\lib\site-packages\django\db\models \fields\related_descriptors.py", line 197, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "<Mock name='mock()' id='80288792'>": "List.owner" must be a "User" instance. So, it look like it don't recognize the self.request.user = Mock() like a User instance. Note on the test_view: 1) the print command 2) the User = get_user_model() variable. get_user_model() comes from django.contrib.auth. I think it don't interfere. I add some more code for completeness, ask for more if you need. My views.py: def new_list2(request): form = NewListForm(data=request.POST) if form.is_valid(): list_ = List() if request.user.is_authenticated: list_.owner … -
How to access session variable in child template in Django?
I'm trying to change some feature on Askbot to make it show different versions of the user-card depending on the session. I learned that I can pass request.session just like any other data from view to template. However, the template that I want to change is buried inside of many parent templates that are eventually rendered by a view. In this case, is it best to use context_processors? If so, how does it work in the context of session and child templates? -
How do I delete users (for custom user model)?
I want to delete all users, including superusers from my custom user model. On Django's default model, I know you can call Users.objects.all().delete() but when I try to call something similar on my own model, it says there is no delete() function. Is there something I can follow to write this function or is there an easier way to delete all users from my custom model? -
How to override GeoDjango GeoJSON Seriliazer to include model properties
This is an offshoot of the generic how can I include properties in a JSON serialization, which is answered here: https://stackoverflow.com/a/38253327/4140357 from django.core.serializers.base import Serializer as BaseSerializer from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.json import Serializer as JsonSerializer class ExtBaseSerializer(BaseSerializer): def serialize_property(self, obj): model = type(obj) for field in self.selected_fields: if hasattr(model, field) and type(getattr(model, field)) == property: self.handle_prop(obj, field) def handle_prop(self, obj, field): self._current[field] = getattr(obj, field) def end_object(self, obj): self.serialize_property(obj) super(ExtBaseSerializer, self).end_object(obj) class ExtPythonSerializer(ExtBaseSerializer, PythonSerializer): pass class ExtJsonSerializer(ExtPythonSerializer, JsonSerializer): pass How to use it: ExtJsonSerializer().serialize( MyModel.objects.all(), fields=['field_name_1', 'property_1' ...] ) And it works great for JSON. How can you do the same thing for GEODJango's GEJSON serializer? -
Implementing social login with django backend and ionic front end
I'm currently building an app with Ionic front end and Django back end, and the two communicate through rest framework. At the moment I handle authentication between the two by using JWT, but now I also wants to add in social login to my ionic app. At this point I'm completely lost cause the documentation for social login I've read seem to only support either django or angular, but here I want my django server to be also able to keep track of the users. So where should I start for this and which auth method should I use? -
Django Rest change primarykey in URL to use custom key
i have two models Stats and Autor, how i can change primary key to use a unqiue field search by parameter(Subname in Autor model) i thinking about APIView but anyone can show me how use this? example : http://127.0.0.1:8000/autors/Subname models.py class Stats(models.Model): # Fields Word = models.CharField(name='Word',max_length=255) Word_count = models.IntegerField(name="Count") def __str__(self): return self.Word+":"+str(self.Count) class Autor(models.Model): name = models.CharField(max_length=255) sub_name = models.CharField(name='Subname', max_length=255, default='puste') # Relationship Fields words = models.ManyToManyField(Stats) serializers.py class StatsSerializer(serializers.ModelSerializer): class Meta: model=Stats fields=('Word','Count') class AutorSerializer(serializers.ModelSerializer): words=StatsSerializer(read_only=True,many=True) class Meta: model=Autor fields=('name','words') Views.py class AutorView(viewsets.ModelViewSet): queryset = Autor.objects.all() serializer_class = AutorSerializer class StatsView(viewsets.ModelViewSet): serializer_class = StatsSerializer queryset = Stats.objects.all() Urls.py from django.contrib import admin from django.urls import path,include from Teonite import views from rest_framework import routers router=routers.DefaultRouter() router.register('autors',views.AutorView) urlpatterns = [ path('',include(router.urls)) ] I using django 2.0, python 3.6 and Django REST framework 3.8.2 -
Django: View-related functionality, specific for the model, where to put?
I.e. I have the Model (actually abstract one, used in many other classes) with two ImageField rendered and preview and it's commonly used operation in views to redirect to rendered or preview depending on request. So I'd like to put some method in my model, which returns desired HttpResponseRedirect, but I feel that it's definitely bad practice to mix Model and View functionality. What is best practice, where to put View-related functionality, specific for the Model? -
Django: Annotate the count of the number of duplicate values for each object
I have a model called Product seen below. Products can have the same field 'bc_sku'. class Product(models.Model) bc_sku = models.IntegerField(null=True, blank=True) product_type = models.CharField(null=True, blank=True, max_length=50) merchant = models.CharField(null=True, blank=True, max_length=50) product_price = models.DecimalField(null=True, blank=True, max_digits=10, decimal_places=2) For example, imagine I had this list of objects bc_sku | product_type | merchant | product_price 100 | good | A | 1.00 100 | bad | B | 2.00 100 | bad | C | 3.00 101 | good | A | 7.00 101 | bad | B | 5.00 What I'd like to do is create a query which annotates each "good" product with the count of the number of duplicates along with the minimum price for each 'bc_sku'. I would then like to be able to use these objects and values in a template. bc_sku | product_type | merchant | dup_count | min_price 100 | good | A | 3 | 1.00 101 | good | A | 2 | 5.00 Any help would be greatly appreciated as I'm struggling to get annotations and filters to make it work currently. -
Django doesn't store password field in User model
I created a signup page using Django's builtin signup forms.Here is my code below forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Please provide a valid email address.') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') def clean(self): cleaned_data = super(SignUpForm, self).clean() username = cleaned_data.get("username") email = cleaned_data.get("email") check_email = User.objects.filter(email=email) if check_email: raise forms.ValidationError( "You are already registered!") return cleaned_data check_username = User.objects.filter(username=username) if check_username: raise forms.ValidationError( "A user with that username already exists") return cleaned_data In my views.py this is how I do the authentication for signup views.py @csrf_exempt def signup_users(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) print("signup authencticate", user) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) Here is my code to handle user login @csrf_exempt def login_view(request): print(request.user.is_authenticated()) if request.POST: email = request.POST.get('username') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return render(request, "login.html") else: return render(request, "login.html") When I signup, everything seems fine but when I try to login, it just won't … -
Django - Execute Celery task with options but no function arguments
I'm using Celery for the first time. Looking at the documentation, it seems like I've tried everything to properly execute the task using apply_async. I'm calling the task from a signal method so it's in signals.py. signals.py from django.db.models.signals import post_save from django.dispatch import receiver from datetime import datetime, timedelta from games.models import Game from contacts.models import Contact from msgs.models import SMS from msgs.tasks import sendSMS_Scheduled @receiver(post_save, sender=Game) def createSMS(sender, instance, created, **kwargs): if created: contacts = Contact.objects.all() body = SMS.defaultMessageBuilder( location=instance.location, time=instance.schedStart ) eta = instance.schedStart - timedelta(hours=7) expire = instance.schedStart result = sendSMS_Scheduled.apply_async(eta=eta, expires=expire) tasks.py from celery import shared_task from SMSerSite.celery import app from contacts.models import Contact from .models import SMS @shared_task(name='SMSerSite.msgs.tasks.sendSMS', bind=True) def sendSMS_Scheduled(): messages = self.request.sms_set.all() SMS.sendSMS(messages) When the code runs, I get an error: sendSMS_Scheduled() takes 0 positional arguments but 1 was given. I've tried various ways of writing the line where I call the task using apply_async but nothing works. What am I getting wrong here? -
Load Flask App into Django page
I'm working with the Dash framework by Plotly and would like to load the application into a Django app using Flask's capabilities. I'd like the behavior to resemble that of an iframe, but as a secure session loader so it can only be displayed via going through the Django authentication process. Is this something I would implement on the underlying webserver or can I accomplish this with just an additional library for Django and/or Flask? -
x__icontains match 2 values
I'm trying to make a call to python from javascript and I want to match 2 values with __icontains. This is what I currently have fetchData(value) { axiox.get('/api/beats.json/', { params: { name__icontains: value, fields: 'field1', 'field2' } }) .then(response => (this.beats = response.data)) .catch(err => console.log(err)) } But I need to pass 2 values, so it would become something like this: fetchData(value1, value2) { axiox.get('/api/beats.json/', { params: { name__icontains: [value1, value2] fields: 'field1, field2' } }) .then(response => (this.beats = response.data)) .catch(err => console.log(err)) } Array syntax doesn't work, this name__icontains: 'x, y' neither. How can I get this to work? -
How to set up free and paid versions of website?
I am currently redesigning a website and looking for a solution on how to add a paid version of the site. For example, say I have a <select> drop-down box with 20 elements inside. However, I want 15 of these 20 elements to be disabled unless the user has a paid account. At this time, that is the extent of what I need to differentiate between free/paid versions. I'm planning on adding the ability to register an account and log in, as well as some type of payment processor (recommendations are appreciated for this! - currently looking at using Django/Python). I just don't know how to best go about managing two different levels of the website, and allowing those additional options to paid members. -
GeoDjango Distance() Annotation on Related Model
I have a Profile class which is a OneToOne with Location model. Every profile has one and only location. class Location(models.Model): profile = models.OneToOne(Profile) point = PointField() In one of my views, I display a list of profiles. For example I first find profiles with locations and then find associated profiles. ref_location = Point(0,0) # point to calculate distances from locations = Location.objects.filter(point__distance_lte=(ref_location, D(m=50 * 1000))) \ profiles = Profile.objects.filter(pk__in=locations.values('profile_id')) What I would want is to be able to know the distance to each of these profile instances, e.g. I want to do something like: profiles = Profile.objects.filter(pk__in=locations.values('profile_id'))\ .annotate(distance=Distance('location__point', ref_location)) and then iterate over for p in profiles: print(p.distance.km) Which is not possible What I can do is annotate the locations instead, which isn't much use, because in the template I loop over profiles, not locations -
Django: how to transform an exception from a signal to a form error in CBV?
For the need of checking uniqueness on an M2M field, I was advised to write a signal that is triggered when m2m changes. It works well. However, when using a class based view to create a Badge object, I'd like to catch this exception and transform it into a form error, so that the error can be displayed in a clean way to the user, instead of getting a HTTP 500 error. I'm not sure how to do this in a clean way however. Usually it's easy because it's automatically handled with model clean() or form clean(), but not here. signals.py @receiver(m2m_changed, sender=Badge.restaurants.through) def check_uniqueness(sender, **kwargs): badge = kwargs.get('instance', None) action = kwargs.get('action', None) restaurants = kwargs.get('pk_set', None) if action == 'pre_add': for restaurant_pk in restaurants: if Badge.objects.filter(identifier=badge.identifier).filter(restaurants=restaurant_pk): raise BadgeNotUnique( f'Badge with identifier {badge.identifier} already exists ' f'for restaurant {Restaurant.objects.get(pk=restaurant_pk)}' ) views.py class BadgesCreateView(PermissionRequiredCanHandleBadges, ModelInContextMixin, SubSectionBadges, BillingClusterMixin, CreateView): model = Badge template_name = "badges/badge_add.html" fields = ('identifier', 'owner', 'expiration', 'is_active', 'restaurants') success_url = reverse_lazy('bo:badge-list') -
Django form for creating users with different permissions
I'm working on a Django system where there are four levels of users: 1. Basic (access only) 2. Admin (can update/change/delete) 3. Gatekeeper (can only create Admin users, cannot update/change/delete) 4. Developer (true superuser) I think I have the permissions somewhat figured out: from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save class CustomUserManager(BaseUserManager): """Customer User.""" def create_user(self, email, password=None): """Creates and saves a user.""" if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_admin(self, email): """Creates and saves an admin user with a temporary password.""" user = self.create_user( email, password=BaseUserManager.make_random_password(self, 12) ) user.is_admin = True user.save(using=self.db) return user def create_gatekeeper(self, email, password): """Creates and saves a gatekeeper.""" user = self.create_user( email, password=password, ) user.is_admin = True user.is_gatekeeper = True user.save(using=self.db) return user def create_superuser(self, email, password): """Creates and saves a superuser.""" user = self.create_user( email, password=password, ) user.is_admin = True user.is_gatekeeper = True user.is_developer = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_gatekeeper = models.BooleanField(default=False) is_developer = models.BooleanField(default=False) objects = CustomUserManager() … -
Postgresql + Django: What is better (for long term)? Same string, or many to many relationship?
I'm currently designing my data base using postgresql with Django and I was wondering: What is best practice - having several instances of the same model with the same value or a many to many relation ship? Let me elaborate. Let's say I'm designing a store. The store sells items. Items can have one or many statuses (e.g. ordered, shipped, delivered, paid, pre-ordered etc.). What would be a better practice: Relating the items to their status via a many-to-many relationship, which will lead to one status having hundreds of thousand and later millions of relations? Will so many relations become problematic? Or is it better for each item to have a foreignkey to their statuses? So that each status only has one item. And if I would like to query all the items that have the same status (e.g. shipped), I would have to iterate over all statuses with a common name. What would be better, especially for the long term? Any help would be much appreciated! -
DJANGO: local variable 'usuarios' referenced before assignment
I have a problem with this. When a record already exists, I like the data, but when not, obviously not. How is this validated so that the template can be seen when there is no record of a post? Image error view.py def MemoList(request, usuario): instancia = get_object_or_404(Empleado, usuario_id=usuario) lista2 = Memorandum.objects.filter(para_id=instancia) for usuarios in lista2: lista_de = usuarios.de lista_para_id = usuarios.para_id lista_asunto = usuarios.asunto lista_fecha = usuarios.fecha context = { "lista2":lista2, "lista_de": usuarios.de, "lista_para_id": lista_para_id, "lista_asunto": lista_asunto, "lista_fecha" : lista_fecha } return render(request, 'app/admin/memolist.html',context) -
DJANGO KeyError when using request.session with form.cleaned_data
I have 2 view functions. One takes form data and (optimally) stores it in the request.session. The second calls this data and uses it to filter in a search query. I also have 2 html templates that correspond to each of these views. Here are the Views def searchpatients(request): form = PatientSearchForm(request.POST or None) if form.is_valid(): request.session['fdata'] = form.cleaned_data['first_name'] request.session['ldata'] = form.cleaned_data['last_name'] context = { 'form_search' : form, } return render(request, 'polls/search.html', context) AND def displayed_try(request): fdata = request.session['fdata'] ldata = request.session['ldata'] results = Patients.objects.filter( first_name__icontains = 'fdata' ).filter( last_name__icontains = 'ldata' ).values_list('first_name', 'last_name', 'phone_number', 'status') context = { 'results' : results } return render(request, 'polls/displayed.html', context) When running the search function, I get a key error like this KeyError at /displayed/ 'fdata' Request Method: POST Request URL: http://localhost:8000/displayed/ Django Version: 2.0.6 Exception Type: KeyError Exception Value: 'fdata' Exception Location: C:\Users\msengar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sessions\backends\base.py in getitem, line 55 Python Executable: C:\Users\msengar\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.5 Can anyone point me in the right direction? I am not sure how to take data from a form (on a distinct HTML template) in Django and use that form data to search and display on another HTML page. For reference, my 2 html pages are search.html (which houses … -
Json Serialize GeoDjago point and also FK relations
I am trying to get a Json response which contains both a geo point and information from foreign key objects in django. My current code is below: location_point = Point(location.longitude, location.latitude, srid=4326) events = TimetableEvent.objects.annotate(distance=Distance('venue__location', location_point)).order_by('distance')[0:5].values('activity__name','venue__name','venue__location','distance') qs_json = serializers.serialize('geojson', events,geometry_field='point') This gave me a meta error as I was trying to use a values query set *** AttributeError: 'dict' object has no attribute '_meta' I have also tried using the geojson fields to select the points but I am having no luck: location_point = Point(location.longitude, location.latitude, srid=4326) events = TimetableEvent.objects.annotate(distance=Distance('venue__location', location_point)).order_by('distance')[0:5] qs_json = serializers.serialize('geojson', events,geometry_field='venue__location',fields=('activity__name','venue__name','venue__location','distance',)) This just gave me empty data p qs_json '{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}]}' Then I tried to use json dumps to print out a list of the data but I get an error related to the distance annotation or the point eg: (Pdb) json.dumps(list(events)) *** TypeError: Object of type 'Point' is not JSON serializable So a few ways not to do it but I would really appreciate some help getting the right way! The model for Timetable …