Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django account and unique users per account concept
I'm trying to figure out the best way to model and implement a Django project with the concept of accounts and unique users per account. The built in auth and users model seemed good at first, but from my tests it has no concept of accounts, just groups (which I don't think gives me enough here). I thought of using the existing auth User model and adding an account and account user model to join the two. This worked at first but didn't work with the django provided admin site as an account is not needed, failing the authenticate check. What I require is: The concept of accounts Users that are linked to one or more accounts that they can only log into but not the Django admin site Admin users that can log into the Django admin site AND any account I'm thinking at some point I will need to store the account model in the session for accessing any data related to the account, is that the preferred way for this? Any suggestions and how to do this with Django best practice would be very helpful! -
How to link my backend bokeh plots to an angular 4 front end, DYNAMICALLY
I have a front end(angular 4 based) viewed by my customers. They want to see a bunch of different plots that could be dynamically plotted. For ex: for a date time based line chart they could want to see visualizations on a 7 day or 8 day or 365 day period. I compute my data in Pandas and pass it onto a bokeh plot. The problem arises, when I have to push this to the front end. One way I understood this could be done is through using the components function https://bokeh.pydata.org/en/latest/docs/user_guide/embed.html. Where the static javascript could be embedded on the front end, and then a very very long json(json_docs) could be passed onto the front end. But this would mean i would need to build an API to parse and send it. I have tried understanding the bokeh server thing with no luck. So any examples would definitely help more. Is there any way to dynamically compute using pandas, plot and then send the plot to a angular 4 front end, with callbacks ? If so, is there a way to do it within bokeh itself ? Not having to deal with django, or flask API. Lastly, is there β¦ -
How to make user active in django allauth?
I have a custom user model (AbstractBaseUser). When i login with google allauth, it says my account is inactive. How can i make it active? Perhaps, override method or something? -
IndexError: tuple index out of range, when trying to print model object
here's my model: class Book(models.Model): title = models.CharField(max_length=255) reviews = models.ManyToManyField(User, through="Review") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __repr__(self): return "<Book object: {}>".format(self.title) In the shell, here's the error when I try to print with Book.objects.all(): Traceback (most recent call last): File "<console>", line 1, in <module> File "/django/db/models/query.py", line 235, in __repr__ return '<QuerySet %r>' % data File "/models.py", line 86, in __repr__ return "<Book object: {}>".format(self.title) IndexError: tuple index out of range -
Django: custom method call in API returns false
I'm a beginner in Django doing this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial02/ I however got stuck at the part where they teach you how to use the API (scroll down untill you reach the playing with the API part): >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() False Here's the complete source code (models.py): from django.db import models import datetime from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text At first I thought that maybe the spaces between the functions aren't enough so I tried to fix it, when that didn't work I copied and pasted the exact code, can somebody please tell me how what went wrong and how to fix this? Thanks in advance! Python version: 3.5 Operating System: Linux Mint Cinnamon -
Pulling Dictionary Data from Django into Swift
I have a Django platform for restaurants and I am connecting it to my Swift App. I've created a form within Django where restaurants are able to add their product with descriptors and it is wrapped in a dictionary but, I cant seem to pull it into my swift file. This is how I've set up my Swift import file: import Foundation import SwiftyJSON class Product { //This pulls the information per product. Edit information here and attach to each dispensary cell. var id: Int? var name: String? var short_description: String? var image: String? var price: Float? var usage: String? var size: String? init(json: JSON) { self.id = json["id"].int self.name = json["name"].string self.short_description = json["short_description"].string self.image = json["image"].string self.price = json["price"].float self.usage = json["usage"].string self.size = json["size"].string } Here is the data structure that I'm pulling in from my Django server via JSON: {"product": [{"id": 9, "name": "Test Mealβ, "short_description": "Best Mealβ, "usage": βBelly Busterβ, "sizes": [{"size": 2, "price": 15.13}, {"size": 3, "price": 123.11}, {"size": 5, "price": 200.0}], "image": "http://localhost:8000/media/product_images/Great_White.jpg"}]} Then I'm have a helper file in Swift that pulls my the data from my Django Server: func getProducts(restaurantId: Int, completionHandler: @escaping (JSON) -> Void) { let path = "api/customer/product/\(restaurantId)" β¦ -
Can Not Load Static Files in Django
I am trying to add an image to a very basic html template. I am able to render the html file, but unfortunately the image will not display. Here is my error: Not Found: /exapp/pic.jpg [21/Apr/2018 18:43:49] "GET /exapp/pic.jpg HTTP/1.1" 404 2145 I noticed that django was looking for the file with a path of /exapp/pic.jpg, so I created a folder in my static directory called exapp, and put the image in there. Still no image :( the file structure is as follows: β db.sqlite3 βββ exapp β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β β βββ __pycache__ β β βββ __init__.cpython-35.pyc β βββ models.py β βββ __pycache__ β β βββ admin.cpython-35.pyc β β βββ __init__.cpython-35.pyc β β βββ models.cpython-35.pyc β β βββ urls.cpython-35.pyc β β βββ views.cpython-35.pyc β βββ static β β βββ exapp β β βββ pic.jpg β βββ templates β β βββ index.html β βββ tests.py β βββ urls.py β βββ views.py βββ manage.py βββ mysite βββ __init__.py βββ __pycache__ β βββ __init__.cpython-35.pyc β βββ settings.cpython-35.pyc β βββ urls.cpython-35.pyc β βββ wsgi.cpython-35.pyc βββ settings.py βββ urls.py βββ wsgi.py Here is the HTML file in question: <html> <head> <title> β¦ -
User authentication doesn't set is_authenticated properly
I am using custom authentication with custom user model. When user authenticates it redirects to the home page, as needed, but the user does not get authenticated? And when I check in a template {{user.is_authenticated}} it says False. How to fix that? Here is my backend file for custom authentication: from contracts.models import User from django.contrib.auth.hashers import check_password class AuthBackend: def authenticate(self, email=None, password=None): try: user = User.objects.get(email=email) if not check_password(password, user.password): return None except User.DoesNotExist: return None return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None my view: class LoginView(View): form_class = LoginForm template_name = 'login.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') return render(request, self.template_name, {'form': form}) Added to my setting file: AUTHENTICATION_BACKENDS = ['contracts.auth.backend.AuthBackend'] AUTH_USER_MODEL = 'contracts.User' -
How to get select field text from html form in django?
I have created a form with select field in template ehrinfo.html <form action="{% url 'ehrs:compcreate' %}" method="GET"> <select> <option value="Vital Signs">Vital Signs</option> <option value="Cancer Signs">Cancer Signs</option> </select><br><br> <input type="submit" value="Select Template" class="addehr"> </form> I have defined form class as: class templateselect(forms.Form): CHOICES = ( ('Vital Signs', 'Vital Signs'), ('Cancer Signs', 'Cancer Signs'), ) template = forms.ChoiceField(widget=forms.Select, choices=CHOICES) Now I want to get selected text from this form in view compcreate. So I used: def compcreate(request): if request.method == 'GET': form = templateselect(request.GET) print("a") if form.is_valid(): print("b") template = str(form.cleaned_data["template"]) but it cant get past the if form.is_valid(): part as 'a' is printed but 'b' is not printed on console. What is the problem? How can I get the selected text in compcreate()? -
Django cleaned_data.get('obj') method returns none
I'm doing a little password confirmation form in django. But Im confused as the self.cleaned_data.get('confirm_password') always returns none and hence my passwords never match to one another. Heres the clean method in the forms.py def clean_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: print(password) print(confirm_password) raise forms.ValidationError( "Password and password confirmation does not match" ) return password self.cleaned_data.get('password') returns the typed password but the confirm_password doesnt. In the view.py when I see the received data before cleaning, the confirm_password shows as it is ......................user = UserRegister(request.POST) print(request.POST.get('confirm_password')) if user.is_valid(): print('valid').......................... What could possibly be the reason for this?? Heres the form declaration part in forms.py first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'})) username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField( required=True, widget=forms.widgets.EmailInput(attrs={'placeholder': 'Email'})) password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) confirm_password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) class Meta: model=User fields=['first_name','last_name','username','email','password','confirm_password'] -
How to Disable Follow Feature on Django-Activity-Stream
I'm creating a Django application with django-activity-stream. I've registered the app inside the project. Unfortunately, the built-in follower/following feature of the app conflicts with my Follow table - I want more granular control than the library allows. Anyone know how to disable the feature or sidestep this issue? ERRORS: actstream.Follow.content_type: (fields.E304) Reverse accessor for 'Follow.content_type' clashes with reverse accessor for 'Follow.content_type'. HINT: Add or change a related_name argument to the definition for 'Follow.content_type' or 'Follow.content_type'. actstream.Follow.user: (fields.E304) Reverse accessor for 'Follow.user' clashes with reverse accessor for 'Follow.user'. HINT: Add or change a related_name argument to the definition for 'Follow.user' or 'Follow.user'. content.Follow.content_type: (fields.E304) Reverse accessor for 'Follow.content_type' clashes with reverse accessor for 'Follow.content_type'. HINT: Add or change a related_name argument to the definition for 'Follow.content_type' or 'Follow.content_type'. content.Follow.user: (fields.E304) Reverse accessor for 'Follow.user' clashes with reverse accessor for 'Follow.user'. HINT: Add or change a related_name argument to the definition for 'Follow.user' or 'Follow.user'. Follow Model: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() -
404 error on CreateView form_valid with more than 1 arguement
My proof App's CreateView takes 2 arguments "user" and "post". The user requirement is fulfilled by self.object.user = self.request.user How do I satisfy the self.object.post requirement. I am new to Django. I apologize if I am violating any Django rules models.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='proofmade') made_at = models.DateTimeField(auto_now=True) image_of_task= models.ImageField() proof_you_made_it = models.ImageField() suggestions = models.TextField(max_length=1000) def __str__(self): return self.post.title views.py User = get_user_model() class ProofCreate(LoginRequiredMixin, CreateView): model = Proof fields = ('image_of_task', 'proof_you_made_it', 'suggestions') def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.user = self.request.user ########## slug = self.kwargs.get('slug')###### I think this line may be wrong print(slug) self.object.post = get_object_or_404(Post, slug=slug) self.object.save() return super().form_valid(form) -
django-filter for django rest frameworks
I am hoping there is a solution for my issue. I am trying to produce a call to a url in javascript from a path that looks like this: /api/vendor_filter/?city=&zipCode=29615&dateServing=04%2F21%2F2018 I have set the filter of the call to call data from date and zip code. What I am hoping to achieve is because this call already populates the date as current date and zip code from a registered device zip code that the zip code in this case 29615 actually pulls a range from 29601, 29627 so that any zip code in that range is retrieved. This would be the same as stating list(range(29601,29627+1)) so that the user zip code pulls all zip code items in the database in that range. -
paypal monthly subscription plan settings for first day of the month - django python
I am using Django paypalrestsdk for paypal https://github.com/paypal/PayPal-Python-SDK And I would like to setup a monthly subscription plan. Every beginning of the month, buyer will be charged USD100. This is my billing plan code I have made: billing_plan = paypalrestsdk.BillingPlan({ "name": "Monthly Billing Plan", "description": "Monthly Plan", "merchant_preferences": { "auto_bill_amount": "yes", "cancel_url": "http://localhost:8000/payment_billing_agreement_cancel", "initial_fail_amount_action": "continue", "max_fail_attempts": "0", "return_url": "http://localhost:8000/payment_billing_agreement_execute", "setup_fee": { "currency": "USD", "value": "100" } }, "payment_definitions": [ { "amount": { "currency": "USD", "value": "100" }, "cycles": "0", "frequency": "MONTH", "frequency_interval": "1", "name": "Monthly Payment", "type": "REGULAR" } ], "type": "INFINITE" }) It is not clear to me if it is charging on the first day of the month or the last day of the month ? Should I have the setup so its charged immediately ? My intention is charging is done on the first day of the month. I am seeing this in the sandbox of the buyer: Preapproved payment USD100 What does this mean, is he charged already USD100 or preapproved and charged on the last day of the month ? -
Django- Json data in template
I am accessing an API and get JSON data. I can see that JSON is generated. However I am not able to show it in template. Below is the sample Json data. { "response_code":1, "response":{ "a":"01/07/2017", "b":"12", "c":"23", "d":"34", "e":"45", "f":"56", }, "error_code":null, "error_message":null } I passed this data in view to template as dataset. What I tried in template. {% for key, value in dataset.items %} {{key}}: {{value}} {% endfor %} Another try {% for d in dataset %} {% for key, value in d.response.items %} {{key}} {{value}} {% endfor %} {% endfor %} Template is not showing any error or any response. What I am doing wrong here? -
Does Django default tables is possible change name?
Does Django default tables is possible change name? django_migrations django_content_type django_admin_log -
Django Migration Order with AUTH_USER_MODEL
I changed the name of a model in one of my apps and now when I go to run the migration it's erroring out because the first migration it runs depends on the changed model. I've checked the order in the settings.py installed apps shown here: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sites', 'django.contrib.sitemaps', 'storages', 'rest_framework', 'rest_framework.authtoken', 'verification', 'comp', 'direct', 'comm', 'track', 'match', 'crawlers', 'event', 'c', 'forum', 'widget_tweaks', ] 'comm' is the app I need to migrate first and I've repeatedly run: python manage.py makemigrations comm and then python manage.py migrate comm still no luck. The only other thing I can think of is a dependency issue. Here are the dependencies for the migration that brings the model over: dependencies = [ ('direct', '0006_auto_20180420_1937'), ('match', '0013_auto_20180420_1937'), ('forum', '0020_auto_20180420_1937'), ('event', '0040_auto_20180420_1937'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('comm', '0037_auto_20180404_2012'), ('track', '0002_auto_20180420_1937'), ('comp', '0074_auto_20180305_1740'), ] -
AttributeError: 'BookForm' object has no attribute 'get'
Error : AttributeError: 'BookForm' object has no attribute 'get'. im unable to debug the problem.please be helping out.thanks in advance forms.py from django import forms from .models import Book class BookForm(forms.Form): class Meta: model = Book fields = ['title', 'sub_title', 'author', 'image', 'price', 'description', 'ISBN', 'number_of_pages','dimensions', 'interior_pages','binding','availability','genre'] urls.py from django.urls import path from . import views urlpatterns = [ path('',views.BookForm, name = 'bookform' ), ] views.py from django.shortcuts import render,redirect from .forms import BookForm def bookview(request): if request.method == 'POST': form = BookForm(request.post) if form.is_valid(): model_instance = form.save() model_instance.save() return redirect('/') else: form = BookForm() return render(request,'book.html',{'myform':form}) template <html> <head> <title>edit</title> </head> <body> <form method="post" > {% csrf_token %} {{form.as_p}} <input type="submit" value="ok"> </form> </body> </html> -
Return context from class based view in django
So if I used function views like so : def messageView(request): webpages_list = AccessRecord.objects.order_by('date') date_dict = {'access_records':webpages_list} return render(request,'index.html',context=date_dict) And my url resolver looks like this : path('', views.messageView , name='index'), Every thing is fine, my records are displayed as expected : HOWEVER, when I try to use class based view like so : class IndexView(CreateView): form_class = RegisterUserForm template_name = "index.html" def index(self,request): webpages_list = AccessRecord.objects.order_by('date') date_dict = {'access_records':webpages_list} return render(request, self.template_name,context=date_dict ) And url is like so : path('', views.IndexView.as_view(), name='index'), I get nothing in this case, I've tried looking for simple cases of just returning a context from a class view in django online, but to no avail. What exactly am I misunderstanding here please ? -
Coverage show test get_serializer_class as untested
Use coverage to show what have to be covered by tests drf views. And coverage show that all view is tested ok (cover by unittest + dango client API) But coverage shows that this part need to be covered: def get_serializer_class(self): return self.serializer_class ` Any idea how to cover that past of code in GenericAPIView? Thx for any help -
Redefine label in django modelform
I have a Django model in wich I have a models.CharField named level I then create a ModelForm from this model, and I want the level to be a select from a ChoiceField. So I create a new widget in the ModelForm. The only problem is that then it seems like I cant redefine the labels for the level. It only appear as "level" in my form. from django import forms from events.models import Event class EventForm(forms.ModelForm): level = forms.ChoiceField(choices=[("RT","RT"), ("RT+","RT+"), ("RI", "RI"), ("RI+", "RI+"), ("RS", "RS"), ("RS+", "RS+"), ("RE", "RE")]) class Meta: model = Event labels = { "title": "Titre de l'évènement", "level": "Niveau de la randonnée", # HERE: wont rename the label "map_url": "Lien Google Map de l'itinéraire", "date": "Date et heure de l'activité (au format DD/MM/YYYY HH:MM)" } exclude = ("slug",) -
How to run pip installed elasticsearch?
I'm trying to use Django + Haystack + Elasticsearch. So I installed Elasticsearch 2.4 with pip becouse Django gave me errors about that it can't import Elasticsearch. Now it can and I can run ./manage.py rebuild_index in my Django project and it gives this output: Indexing 23 journal entrys GET /haystack/_mapping [status:404 request:0.006s] but only if I somehove run elasticsearch. So I installed elsasticsearch2 from AUR packages as well and run that. But as I suspected when I try to get all documents by running: curl -X GET "localhost:9200/_cat/indices?v" which returns: health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open haystack 5 1 0 0 795b 795b If I understand correctly it is empty. I went where pip installs packages(/usr/lib/python3.6/site-packages) and found two folders related to Elasticsearch: elasticsearch βββ client β βββ cat.py β βββ cluster.py β βββ indices.py β βββ ingest.py β βββ __init__.py β βββ nodes.py β βββ __pycache__ β β βββ cat.cpython-36.pyc β β βββ cluster.cpython-36.pyc β β βββ indices.cpython-36.pyc β β βββ ingest.cpython-36.pyc β β βββ __init__.cpython-36.pyc β β βββ nodes.cpython-36.pyc β β βββ snapshot.cpython-36.pyc β β βββ tasks.cpython-36.pyc β β βββ utils.cpython-36.pyc β βββ snapshot.py β βββ tasks.py β βββ utils.py βββ compat.py β¦ -
Django JSONField filtering Queryset
For project I'm using Python 3.6.3, Django 2.0 and Postgre 9.4. In my class Ticket, a have JSONField passenger passenger = JSONField(blank=True) and my passenger JSON looks like this: { "email": null, "mobile": "21312", "passport": "2141241", "sms_sent": false, "full_name": "something" }, { "email": null, "mobile": null, "passport": "1231231", "sms_sent": false, "full_name": "Irfan" }, { "email": null, "mobile": null, "passport": "1231231", "sms_sent": true, "full_name": "Irfan" } Now I have django command where I want to filter tickets that have mobile that is not null or None, and sms_sent is False. tickets = Ticket.objects.filter( date=tomorrow, trip__bus_company=bus_company, passenger__sms_sent=False ).not_cancelled() Now passenger__sms_sent=False filter is working, and is giving my only Tickets with sms_sent=False. But passenger__mobile filter is not working. I tried everyone of this: tickets = tickets.exclude(passenger__mobile=None) tickets = tickets.exclude(passenger__mobile=None).exclude(passenger__mobile='') tickets = tickets.exclude(passenger__mobile__isnull=True) tickets = tickets.exclude(passenger__exact={'mobile': None}) tickets = tickets.exclude(passenger__mobile__isnull=True).exclude(passenger__mobile='') tickets = tickets.exclude(passenger__mobile__isnull=False).exclude(passenger__mobile='') tickets = tickets.exclude(Q(passenger__mobile__isnull=True) | Q(passenger__mobile='')) and also puting passenger__mobile in first filter, but I can not filter out(exclude) tickets where passenger__mobile is null. Now I can do this: for ticket in tickets: if ticket.passenger['mobile'] is not None: print(ticket.passenger['mobile']) but that is not what I'm looking for. I want to use filter or exclude to get those tickets. What I'm I doing β¦ -
add +1 hour to datetime.time() django on forloop
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying out.hour+1 with this code, but didn't work. overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours how to add 1 hour every loop?... -
Changing object data in javascript of a Django/Heroku website
I'm wondering if it's possible for me to change the values of a data object inside my javascript. The javascript receives postmessages from an iframe and I need to be able to store that information to the correct objects, but I'm not quite sure how to do it on the HTML surface or if it's possible to do in the javascript surface. I can call {{ game.gameData.high_score}} in the HTML to fetch the high_score of a certain game object, but my attempts at working out how to have my javascript send values to these objects flies right over my head. The most recent venture I tried was simply doing game.gameData.name = somevalue; in the javascript, but this doesn't seem to change the global value for this data object value (the change is not seen outside of the javascript). Are there any solid ways of handling this inside/outside of javascript in Django/Heroku environment?