Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I consume REST APIs from ESP8266?
Using Django and Django Rest Framework I have created a server and implemented some REST APIs in it. In django rest framework I have enabled token based authentication and I'm able to test my APIs by following this tutorial. Also I'm able to access my APIs by loggin in from browser. Now I have to consume these APIs from ESP8266. For that I'm following examples given here, I'm using following code http.begin("http://192.168.1.12/rest/v1/sensors"); http.setAuthorization("user", "password"); int httpCode = http.GET(); String payload = http.getString(); Serial.println(payload); But I'm getting {"detail":"Authentication credentials were not provided."} on serial port. Also I have tried using following code: http.begin("http://192.168.1.12/rest/v1/sensors"); http.setAuthorization("dXNlcjpwYXN3b3Jk"); int httpCode = http.GET(); String payload = http.getString(); Serial.println(payload); // where dXNlcjpwYXN3b3Jk = base64 encoding of user:password Still I'm getting same output on serial port. What am I doing wrong here? Also if I want to consume the REST API in ESP8266 using token, how can I do that? -
How to process incoming data in Django-rest-framework to run ML on it and then send results to user?
So I've been using DRF, which holds some sentiment analysis code. What I'd like to do is let the user submit data, and then run sentiment analysis on it, and send the result back to the user (and also store it in a Model), most Serializer implementations I see online, directly push the data to the Model. I just want to access the inputs as they flow in, and then serve users the results. Right now I'm using a Flask based implementation, which is as follows: from flask import Flask, render_template, request import Core import Text_Processing_Engine import Classifier app = Flask(__name__) app.config['DEBUG'] = False @app.route("/") def home(): return render_template("index.html") @app.route("/chat") def add(): return render_template("Chat.html") @app.route("/result", methods=['POST']) def result(): query = request.form.get("Query") sentence = query Trained = True if Trained == False: #MLCODE result = response[0] else: #MLCODE result = response[0] return render_template("result.html", result=result) if __name__ == "__main__": app.run() While I like the simplicity and customization Flask has to offer, I prefer Django's approach, that let's me take my eyes off security and all the issues. Thanks in advance 🙂 -
Python multiple divs in a row dependent on screen width
Hello dear stackoverflow community, as this is my first time ever asking something here please excuse me if I miss any necessary information. I started to learn Python and the Framework Django by reverse engineering the following website: thieve.co as a practice. Now I am stuck with the following issue: All my uploaded articles, that are displayed as cards (bootstrap) are automatically arranged below each other. What I actually want to do is that they are displayed in rows, where the number of cards depend on the screen size. views.py: from django.shortcuts import render,redirect from .models import Article from django.http import HttpResponse from django.contrib.auth.decorators import login_required from articles import forms def article_list(request): articles = Article.objects.all().order_by('date') return render(request,'articles/article_list.html',{'articles':articles}) def article_detail(request,slug): #return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request,'articles/article_detail.html',{'article': article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request,'articles/article_create.html',{'form':form}) urls.py: from django.urls import path from articles import views app_name='articles' urlpatterns = [ path('',views.article_list,name="list"), path('create/', views.article_create,name="create"), path('<slug:slug>',views.article_detail, name="detail"), ] models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date … -
Any way for dehydrate() to share an object during an API call in tastypie?
Is there any way for the dehydrate function in tastypie to share some variable? In any other framework, every request would create a new instance of the class, so we can use self to share data. My use case: want to dehydrate objects returned by GET list with some additional data, but the request gets heavy due to the repeated db calls. Not everything is from a standard sql db, so prefetch_related will only take me so far. class Meta: queryset = Entry.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] def dehydrate(self, bundle): # # wanted something like this # bundle.foo = self.cache['foo'] # # but self is shared between all requests as an instance # # of this class is declared while initializing, and I want # # self.cache to be recreated for every request (without # # potential races) urlpatterns = [ url(r'^api/', include(EntryResource().urls)), ] -
Django REST framework serializer is slow even with prefetch related
I'm trying to serialize 30-50 instances with a few nested models each (e.g. Posts with some data, nested image and nested writer details). The serialization takes 50-150ms and makes the response quite slow. The data is prefetched so the queries themselves take around 15ms. What's the best approach to speed up the serialization? -
Is there a way to send push notifications with Django
Hello I wonder is there a way to send push notifications with Django to an user I have a website that accepts/refuses vacation demands When user sends a vacation demand my Django app sends email to the CEO to notify him that there was a new vacation request When the CEO accepts the demand it sends email to the user that the demand was accepted But since the CEO receives plenty of emails a day and he barely sees my emails i would like to make a browser notification whenever he opens the browser to see notification from my website that a demand is waiting to be approved/refused. is there a library that can do that for me I've tried django-webpush but I couldn't managed it to work even though I followed all the steps -
AttributeError: type object 'MyUser' has no attribute 'USERNAME_FIELD'
I am building a custom User class in django to use in creating a signup application and I keep on getting the error above every time I try to makemigrations. As far as I can see, my code is per django documentation here.. I also have AUTH_USER_MODEL correctly placed in my settings configurations. Here's my models.py `class MyUserManager(BaseUserManager): def create_user(self, email, first_name,last_name,profile_picture,phone_no,password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, profile_picture=profile_picture, phone_no=phone_no, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ SuperUser = self.create_user( email, password=password, ) SuperUser.staff = True SuperUser.admin = True SuperUser.save(using=self._db) return SuperUser class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name = 'email_address', max_length=255, unique=True, # validators=email_validator, ) first_name = models.CharField(max_length=20,blank=False,null=False) last_name = models.CharField(max_length=20,blank=False,null=False) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+254 ...'") phone_no = models.CharField(validators=[phone_regex], max_length=17, blank=False) profile_picture = models.ImageField(upload_to='media/',blank=False) #email_validator = EmailValidator(message='Invalid email address',code=None,whitelist=None) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','phone_no','profile_picture'] # Email & Password are required by … -
Possible to use mixins in function based views?
Like the title states, I'm wondering if it's possible to use mixins in a function based view. If so, how would I import it? The following code doesn't work: def payment_method_view(request, MyMixin): Thanks! -
Django project hosted with apache2 and mod-wsgi - make site root IP/projectname
I have a django project which I have deployed with apache2 on my server. I access this currently through my IP address. I would however like the apache 'root' (?) of the project to be IP_address/django_project/ I Have tried changing ServerName in my apache2 000-default.conf file, but I can't seem to get this working... 000-default.conf: <VirtualHost *:80> ServerName results ServerAlias results ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess results python-home=/home/django/config/env python-path=/usr/local/Databases/results WSGIProcessGroup results WSGIScriptAlias / /usr/local/Databases/results/django_project/wsgi.py <Directory /usr/local/Databases/results/django_project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /usr/local/Databases/results/static/ <Directory /usr/local/Databases/results/static> Require all granted </Directory> <Directory /usr/local/Databases/results> Deny from all Allow from *<subnet>* </Directory> </VirtualHost> How can I set this up so that I access this project through a new 'root'? Thanks -
Why Django DateField doesn't accept empty values?
I have a model with a DateField field with blank = True and null = True. It seems that is not possibile save an object with an empty value for the Datefield. class ProjectTask(models.Model): actual_start_date = models.DateField(blank=True, null=True) Then try with Python console: p = ProjectTask.objects.all().last() p.actual_start_date = "" p.save() The results is: venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1273, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] I'm using Python 3.4, Django 1.9 and PostgreSQL. Any suggestions? -
Django add to cart and cart view error
I get a 'NoneType' object is not iterable error when I add 1 object to the cart via the scan_to_cart view and want to add a second object. Also I get the same error when I want to view my cart when there are actually objects in it. I could not find a common problem with a solution... Is the python version I work with the issue, or is there a logic or code error? Thanks in advance for suggestions/advice! models: from manageinv.models import Child User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Child, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or … -
Django messages if connected model doesn't exist
I have a Profile model, which is a OnetoOne relation to the User model. I would like to tell the users that their profile is not complete, and ask them to fill in certain details dynamically. For example, I have a Location model which is a OneToOne to the Profile. (Question: should I add location fields into profile model since it's one to one? This way all location data can be found in profile instance and might make things easier) class Profile(models.Model): # some fields e.g. name class Location(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True) # longitude = ... # latitude = ... After user signup, we do not yet have the location instance connected to profile. What I would like to display, is a django-message/error bar at the top, instructing the user to complete the profile if the profile doesn't have the location attribute. I'm not sure how I should proceed: One way, I thought is to add the completed_setup boolean field to the Profile class. If user now decides to delete location, we will also update this field. {% if profile.completed_setup %}{% else %} <p>Finish Building Your Profile</p> {% endif %} Another way would be to have the following … -
How to make tests with Django using real data?
Here is my situation: We have a project that started by the wrong way, without testing. The Project uses Python 3.6* and Django 2.*. Anyway, now we are trying to code the tests and for this we are reading "Obey the Testing Goat" book, for Django tests. The problem is that we are in a closed network and our system uses LDAP to make login. LDAP user is compared with our Workers database and, if the worker was not fired or in vacances, he can log in the system. For This Worker database (HR) we just have access to make queries, not inserts or updates, create, delete, etc... In resume, we have no power to manage LDAP and HR Database, just make queries. Other thing: we have no power (privileges) to create more than one database in our SQLServer. They created for us a TestDatabase. So, I always need to put --keepdb when I run the test command. Also, if there is more than one database in settings, Django Tests will try to create both databases. As we have in settings.py the HR Database (it's not managed) and the Application Database (as default), Django are trying to create both databases. … -
How can I filter DRF serializer HyperlinkedRelationField queryset based on request data?
I have my users account authority stored in request.session.get('authority') At the moment the endpoint in DRFs web-browsable HTML representation is showing all the addresses of all accounts in the html form. Which I'd expect as I'm querying all the addresses. Company Serializer # ToDo: filter queryset objects class CompanySerializer(serializers.ModelSerializer): clients = serializers.HyperlinkedRelatedField( many=True, view_name='client-detail', queryset=Client.objects.all() ) addresses = serializers.HyperlinkedRelatedField( many=True, view_name='address-detail', queryset=Address.objects.all() ) class Meta: model = Company fields = ('name', 'url', 'clients', 'addresses') read_only_fields = ('authority',) I want to be able to do something like: addresses = serializers.HyperlinkedRelatedField( many=True, view_name='address-detail', queryset=Address.objects.filter(authority=request.session.get('authority')) ) But not sure there is a way to access the request data in the serializer when I'm setting up the HyperlinkedRelatedField. Perhaps I'm approaching this in entirely the wrong way. Any guidance will be greatly appreciated. -
Django app to run a python ML application
I have a python/pandas application that does data analysis and outputs reports to csv format. I would like to out an interactive front end UI on top of this application so the user can mix and match data, select parameters for scenario testing, have interactive charts and dashboards displayed on screen instead of csv etc. I am looking to use Django, but for interactive charts, do I need to learn a javascript library (which one), or will Django be sufficient? -
{ % include tag %} including only one object from another template
guys i need a small help here is my views.py def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) verification=VerificationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] email = userObj['email'] password = userObj['password'] return HttpResponseRedirect('/index/verification/') # if if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username = username, password = password) login(request, user) return HttpResponseRedirect('/') else: raise forms.ValidationError('Looks like a username with that email or password already exists') else: raise forms.ValidationError('a valid') else: form = UserRegistrationForm() verification = VerificationForm() return render(request, 'question/signup.html',context= {'verification':verification,'form' : form}) here you can see i have declared two context variables one is form and the other one is verification now i want to use now this is my signup.html {% extends 'question/index.html '%} {% block body_block %} <div class="conrainer"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <a href="{% url 'social:begin' 'facebook'%}">facebook auth</a> </div> {% endblock %} now i have used form variable in this page and i want to use verification varible in another page as django views are not made to use two templates in a single view after searching a lot in online forums i came to know about {% include tag %} after trying to … -
Django Rest Framework - How to POST foreign keys in ListCreateAPIView
Post model class Post(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE) # Profile is another model title = models.CharField(max_length=300) content = models.CharField(max_length=1000) votes = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) # Subreddit is another model PostSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' depth = 1 ListPostsOfReddit class ListPostsOfReddit(ListCreateAPIView): serializer_class = PostSerializer def get_queryset(self): return Post.objects.filter(subreddit__name=self.kwargs['r_name']) In the ListCreateAPIView of rest-framework, I am able to GET all the foreign key data. In the form that rest-framework provides, only the Title Content Votes are asked, I want the foreign key fields to be also asked as input. How do I achieve that? -
django update usage within for loop
Within Django, I can't update the database even though all is correct.(I assume :) ) Should I proceed with query get instead of filtering and use save instead of update ? In my database I have P_350 and P_450 columns. I am getting no error and also nothing is updated :) for thing_id, values_dict in groups.items(): for value_id, value_value in values_dict.items(): qs = RFP.objects.filter(id__in=thing_id) updates = {} if value_id == '350': if len(value_value) > 1: updates['P_350'] = value_value if value_id == '450': if len(value_value) > 1: updates['P_450'] = value_value if updates: qs.update(**updates) Here is the prints for the groups.items: 397 350 try_3 397 450 try_4 370 350 try_1 370 450 try_2 -
Django datatables and multiple rows
Good morning mates, I am trying to pass some values to a view in Django. I have a table (Datatables) with n values (id, name, lastname, etc), and I'd like to select some values and pass them (just the id) to the view and process it later. I can select multiple values and it works properly: $('#btnSelectedRows').on('click', function() { var tblData = table.rows('.selected').data(); var tmpData; $.each(tblData, function(i, val) { tmpData = tblData[i]; alert(tmpData); }); }) The problem comes when I try to "tell" the view what values I want to process, I don't know how to send this values to the view. Thanks a lot -
How to use saved object in class based views Django
In views.py I saved the form object in "buyer". And used "buyer" in receipt.html as {{ buyer.Invoice_number }}. It works fine. How do i do the same thing in Class based views views.py def ind(request): form = Sale() if request.method == 'POST': form = Sale(request.POST) if form.is_valid(): buyer = form.save(commit=True) return render(request,'app_one/receipt.html',{'buyer': buyer}) else: print("form is not vaalid") return render(request,'app_one/index1.html',{'form':form}) receipt.html receipt : {{ buyer.Invoice_number }} How do I do the above in class based views. This is what I tried : class ind(CreateView): model = Buyer form_class = Sale def get_success_url(self): return reverse('receipt', kwargs={'upform': self.model}) -
Did you forget to register or load this tag?
The following error is showing up even if I think there is no error. It worked very well but suddenly showing the following error "Invalid block tag on line 53: 'endblock'. Did you forget to register or load this tag?" here is the views.py code: def full_contacts(request, city_id): office = get_object_or_404(MainOffice, id=city_id) context = {'office': office} return render(request, 'contacts/full_office_contacts.html', context) here is the html file: {% block page %} <div class="container contacts-header"><h2>Филиалы и точки продаж</h2></div> <div class="container contacts-data-field"><p style="font-weight: 700; font-size: 12px;">Дата изменения: 07.11.2016 11:00</p></div> <div class="row"> <div class="container contacts-side-nav col-xl-2 col-lg-2 col-md-2"> {% extends 'base/sidebar.html' %} </div> <div class="contacts-main-table col-xl-9 col-lg-9 col-md-9"> <p style="font-weight: 750; font-size: 13px;">По всем вопросам, связанным с работой точек продаж <span style="font-style: italic;">«Узагросугурта»</span>, Вы можете узнать по телефону горячей линии 998 71 239 11 01 или по электронной почте <span style="font-style: italic;">info@agros.uz.</span></p> <hr> <h4 style="color: rgb(59, 151, 74); font-weight: bold;">{{ office.city }}ский областьной филиал</h4> <div class="jumbotron container"> <p><span style="font-size: 14px; font-weight: bold;">Адрес</span>: {{ office.address }}</p> <p><span style="font-size: 14px; font-weight: bold;">Телефон</span>: {{ office.phone_number }}</p> <p><span style="font-size: 14px; font-weight: bold;">E-mail</span>: {{ office.email }}</p> <p><span style="font-size: 14px; font-weight: bold;">Приемные дни</span>: Каждый день с 16.00 до 18.00</p> </div> <hr> <h5 style="color: rgb(59, 151, 74); font-weight: bold;">Подразделения</h5> {% for f … -
How to display my python code in a table on Django webpage?
I have written some code in Python that reads in two strings, removes the punctuation and then compares the words in them within a matrix table which it prints to the console. How do I convert the code to be utilised within the Django framework. I want to display a similar matrix on the web. I've already imported it into views. Please may someone point me in the right direction? I've been using django project and lynda to learn as I go along, My code is below: import string import pandas as pd pd.set_option('display.max_columns', None) with open('./arrayattempts/samp.txt', 'r') as file1: sampInput=file1.read().replace('\n', '') #print(sampInput) with open('./arrayattempts/ref.txt', 'r') as file2: refInput=file2.read().replace('\n', '') #print(refInput) sampArray = [word.strip(string.punctuation) for word in sampInput.split()] refArray = [word.strip(string.punctuation) for word in refInput.split()] out=pd.DataFrame(index=refArray,columns=sampArray) for i in range(0, out.shape[0]): for word in sampArray: out.ix[i,str(word)] = out.index[i].count(str(word)) print(out) -
Pass parameters to base.html from every single views
I have such a top nav-bar in the base.html <div class='section-topbar'> <div class="row"> <nav class="col-md-12"> <ul class="nav nav-tabs nav-justified"> {% for sec in sections %} {% if sec == current_section %} <li class="active"> <a href="/article/list/{{ current_section.id }}">{{ current_section.name }}</a> </li> {% else %} <li> <a href="/article/list/{{ sec.id }}">{{ sec.name }}</a> </li> {% endif %} {% endfor %} <br class="cbt"> </ul> </nav> </div> <!--first row--> </div> It is designed to present on every single page, and retrieve two contextual parameter sections and current_section from the view, context = {"page":page, "current_section": section, "sections": sections,} return render(request, "article/article_list.html", context) So I have to pass the extra parameters to templates from every views, Is it possible to pass them in one go and enable them globally? -
DRF - change field by url
I am new to Django Rest Framework. I have a Django model with a file field. class MyClass(models.Model): name = models.CharField(max_length=200, null=True, blank=True) file = models.FileField(blank=False, null=True, use_url=True) class MyClassSerializer(serializers.ModelSerializer): class Meta(object): model = MyClass exclude = [] class MyClassView(generics.RetrieveUpdateDestroyAPIView): queryset = MyClass.objects.all() serializer_class = MyClassSerializer Take two MyClass instances A & B. From my front-end, I'd like to send a PUT request to copy the file of Instance A to model B. Therefore I first make a GET requests which returns instance A with a file URL (ex: `{..., file: 'http://myserver.com/file.pdf')). I then send a PUT request to update instance B with that URL but I get the following error: The submitted data was not a file. Check the encoding type on the form. For performance reasons I don't want the file to be downloaded and uploaded again. Any idea how to serialize the filed field to make it accept an url of another file on my server ? -
How do you print Cart item and quantity in Python shell?
I am a newbie to django-import-export and I want to print(dataset.csv) for OrderResource. In my OrderResource I will make new column for every (Item)Variation and have quantity for that column, but I don't know what to write... I won't be using cart column but instead the new column I plan to create for every Variation with quantity as value. Right now in my django admin I have 'Item', 'Quantity', and 'Line item total'. Can you please help write the correct lines of code for OrderResource so that I can print quantity for each Variation. My Variation is [Variation: swiss, Variation: ham, Variation: cheddar] when I type Variations.objects.all() in Python shell. Is it possible to write something like swiss = fields.Field( column_name='swiss', attribute='Variation.objects.all()[0]', widget=ForeignKeyWidget(CartItem, field='quantity')) Cart/model class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) items = models.ManyToManyField(Variation, through=CartItem) total = models.DecimalField(max_digits=50, decimal_places=2, default=25.00) class CartItem(models.Model): cart = models.ForeignKey("Cart") item = models.ForeignKey(Variation) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) Order/model class Order(models.Model): status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created') cart = models.ForeignKey(Cart) user = models.ForeignKey(UserCheckout, null=True) when I print(database.csv) I get ,products.Variation.None, under Cart column orders/admin class OrderResource(resources.ModelResource): cart = fields.Field( column_name='cart', attribute='Cart', widget=ForeignKeyWidget(Cart, field='items')) class Meta: model = Order