Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset after login in created login panel doesn't display in html
I have a little problem. I've create a login and registration site seperated from Admin Login. When I login to panel as for example John i have a choise to add new record via forms. After that I want on dashboard display the records created exacly and only by user John. Problem is that, if I wrote in my dashboard.html the code <h1>Strony www</h1> {% for website in website_list %} {{website.website}} {% endfor %} {% endif %} the html responde me only label Strony www and thats all. It's not displaying me records created by the users from dashboard panel. I have in my view def website(request): website_list = Website.objects.filter(user=request.user).order_by('-User') context = {'website_list:', website_list} return render(request, 'konto/dashboard.html', context=context) If I create the records using Django Admin Panel, the records are visible in dashboard. Where is a problem in my project? I want to say in every html file I using the code on the beggining {% if request.user.is_authenticated %} -
django filters and checked box in results
I have my filters working correctly, but I want to also filter on a checkbox that's in my result set, is this possible with Django filters? My filter.py is the following: class UserFilter(django_filters.FilterSet): class Meta: model = Employee fields = ['employeeusername', 'employeefirstname', 'employeelastname', 'statusid', 'positiondesc'] My search form is the following: <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> 3-4 User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Title {% render_field filter.form.positiondesc class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> In my result set I have the following: <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Title</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.positiondesc }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> … -
geo Django: get the neighbors of a house
i have a house model with these properties centerpoint = PointField(srid=0, null=True, blank=True) front_left = PointField(srid=0, null=True, blank=True) front_right = PointField(srid=0, null=True, blank=True) rear_left = PointField(srid=0, null=True, blank=True) rear_right = PointField(srid=0, null=True, blank=True) polygon = PolygonField(srid=0, null=True, blank=True) direction = FloatField(null=True, blank=True) # the direction this house faces, in degrees and i want to get the houses in front of a specific house... im having a hard time trying to use Distance and polygon__dwithin i need to get the ones that are touching and the ones that have relative direction of less than 160 degrees: for that i do: House.objects.filter(polygon__touches=house_instance.polygon, direction__lt=160) how can i modify this query to get the houses that are in front maximum one block and the ones that are one house away from my reference house? -
Stop coreapi displaying the admin api docs
I am currently documenting the API I have created for an app. I'm using the built in documentation system that comes with Django Rest Framework and coreapi (as described here). The problem I have is that when I visit the docs I see the admin API docs alongside my API docs. I've tried using the answer to this question: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } But the admin docs still show up. Is there a way to hide the admin docs? -
Saving Django model throws OperationalError: cannot start a transaction within a transaction
I'm seeing a weird error in a Django unittest where, on rare occasions, attempting to save a model instance will throw the exception: OperationalError: cannot start a transaction within a transaction What would cause this? The really odd thing is that this is happening in a loop like: for i in range(10): obj = MyModel(name='blah %i' % i) obj.save() and it'll get through several iterations before throwing the exception. Since it's non-deterministic, it's incredibly frustrating to diagnose, and I have no clear idea what's happening. Since I'm using Django's standard TransactionTestCase, I would have thought this error was impossible, since the TestCase wraps each test in an atomic() context manager to wrap all changes in a transaction. There should be nothing attempting to create another transaction. The only other thing I could think might effect this is that my model has a post_save signal handler, and that that might be someone breaking outside of the transaction, or otherwise interfering, but I'm not sure how to test it, since I can't reliably reproduce the error. -
django update record in database
I tried following code to update records in table but this creates new record instead of updating. Here is my code , thank you: view : class ReservationCancelView(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,mixins.UpdateModelMixin, viewsets.GenericViewSet): #Model = Reservation serializer_class = ReservationCSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): resid = self.request.POST.get('id') Res= Reservation.objects.get(id=resid) #Res.reservedplaces =F('reservedplaces ') - 1 #Res.save() return Res def post(self, request, token=None, format=None): resid = self.request.POST.get('id') travel_id = self.request.POST.get('travel_id') Res= Reservation.objects.get(id=resid) Res.reservedplaces =F('reservedplaces ') - 1 Res.travel_id = travel_id Res.save() serializer class ReservationCSerializer(serializers.ModelSerializer): user = Serializers.PrimaryKeyRelatedField(read_only=True,default=serializers.CurrentUserDefault()) class Meta: model = Reservation fields = ('all') urls.py router.register(r'cancelreservation', ReservationCancelView,'reservationcancel') -
How to use social-auth-app-django with Facebook JavaScript SDK
I wan't to use Facebook JavaScript SDK with Python Social Auth I'm using next authentication backend: AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', ) Firstly I find this example in django-social-auth(what was deprecated in favor of python-social-auth) and it seems like what I seek, but It doesn't work. FB.login() returns data like { status: 'connected', authResponse: { granted_scopes: '...', accessToken: '...', expiresIn:'...', signedRequest:'...', userID:'...' } } But PSA wan't to get data like /complete/facebook/?granted_scopes='...'&code='...'&state='...' Where state is parameter generated on backend for preventing CSRF. Am I missing something? -
Dynamically pull API data based on form field value in Wagtail/Django
I'm trying to create a form where users can search for a medical facility in a location using Django. The search results come from an API that displays countries, regions, cities, and the medical facilities within those locations. So far I have created the functions that pull in ALL of the data: import requests MAIN_URL = 'https://www.sample.com' API_KEY = 123456789 def get_countries(): response = requests.get('{}/GetCountryList?apikey={}'.format(MAIN_URL, API_KEY)) json_response = response.json() countries = json_response['GetCountryListResult'] return countries def get_regions(country): response = requests.get('{}/GetRegionList?countrycode={}&apikey={}'.format(MAIN_URL, country, API_KEY)) json_response = response.json() regions = json_response['GetRegionListResult'] return regions def get_cities(country, region): response = requests.get('{}/GetCityList?countrycode={}&regioncode={}&apikey={}'.format(MAIN_URL, country, region, API_KEY)) json_response = response.json() cities = json_response['GetCityListResult'] return cities def get_facilities(country, region, city): response = requests.get('{}/SearchByCity?city={}&regioncode={}&countrycode={}&apikey={}'.format(MAIN_URL, city, region, country, API_KEY)) json_response = response.json() facilities = json_response['GetFacilitiesByCityResult'] return facilities I have also created the view and passed these items through in context: class MedicalFacilitiesPage(Page, TranslatablePageMixin): def get_context(self, request): context = super(MedicalFacilitiesPage, self).get_context(request) context['countries'] = get_countries() context['regions'] = get_regions(country) context['cities'] = get_cities(country, region) context['facilities'] = get_facilities(country, region, city) return context The data is showing up in the select boxes when I do something like this: <select class="form-control searchOption" id="Country" name="Country"> <option value="">Select</option> {% for country in countries %} <option value="{{ country.CountryCode }}">{{ country.CountryName }}</option> {% … -
NoReverseMatch at /blog/ Using Django 2
Hello guys i am receiving this error : enter image description here this my main url urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] My blog/url.py app_name = 'blog' urlpatterns = [ path('',views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<int:post>',views.post_detail,name='post_detail'), ] view.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published',publish__year=year,publish__month=month,publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) list.html {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <p class="date">Published {{ post.publish }} by {{ post.author }}</p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% include "pagination.html" with page=page_obj %} {% endblock %} I don't know what is the problem. Need a help pl -
Syntax behind how as_view() delivers callable, DJANGO
I will keep this question short. Similar questions on S/O do not address what I am wondering about, and I have struggled to find an answer. When I point to a CBV in my urls.py, I use the as_view class method: ...MyView.as_view()... Looking at the actual script (django/django/views/generic/base.py), the as_view returns a function 'view' that is specified within the actual class method itself. How come it returns the function with this line: return view Why does it not have to specify: return view(request, *args, **kwargs) I tried this out myself. I went and created a FBV_1 that returned yet another FBV_2 (the view responsible for delivering all functionality), in this same manner: return fbv_2 It generated an error. I had to return fbv_2(request) to access it. Thank you in advance. Apologies for any idiomatic expression-errors, my Swedish sometimes gets the best of me. -
How can I save image from MS AD, into the field of django model?
I tried ContentFile and save() method from FieldFile in views.py, but in the model I'm using ImageField. It even works. But the Image saving with strange id like NameOfImage_gdicbHhvd.jpg. How can I save it normally? -
Trying to edit profile for two different user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displayed... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) I think there is something wrong with the way I pass data to student and teacher and the view can't differentiate between user types. -
Django "UPDATE `django_session`" killing performances
My Django client was very slow during MySQL queries. Doing a tcpdump on the MySQL server, I saw that the following SQL query "UPDATE `django_session` SET `session_data`" [...] seems very long. What is the simplest way to solve this problem ? Thank you. -
Django Wagtail wagtailcore_tags image TemplateSyntaxError
I am following this Tutorial from Wagtail in Images Section to build my blog, I am having this weird TemplateSyntax Error which shouldn't be there. Please help me This is my HTML code. I use image from wagtailcore_tags. <div class="container"> <h1>Blog</h1> <div class="card-columns"> {% for post in blogpages %} {% with post=post.specific %} <a href="{% pageurl post %}"> <div class="card"> {% with post.main_image as main_image %} {% if main_image %}{% image main_image fill-160x100 %}{% endif %} {% endwith %} <h5> {{ post.title }} </h3> <p> {{ post.date }}</p> </div> </a> {% endwith %} {% endfor %} </div> </div> This is my models.py class BlogPage(Page): body = RichTextField() date = models.DateField("Post date") def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('body', classname="full"), InlinePanel('gallery_images',label= "Gallery images"), ] class BlogPageGalleryImage(Orderable): page = ParentalKey(BlogPage, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] And, this is the error I am getting -
How to compare form, model and auth_User in Django
I have a idea to create something like a admin panel. In that panel the user (or admin as well) for example in my case will can add a field named "website". And in this moment I have a problem. I've create in myapp model Website: from django.db import models from django.contrib.auth.models import User class Website(models.Model): user = models.ForeignKey(User,related_name="website_user", on_delete=models.CASCADE) website = models.CharField(help_text="Podaj stronę wraz z http lub https",max_length=250,verbose_name='Strona www', unique=True) class Meta: verbose_name = 'Strona www' verbose_name_plural = 'Strony www' def __str__(self): return self.website after that I've create a form to display for the user when is loggin: from django import forms from django.contrib.auth.models import User from .models import Website class WebsiteForm(forms.ModelForm): class Meta: model = Website fields = ('website',) Next step was a creating view : from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from .forms import LoginForm, UserRegistrationForm, WebsiteForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Website ... @login_required def add_website(request): if request.method == 'POST': website_form = WebsiteForm(data=request.POST) if website_form.is_valid(): new_website = website_form.save(commit=False) new_website.post = add_website new_website.save() else: website_form = WebsiteForm() return render(request, 'konto/add_website.html', {'add_website': add_website, 'website_form': website_form}) and on the end I've create … -
In Django, how to add payments with fees to a freelance website?
I have a freelance website, written in Django. I need to implement a payment system: user should be able to pay to another user (it must be card transaction) and I have to receive some fee from each payment. How can I implement it? -
DataTables Refresh Django Ajax Data on CRUD Operations
I have a Django project with an Analytic model. This model is a list of analytics. It has a ForeignKeyField and a ManyToMany Field. The end goal is to have the user go to a URL where they can view a list of Analytics in a DataTable, create a new analytic, edit analytics, and delete analytics. Using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html, I accomplished all of these objectives in a regular Bootstrap HTML table (i.e. not in a DataTable). When I attempted to introduce a DataTable to the mix, I discovered that my DataTable was pulling from the HTML/DOM source, so it was not updating unless the page was refreshed. So I then realized that I need to either configure the DataTable to initially pull from HTML/DOM and then pull from AJAX, or I need to initially use Ajax as the source. It turns out, regular Django does not do a good job of serializing ManyToMany fields, so I opted to use DRF to serialize my Analytic model. This works to a degree: the JSON output looks decent, and the results show up in my DataTable. However, the data is still not updating when an Ajax call is made. In addition, DataTables … -
How to construct url suitable for django from html form action
I have django site which I can query with various combinations of parameters. I am trying to write a html form for selecting the various combinations like so : <form action="http://mydjangosite.com/summaryReports/" target="_blank"> <input type="radio" name="reportType" value="messageSummary" checked> messageSummary<br> <input type="radio" name="reportType" value="countSummary"> countSummary<br> <select name="period"> <option value="today">Today</option> <option value="yesterday">Yesterday</option> <option value="thisWeek">This Week</option> <option value="lastWeek">Last Week</option> <option value="thisMonth">This Month</option> <option value="lastMonth">Last Month</option> </select> <br> <input type="radio" name="reportFormat" value="html" checked> html<br> <input type="radio" name="reportFormat" value="pdf"> pdf<br> <input type="radio" name="reportFormat" value="csv"> csv<br> <input type="radio" name="reportFormat" value="email"> email<br> <input type="radio" name="reportFormat" value="debug"> debug<br> <input type="submit" value="Submit"> </form> When I press button the url generated is : mydjangosite.com/summaryReports/?reportType=messageSummary&period=today&reportFormat=html whereas what I require is : mydjangosite.com/summaryReports/messageSummary/today/html How to do it? Thanks in advance -
Difference between mongoengine and django-mongo-engine and pymongo
Can anyone explain me the difference between mongoengine and django-mongo-engine and pymongo. I am trying to connect to mongodb Database in Django2.0 and python3.6 -
Django oscar sandbox editing or django oscar documentaion
Is it okay to edit the existing django-oscar sandbox project as my project or is it better to follow the django-oscar documentation? -
Tango with Django 1.9 on Django 2.0 - "list indices must be integers or slices, not str"
I am, probably stupidly, attempting to go through Tango with Django 1.9 on newly released Django 2.0. I am up to chapter 6 and am getting the following error. The error pertains to my views.py file (below) with the lines, context_dict['pages'] = pages context_dict['category'] = category seemingly the culprits. Has the way in which variables are assigned to dictionaries changed in Django 2.0 or is this a Python issue? Can provide code from all other application files. Views.py from django.shortcuts import render from rango.models import Category, Page def index(request): category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories':category_list} return render(request, 'rango/index.html', context=context_dict) def about(request): return render(request, 'rango/about.html') def show_category(request, category_name_slug): context_dict = [] try: category = Category.objects.get(slug=category_name_slug) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: context_dict['category'] = None context_dict['pages'] = None return render(request, 'rango/category.html', context_dict) Models.py from django.db import models from django.contrib import admin from django.template.defaultfilters import slugify # Create your models here. class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category,self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) title = models.CharField(max_length=128) url = models.URLField() views = … -
CSRF verification failed. Request aborted. Django 2.0
def order_view(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): return HttpResponseRedirect('Order Submitted') else: form = OrderForm() return render_to_response('home/order.html', {'form': form}) order_view function in views.py <form class="form form-table" method="post"> {% csrf_token %} {{ form|crispy }} <input class="btn br-green" type="submit" value="Submit"/> </form> There is still a CSRF error in it. Have tried most of the solution but they are not working.Have tried adding RequestContext(request) as well. -
Use Django with MongoDB
I have a large mongo database with documents and i want to make Django website that is going to be a client to this mongo database but it can only filter (aggregate) and view information from database without any edit/update operations. I don't want to put other web site data (users' data, comments, other information) to mongo db. I'm new to django framework and i wonder if it is better to connect mongodb and django using, for example, mongoengine and use two databases (one for the web site data, and the second one for external documents in mongodb) or use pymongo inside django to fetch data from external db and somehow transform it to djungo models? -
Get variables from server(django) and use in javascript
I'm new in django. I want to use the variables return from my python code, to create a map of the input city.(realise the request and response between server and client) But it does work in showing the map. (I use {{Latitude}} in html and get the right number.) Here is my python code: def searchMap(request): latitude =40 longitude=50 return render(request,'WebPage1.html,{'Latitude':latitude,'Longitude':longitude}) And my HTML code is like : <!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } #floating-panel { position: absolute; top: 10px; left: 25%; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; text-align: center; font-family: 'Roboto','sans-serif'; line-height: 30px; padding-left: 10px; } </style> </head> <body> <div id="map"></div> <div id="floating-panel"> <form method="POST" action="/searchMap/"> {% csrf_token %} <input name="city" type="text"> <input type="submit" value="Geocode" onclick="myMap()"> </form> </div> <p>{{Latitude}}</p> <script> var lat={{Latitude}}; var lng={{Longitude}}; var map; function myMap() { map = new google.maps.Map(document.getElementById('map'), { center: { lat:lat, lng:lng }, zoom: 8 }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key="API KEY"&callback=myMap"> </script> </body> </html> Thanks for kindly reply! -
Django autocomplete from json
I'm trying to add some autocomplete field in Django Admin (Django 2.0.1). I managed to get it to work (both with the autocomplete included in Django and with Select2) because in those cases I loaded the dropdown options from a ForeignKey field. Now I need to have autocomplete on a simple CharField but the choices need to be taken from a remote API that return a json response. I can decide how to structure the json response. Any way to do this? The returned json responde doesn't represent objects of model, just simple text options.