Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the "path" mean in Django urls
When a read some new project on Django in one of urls.py files i find following code: from django.urls import path from . import views urlpatterns = [ path('buyers/embed/<int:id>/view', views.buyers_view), ] This is written in application that not used for now (Instead of this is used another application for buyers view). But i want to know what is this path. I can't find any information about it in documentation. Maybe this is some old style for url routing, or some mistakes. Thanks for any help! -
Django pass empty parameter
I'm trying to pass an empty parameter to render a template but I can not achieve this I do not know if the problem is in urls or views, I really appreciate a hand. Urls url(r'^hola/(\b[a-z\.-]+)$', views.hola, name='hola'), Views def hola(request, varr = ''): #val = val pregunta = Datos_usuario_DB.objects.all().order_by('-id').filter(activo="1")[:15] plantilla = {'': 'index.html', 'nosotros': 'nosotros.html'} return render(request, plantilla['%s' % varr], {'pregunta': pregunta}) When I accès to hola/ it the web site does not exist. -
Buttons with Django to choose items
I have 6 buttons which are options to buy something. You cannot make multiple choices but choose one and it automatically selects that item and reroutes you to checkout section. My question is, using Django, how do I embed the values of those buttons (ie. price, credits etc) into each button so they the ones used in the checkout. My initial method was that I created the items dynamically in Django.admin and instead of having a page in which you individually selected an item you had instead a checkboxes to select from whichever items I had created in the admin through a model (bono) I had created. However, I need the items to be hard coded into individual buttons rather than relying on Django.admin and the server. I've attached a sample html and pic showing the buttons and will add any other items upon request. I simply had no clue which items I should include: html: <div> <div class="row"> <!-- New set of columns, centered --> <div> <div class="row"> <div id="bonocredits3" class="col-xs-12 col-sm-12 col-md-4 col-lg-4 text-center bonoint" data-toggle="modal" data-target="#login-modal"> <a href="{% url 'home' %}"> <div class="circle" style="background: #0045ab" ><span style="font-weight:bold; font-size:60px;" >3</span><br> Credits</div> <div id="price">25€</div> <div id="savings"> {% trans 'You … -
use REST for DJango model instead of DB Access
I am looking to connect REST APIs to a DJango model. I want to do this because I have a database that is to work with Android, iOS and just regular HTML/CSS/Python. Instead of writing code to access a particular DB in Python directly (to support the CRUD functionalities), the goal is to map REST APIs to a Python Model instead. How can this be done? Below are some things that were found; however, is there a better approach? TIA http://www.django-rest-framework.org/api-guide/serializers/#modelserializer https://pypi.python.org/pypi/django-rest-models -
Django: get objects.all() with the related rows in another ManyToMany table
I have 3 models: The django normal User model Author model UserAuthor models which is considered as a many-to-many relationship between the previous two models, but with additional fields (is_follow, review) class Author(models.Model): name = models.CharField(max_length=50) class UserAuthor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='userauthors') is_follow = models.BooleanField(default=0) review = models.TextField(max_length=500, blank=True, null=True) My question is about how to get all the authors with a field inside each author to show that the authenticated user is following him or not. I know that I can use the related_name attribute, which returns the UserAuthor manager filtered by specific author, in some way to get it but how?! My trial is: class AuthorListView(ListView): model = Author def get_queryset(self): final_list = [] authors_list = list(Author.objects.all()) for author in authors_list: element = author.userauthors.filter(user=self.request.user) final_list.append(element) return final_list I don't like this solution for sure, but how to do it in a better way? -
How do you make a 1 on 1 (Like Twitter) messaging feature with django 1.11?
Would any of you know how to implement a 1on1 chat feature on Django 1.11? How would the views, models, templates .py look? Any recommendation's? Any python library for this kind of act? Thanks! -
Display datraframe into django template
I'm currently working on a stadistics portal with Django and i'm trying to display a Dataframe in my template with the next code: View.py: def tabla(request): engine = create_engine('postgresql://postgres:alphabeta@localhost:5432/escaladas') t='escalado 08/2017' sqltable = ps.read_sql_table(t,engine) sqltablehead = sqltable.head(n=10) table = sqltablehead.to_html(classes='table',index=False,escape=False) return render(request,'escalamiento.html',{'table':table}) I've tried display that table with a for on the template but doesn't show anything and writing {{table}} but gives me this https://ibb.co/bVpWw5 any ideas? -
Python Templates - Include/With - Passing parameters
So according to the Django docs, in python we can pass a parameter from one template to another. So at present I have a main html template (home.html) which my python program renders. It passes a username parameter as 'un'. To print this parameter in the home.html I do: {% if user_info %} {{ un }} {% endif %} //this works and prints the username Now I have another template that is included within the main.html. It is called user.html. I have included it as below wit using the 'with' statement to pass the parameter {% include 'sub_pages/user.html' with un=un %} The error I get: TemplateSyntaxError: expected token 'end of statement block', got 'with' Why is this happening? Also when and if the parameter does pass to the sub template do I print it in the same way as I'am printing on the main.html? -
django multiple search terms
I want to add all the columns in 1 algorithm for a search. If it is possible. Something like this: views.py def search_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if 'q_title' in request.GET and request.GET['q_title']: q = request.GET['q_title'] title = t.objects.filter(id__icontains=q_id, title__icontains=q_title, url__icontains=q_url) return render(request, 'search/results_table.html', {'tbl_name': table_name, 'details': title, 'query': q}) else: return HttpResponse("Please submit a search term!") results_table.html <strong> {{ tbl_name }}</strong> <p> You searched for: <strong>{{ query }}</strong></p> {% if details %} <p> Found {{ details|length }}</p> <div class="row"> <table class="table table-bordered sortable"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Url</th> </tr> </thead> <tbody> {% for lists in details %} <tr> <td>{{ lists.id }}</td> <td>{{ lists.title }}</td> <td><a href="{{ lists.url }}" target="_blank">{{ lists.url }}</a></td> </tr> {% endfor %} </tbody> </table> </div> {% else %} <p> No results found</p> {% endif %} {% endblock %} search_table.html {% if tbl_name %} <form action="/search/{{ tbl_name.id }}/results" method="GET"> {% endif %} <input type="text" name="q_id" placeholder="Id"> <input type="text" name="q_title" placeholder="Title"> <input type="text" name="q_url" placeholder="Url"> <input type="submit" value="Search"> </form> -
Django behind Apache transforms HEAD in GET
I'm managing an old django (1.4) application where the following is happening. In a function based view I receive a request, if it is a HEAD method then I just reply with an empty response if request.method == 'HEAD': return HttpResponse() This is just a simple method to check that the client (a script) has a correct configuration and the url is correct. Otherwise, if method is GET then proceed inside then view. This work in a local django debug server. When I deploy this behind Apache and wsgi, something is transforming my http HEAD method in GET. In the apache log I see that it correctly receives a HEAD method but then in my django application the same request is received as GET! Can Apache or wsgi be responsible for this? Where should I look for additional clues? -
Django Styling Issue - Can't get icons to display
I'm using a custom set of icons from a template from themeforest. I can't get them to display using Django and I'm not sure why. The styling is setup with static files, the rest of the site loads, and i assume it's to do with the styling linking to a bunch of .svg, .eot, .ttf, .woff files. I can include code if needed but I feel like there's a more simple solution to this. Cheers! And i'm using Canvas template, being single page app template. -
Getting the error 'Credentials' object has no attribute 'revoke'
I'm using Google Calendar OAuth2 login. Now once the user is successfully logged in, I'd like to revoke the credentials token on clicking a link. The official documentation here says that the code below revokes the token credentials.revoke(httplib2.Http()) However, I'm getting the error - 'Credentials' object has no attribute 'revoke' Could someone help figure this out? Thank you! -
How to change format of a field value in model serializer keeping the field name same in both display and create?
I have a model called Task with field delay which is a duration field. class Task: delay = models.DurationField(timedelta(seconds=0)) and a serializer as below. class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'delay') On creation of instance using serializer, i pass data such as {delay: 30} expecting seconds to be passed. Instance is created as expected. However on retrieval, I get below result. [ { "delay": "00:00:00.000060", }, { "delay": "00:00:00.000050", }, { "delay": "00:00:00.000060", } ] I am trying to get delay value in serializer in integer format only. For example: [ { "delay": 60, }, { "delay": 50, }, { "delay": 60 } ] I am not willing to change field name "delay" in either write or read serializer. How can I achieve the requirement ? -
OperationalError at /accounts/login/ attempt to write a readonly database
I have just setup my server and uploaded all my files for amy Django project. I am currently debugging all the errors it is giving me and I came across this one, which I have never seen before and can't seem to find very much on: OperationalError at /accounts/login/ attempt to write a readonly database I understand what it means, I just have no idea how to fix it nor do I know why it is happening. I am using a Digital Ocean droplet as my server. I had just gotten the homepage (login page) to work and upon logging in I came across this. Here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper return bound_func(*args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) ... ▶ Local vars … -
Ordering listview with get_queryset
Two models : Post and Author This view displays the last Post for each Author (author is a ForeignKey) I want to have these posts in a descending order, but it does not work. The template keeps displaying these in a ascending way. I try this following: views.py class LastestListView(ListView): context_object_name = 'posts' model = models.Post ordering = ['-date'] paginate_by = 10 def get_queryset(self): return self.model.objects.filter(pk__in= Post.objects.values('author__id').annotate( max_id=Max('id')).values('max_id')) or: class LastestListView(ListView): context_object_name = 'posts' model = models.Post paginate_by = 10 def get_queryset(self): return self.model.objects.filter(pk__in= Post.objects.order_by('-date').values('author__id').annotate( max_id=Max('id')).values('max_id')) -
How to display my form in template
I'm new to django and I've been following a tutorial to help me create my project. My problem is that I can't seem to display my from on my html page. line of code from my html file <form action="admin/signup/" method="post"> <div class="form-horizontal form-label-left"> {% csrf_token %} {% for field in signupForm %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <div class="ln_solid"></div> <div class="form-group"> <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-4"> <button class="btn btn-primary">Cancel</button> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </div> </form> my signup form class class SignUpForm(UserCreationForm): usertype = forms.CharField(max_length=10) userID = forms.CharField(label="User ID") class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'userID', 'usertype') and my signup page view def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.usertype = form.clean_data.get('usertype') user.profile.userID = form.clean_data.get('userID') user.save() else: form = SignUpForm() context = { 'signupForm' :form } return render(request, 'admin.html', context) any possible solutions and suggestions are appreciated, thanks! -
Unable to get base64 data in POST request
I'm having trouble while reading data from POST request. Request screenshot enter image description here It seems everything is fine from frontend but when I'm getting nothing when trying to read the request data on the backend. request.FILES <MultiValueDict: {}> request.POST <QueryDict: {}> request.body *** RawPostDataException: You cannot access body after reading from request's data stream I'm completely blank, any help would be appreciated. -
Django faceting sub-categories via foreign keys
I have a list of items that have a 'top category' and a 'middle category', eventually there will be a 'lower category' but not right now. For example Electronics > Laptops, respectively. I want to dynamically facet on this categories, so laptops will display under electronics etc. Any thoughts on how I can acheive this? Currenty I have the 'Top Categories' faceting correctly. models.py class mid_category(models.Model): class Meta: verbose_name_plural = 'Mid Categories' name = models.CharField(max_length=500) def __str__(self): return self.name class top_category(models.Model): class Meta: verbose_name_plural = 'Top Categories' name = models.CharField(max_length=500) mid_cat = models.ForeignKey(mid_category, null=True) def __str__(self): return self.name # Item class Product(models.Model): title = models.CharField(max_length=500, db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) retailer = models.CharField(max_length=255) image = models.CharField(max_length=1000) url = models.URLField(max_length=800, unique=True, default='') sku = models.BigIntegerField(default=0) barcode = models.BigIntegerField(default=0) featured = models.CharField(max_length=255, db_index=True, choices=FEATURED_CHOICES, default='NO') timestamp = models.DateTimeField(auto_now=True) top_cat = models.ForeignKey(top_category) mid_cat = models.ForeignKey(mid_category, null=True) def __str__(self): return self.title search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from decimal import Decimal from .models import Product, top_category class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='/home/wilkinj33/bargainforest/bargainforestenv/motorclass/templates/search/indexes/product_text.txt' ) title = indexes.EdgeNgramField(model_attr='title') retailer = indexes.CharField(model_attr='retailer', faceted=True) price = indexes.IntegerField(model_attr='price', faceted=True) barcode = indexes.CharField(model_attr='barcode') topCat = indexes.CharField(model_attr='top_cat', faceted=True) midCat … -
Django MySQL IntegrityError: ("Field 'created_at' doesn't have a default value")
I am new to Django. IntegrityError: (1364, "Field 'created_at' doesn't have a default value") occurred when I didn't write created_at for models I defined at models.py. Every time I face such error, I add created_at = models.DateTimeField(default=timezone.now, null=True) to models.py and then run makemigrations; migrate --fake. Is that OK? (I mean, does it follow Django best practice or not? ) When I was using Rails, I've never faced such issues. Also, I'd like to know why --fake option removes this error. version Django==1.11.5 mysqlclient==1.3.12 Python 3.6.1 Thanks in advance. -
How to use orderby based on condition in Django?
I have a model called DemoModel and i am querying it i.e; DemoModel.objects.all() I am fetching all the objects but i want to do order_by based on condition i.e; In my models there is a field called demo_field, if that field value is 'Testing' then it should be ordered using that condition DemoModel.objects.all().order_by(demo_field='Testing') Is there anything like this? or we have to create customized order_by? -
ForeignKey relashionship to geojson serializer
I have 2 models, lets call them Model1 and Model2. And I would like to add an image from Model2 as a field, like the featured_image property into the serialized output. But I can't pass in a property since it is not a field. Is there some elegant way of doing this? models.py class Model1(models.Model): model1 = models.CharField(max_length=200, null=True) point = PointField(null=True) slug = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return self.project def get_absolute_url(self): return reverse('model1-detail', kwargs={'slug': self.slug}) @property def featured_image(self): image = self.images.all() return image[0] class Model2(models.Model): model1 = models.ForeignKey(Model1, related_name='images') order = models.PositiveIntegerField(default=1) views.py JSONSerializer = serializers.get_serializer('geojson') json_serializer = JSONSerializer() with open('path/to/file.geojson', 'w') as out: model1 = Model1.objects.all() json_serializer.serialize(model1, geometry_field=('point'), fields=('point', 'model1', 'slug'), stream=out) I've tried writing a simple function that would return the featured_image. JSONSerializer = serializers.get_serializer('geojson') json_serializer = JSONSerializer() with open('path/to/file.geojson', 'w') as out: model1 = Model1.objects.all() def featured_image(): image = Model1.featured_image return image json_serializer.serialize(architecture, geometry_field=('point'), fields=('point', 'project', 'slug', featured_image), stream=out) I've tried fooling around with filters such as, but it return a wrong queryset. model1 = Model1.objects.all() image = model1.filter(images__order=1) model1 = list(model1) + list(image) -
Django custom Func
While tried to find solution for the Django ORM orderby exact i generated custom django Func: from django.db.models import Func class Position(Func): function = 'POSITION' template = "%(function)s(LOWER('%(substring)s') in LOWER(%(expressions)s))" def __init__(self, expression, substring): super(Position, self).__init__(expression, substring=substring) and it's work, but by comment @hynekcer "It crashes easily by ') in '') from myapp_suburb; drop ... expected that the name of the app is "myapp and autocommit is enabled. " The main trouble is: that extra data (substring) putted into the template without sqlescape. I could not found the django way solution. P.S. how this function work: class A(models.Model): title = models.CharField(max_length=30) data = ['Port 2', 'port 1', 'A port', 'Bport', 'Endport'] for title in data: A.objects.create(title=title) search = 'port' qs = A.objects.filter( title__icontains=search ).annotate( pos=Position('title', search) ).order_by('pos').values_list('title', flat=True) # result is # ['Port 2', 'port 1', 'Bport', 'A port', 'Endport'] -
page redirection in django views + reactjs
I am stucked in one Situation that i need to redirect page after user login but i have also used rest-auth for token authentication.Here is my django views.py: @ensure_csrf_cookie def loginform(request,LoginView): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user_data=User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password']) print (email," ",password) return render(request, 'inventory/index.html', {'email':email,'password':password}) return render(request, 'inventory/index.html', {}) And here is my login component (login.js): import React, { Component } from "react"; import ReactDOM from 'react-dom'; import DjangoCSRFToken from 'django-react-csrftoken'; import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap"; var formStyle={margin: '0 auto',maxWidth: '320px'} var loginStyle={padding: '60px 0'} class Login extends React.Component { constructor(props) { super(props); this.state = { email: "", password: "" }; } render() { return ( <div className="Login" style={loginStyle}> <form style={formStyle} method="post"> <DjangoCSRFToken/> <FormGroup controlId="email" bsSize="large"> <ControlLabel>Email</ControlLabel> <FormControl autoFocus type="email" name="email" /> </FormGroup> <FormGroup controlId="password" bsSize="large"> <ControlLabel>Password</ControlLabel> <FormControl type="password" name="password" /> </FormGroup> <Button block bsSize="large" type="submit" > Login </Button> </form> </div> ); } } ReactDOM.render(<Login/> , document.getElementById("login")); Now i need to Redirect on index page after user logged in. What should i do? -
Two ModelForms in one CreateView
This probably have no sense, but it's better to get advice how to implement this behavior properly. I have User model and two others (let it be A and B). Both A and B have ForeignKey to User. On User creation I also create A and B for this User: def save(self, *args, **kwargs): user_id = self.id super(User, self).save(*args, **kwargs) if user_id is None: as_A = A(user=self) as_A.save() as_B = B(user=self) as_B.save() The only required field in A and B is user = models.OneToOneField(User), others are optional. class A(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) x = models.CharField(max_length=100, blank=True) class B(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) y = models.CharField(max_length=100, blank=True) I want to provide two forms for registration: as A or as B. In registration form as A, customer should be able to set fields for A model entity related to User. Similar for B. This is my RegistrationForm: class RegistrationForm(forms.ModelForm): password = forms.CharField( strip=False, widget=forms.PasswordInput, ) confirm_password = forms.CharField( strip=False, widget=forms.PasswordInput ) class Meta: model = User fields = ['email', 'first_name', 'password'] def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError("Passwords are not same") return cleaned_data As you can see it contains only … -
django transfer variable between html's
Hi i am trying to create a search engine and i need to make the table id stay in the link. In my CrawledTables have all the tables with the id...and i need to pass that id into the var pk through the links...cause then i request to get that pk and use the pk to get the table name. and then use the table name to get the data inside the table i searched for...and make a search engine inside those table info. This is my views.py def search_form(request): return render(request, 'search/search.html') def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] name = Crawledtables.objects.filter(name__icontains=q) return render(request, 'search/results.html', {'name': name, 'query': q}) else: return HttpResponse('Please submit a search term.') def search_form_table(request): return render(request, 'search/search_table.html', {'tbl_nm': table_name}) def search_table(request, pk): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] table_name = Crawledtables.objects.get(id=pk) print table_name t = create_model(table_name.name) print t title = t.objects.filter(title__icontains=q) print title return render(request, 'search/results_table.html', {'tbl_name': table_name, 'details': title, 'query': q}) else: return HttpResponse("Please submit a search term!") this is my search/urls.py urlpatterns = [ url(r'^results$', views.search, name='search'), url(r'^$', views.search_form, name='form'), url(r'^(?P<pk>\d+)/$', views.search_form_table, name='table_search'), url(r'^(?P<pk>\d+)/results$', views.search_table, name='table_results'), ] this is my search.html <form action="/search/results" method="GET"> <input type="text" …