Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is the meaning of BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
I am a beginner to Django. currently I have installed my Django project on my PC. when I saw setup in settings.py file. its really difficult to understand the python codes, especially this one "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))" what is the actual meaning of this code. pardon for my english. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -
Taking index.html template from already built vue.js app as a Django template using multiple nginx config files
When requested to example.com, from my backend, nginx should return rendered index.html from one nginx config file, and when requested to another, api.example.com, nginx should take configurations from another nginx config file. Another problem is based on first one: I should somehow take that index.html from my vue frontend. Did someone encounter this issue? Some solutions on the net don't seem to work! -
How to create a One-To-Many relationship and display it as a dynamic form in Django?
I am trying to build a form for a resume website where there is an option for users to add their education history/histories. I want to allow users to complete 4 fields for each school they attended. Initially they should only be able to see those first 4 fields and should have a button to add more education histories. Clicking on the button should display an extra 4 fields for the user to complete for the other school they attended. What is the best way I can implement this in models.py, views.py and forms.py? It is a one-to-many relationship in the sense that one user can have multiple education histories. How can I implement this such that the admin can neatly see the education histories, and the user can dynamically add extra fields by clicking the add button? P.S. I am using Django Wizard-Forms to have a large form spread over multiple pages. Any help would be greatly appreciated :) Thank you -
vuejs accessing django context variable's get_absolute_url
I am integrating django with Vue.js. With Vuejs, I am just building a webpage for my blog's category and it will render django's blog post lists with URL(so that it can be clickable) I have difficulty getting url of context variable objects coming from django(now I don't use DRF but just using axios and jsonresponse to get context model's instances(I mean context variables) What is the most efficient way to put URL when using axios + vue +django? Thanks! -
My choice for positiveinteger model does not appear in the restframework interface and therefore cannot be updated
I'm developing a backend with the django rest api. I have the same problem with my advertise model except for my user model. My choice linked to positiveintegerfielder is not displayed in restframework for post method.I'm doing an action like in serializer.py, whose photo I shared to display. When I do this, it is not displayed in restframework and I cannot use the post method. Thank you very much in advance serializer.py## from user.models import User from rest_auth.serializers import * class ChoicesSerializerField(serializers.SerializerMethodField): def init(self, choices, **kwargs): self._choices = choices super(ChoicesSerializerField, self).init(**kwargs) def to_representation(self, value): # sample: 'get_XXXX_display' method_name = 'get_{field_name}_display'.format(field_name=self.field_name) # retrieve instance method method = getattr(value, method_name) # finally use instance method to return result of get_XXXX_display() return method() def to_internal_value(self, data): return getattr(self._choices, data) class UserSerializer(serializers.ModelSerializer): gender = ChoicesSerializerField(choices=User.gender) class Meta: model = User fields = ('gender',) view.py## from rest_framework.viewsets import ModelViewSet from user.serializer import UserSerializer from .models import * from rest_framework import permissions from rest_framework.generics import CreateAPIView, ListAPIView, GenericAPIView, get_object_or_404 class CreateUserView(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Custom CSS not applying for Bootstrap
newbie in Bootstrap here. I am trying to make a simple blog in my Django project and it seems that my custom css does not work alongside bootstrap's. Overwriting it by using style tag on every line is tedious. The order in which I loaded the css and js is: Bootstrap CSS My own CSS JQuery, Popper.js and Bootstrap.js Then, in the navigation bar html I noticed that the href does not work, even with the correct link: <li class="dropdown-item" href="#"><a>See all</a></li> So, naturally I tried to put href into the a tag like so: <li class="dropdown-item"><a class="nav-link" href="{% url 'blog_index'%}">See all </a></li> With that, the text "See all" becomes white and is not visible anymore since the background is also white. So as a work-around I changed style directly into this tag. Changing it by altering the nav-link class in the css file doesn't do anything. Also my html page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Title</title> {% load static %} <!-- Bootstrap CSS --> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <!--Custom CSS--> <link rel="stylesheet" type="text/css" href="{% static '/css/base.css' %}"> <!-- JQuery, Popper.js, Bootstrap js scripts --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> <script … -
Django - Handle KeyError event (API)
I make a little weather app with Python/Django. I took actual weather data from openweathermap.org. I set up my project, create search field to search a city and connect with API and everything works fine.. until you type a wrong letter (e.g. chikago). Then I get a KeyError. Here you can see my code views.py from django.shortcuts import render import requests def index(request): API_KEY = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=123456789' city = request.POST.get('search_input') res = requests.get(API_KEY.format(city)).json() if city == '': city = 'Berlin' city_weather = { 'city': res['name'], 'temperature': res['main']['temp'], 'description': res['weather'][0]['description'], 'icon': res['weather'][0]['icon'] } return render(request, 'weather/index.html', {'data': city_weather}) If I look up the inspector I see a error 404 so I tried to add a handle404 in the base urls.py but it doesnt catch the internal error. Also the openweathermap response with a error 404 message: res {'cod': '404', 'message': 'city not found'}. Is there a way I can handle the error message into a div? -
i cant send an input value as Django template tag URL parameter
hi i'm trying to send the value of input id="inp_pin" as a parameter in a url tag but is not working. the rest of the code is working fine, and if i change 'inp_pin' by other parameter it works fine. but not with inp_pin. Any ideas please ??? {% for key_j, value in ex_conf.items %} <tr><td>&nbsp Ext # &nbsp</td><td>&nbsp {{ value.ext }}</td><td></td></tr> <tr><td>&nbsp Name &nbsp</td><td>&nbsp {{ value.name }}</td><td></td></tr> <tr><td>&nbsp Email &nbsp</td><td>&nbsp {{ value.email }}</td><td></td></tr> <tr><td>&nbsp PIN &nbsp</td><td>&nbsp {{ value.pin }}</td> <td> <input type="number" id="inp_pin" min="1000" max="9999" placeholder="4 digit PIN"><a> </a> <a class="btn btn-primary" href="{% url 'ext_pin' value.ext key_j inp_pin %}">New PIN</a> </td></tr> <tr><td>&nbsp DND &nbsp</td><td>&nbsp {{ ex_ES_dnd }}</td> <td> {% if ex_ES_dnd == 'Activated' %} <a class="btn btn-primary" href="{% url 'ext_dnd' value.ext key_j ex_ES_dnd %}">OFF</a> {% endif %} {% if ex_ES_dnd == 'Deactivated' %} <a class="btn btn-danger" href="{% url 'ext_dnd' value.ext key_j ex_ES_dnd %}">ON</a> {% endif %} </td></tr> {% endfor %} -
I have this error in Django regarding a failed test
It says that 1 test has failed in the tests.py file in the HomeTests. I am doing a product application. Here is my tests.py file. from django.urls import reverse from django.urls import resolve from django.test import TestCase from .views import home, product_topics from .models import Product class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_view_contains_link_to_topics_page(self): product_topics_url = reverse('product_topics', kwargs={'pk': self.product.pk}) self.assertContains(self.response, 'href="{0}"'.format(product_topics_url)) class ProductTopicsTests(TestCase): def setUp(self): Product.objects.create(name='Light Bulb', description='Conserver energy',price=25.99,qtyOnHand=25) def test_product_topics_view_success_status_code(self): url = reverse('product_topics', kwargs={'pk': 1}) response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_product_topics_view_not_found_status_code(self): url = reverse('product_topics', kwargs={'pk': 99}) response = self.client.get(url) self.assertEquals(response.status_code, 404) def test_product_topics_url_resolves_board_topics_view(self): view = resolve('/products/1/') self.assertEquals(view.func, product_topics) The AttributeError says that HomeTests has no attribute Product. and here is my views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Product # Create your views here. def home(request): products = Product.objects.all() return render(request, 'home.html', {'products': products}) def product_topics(request, pk): product = get_object_or_404(Product, pk=pk) return render(request, 'topics.html', {'product': product}) In the urls.py, I have the following. from django.conf.urls import url from django.contrib import admin from inventories import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^products/(?P<pk>\d+)/$', views.product_topics, name='product_topics'), url(r'^admin/', admin.site.urls), ] I would like … -
How to pass multiple QuerySet values into filter()
I got 3 models, one with auctions, second with watchlist, third with users class Auctions(models.Model): lot = models.CharField(max_length=64) owner = models.CharField(max_length=64) url = models.CharField(max_length=256, blank = True) startBid = models.IntegerField() description = models.CharField(max_length=64) category = models.CharField(max_length=64, blank = True) class User(AbstractUser): pass class Watchlist(models.Model): user = models.CharField(max_length=64) watchlist = models.CharField(max_length=64, blank = True) Views: def addToWatchlist(request, id): print(id, "ID") user = request.user watchlist = Watchlist.objects.filter(user = user, watchlist = id) data = list(watchlist) if data == []: createWatchList = Watchlist( user = request.user, watchlist = id ) createWatchList.save() else: watchlist.delete() return redirect('listing', id=id) def watchlist(request): id = Watchlist.objects.filter(user = request.user) auctions = Auctions.objects.filter(id = id) return render(request, "auctions/watchlist.html", { "auctions": auctions }) I receive an error "ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing." Can someone explain how to pass multiple QuerySet values into filter() As a result, I need all auctions, that's a match the watchlist Thank you! -
Django - DeleteView; how to pass argument (slug) for success_url
I am using DeleteView to delete posts from a forum group. I would like to define success_url in way so user will be redirected to post list within the same group where deleted post was. The issue is that I don't know how to pass group name (slug) from _confirm_delete.html page to DeleteView in views.py delete button --> urls.py urlpatterns=[path('delete/<slug>/<pk>/',views.DeleteMyPost.as_view(),name='delete')] views.py class DeleteMyPost(DeleteView): model = models.MyPost def get_success_url(self,*args,**kwargs): return reverse_lazy('desired_url_name',kwargs={'slug':self.kwargs.get('slug')}) mypost_confirm_delete.html <form method="post"> {% csrf_token %} <input type="submit" value="Delete"> </form> It doesn't work right now - slug is not being passed to DeleteView. How an I fix it? Thanks, Pawel -
select2 add options dynamically and save it in the respective module
I'm new to web app development. Using select2 for multi-select and then tried tagging, to add options dynamically and save it so that next time the new option is available for selection. But not getting where I'm wrong. Please help me out. In HTML Without dynamic add option $('#id_student').select2(); For dynamic tag option $('#id_student').select2({ tags: true, tokenSeparators: [' '], createTag: function (params) { var term = $.trim(params.term); if (params.term === '') { return null; } var newOption = new Option(term.text, term.id, true, true); $('#id_student').append(newOption); } }); Not working at all...Please suggest -
Django: 'LanguageForm' object has no attribute 'Cleaned_data'
I am trying to create an new Language object via LanguageForm where I am accessing form data via cleaned_data dictionary. Creating the object using Django shell. My model.py: class Language(models.Model): name = models.CharField(max_length=100) lang_code = models.CharField(max_length=100, unique=True, verbose_name= 'Language Code') slug = models.SlugField(max_length=100,unique=True) mime = models.CharField(max_length=100, help_text='MIME to use when sending snippet as file.') file_extension = models.CharField(max_length=10) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.name forms.py from django import forms from django.core.exceptions import ValidationError from .models import Language class LanguageForm(forms.Form): name = forms.CharField(max_length=100) lang_code = forms.CharField() slug = forms.SlugField() mime = forms.CharField() created_on = forms.DateTimeField() updated_on = forms.DateTimeField() def clean_name(self): name = self.cleaned_data['name'] if name == 'djangobin' or name == 'DJANGOBIN': raise ValidationError("name can't be {}.".format(name)) return name def clean_slug(self): return self.cleaned_data['slug'].lower() def clean(self): cleaned_data = super(LanguageForm,self).clean() slug = cleaned_data.get('slug') mime = cleaned_data.get('mime') if slug == mime: raise ValidationError("SLUG and MIME shouldn't be same.") return cleaned_data def save(self): new_lang = Language.objects.create( name=self.cleaned_data['name'], lang_code=self.cleaned_data['lang_code'], slug=self.cleaned_data['slug'], mime=self.cleaned_data['mime'], created_on=self.cleaned_data['created_on'], updated_on=self.cleaned_data['updated_on'], ) return new_lang Django shell where I have created my new object to save data into database >>> data = { ... 'name':'Go', ... 'lang_code': 'go', ... 'slug': 'go', ... 'mime': 'text/x-gosrc', ... 'created_on': datetime.now(), ... } >>> f = LanguageForm(data) … -
How can I remove the upper array list from the list of dictonaries?
I've a list of dictionaries and want to get rid of the external list array. Take into consideration the array below, [ { "stores": [ { "id": 1, "storeName": "Green Mart", "lat": 12.905616, "lon": 77.610101, "offer": [ { "offer": "Get 10% OFF on Fruits & Vegetables" } ] }, ] } ] My serializer looks like, class storesSerializer(serializers.ModelSerializer): offer = StoreOffersSerializer(read_only=True, many=True) storeName = serializers.CharField(source="store_name") lat = serializers.FloatField(source="latitude") lon = serializers.FloatField(source="longitude") class Meta: model = Vendors fields = ('id', 'storeName', 'lat', 'lon', 'offer') class CategoryStoreSerializer(serializers.ModelSerializer): stores = storesSerializer(read_only=True, many=True) class Meta: model = CategoryStore fields = ('stores',) and the view definition is, if request.method == 'POST': c = CategoryStore.objects.filter(category=request.data['cat_id']) serializer = CategoryStoreSerializer(c, many=True) return Response(serializer.data) -
Failed to push django app on Heroku because it collects ALL modules
I’m trying to deploy my django app to Heroku. However, when I push heroku master, it collects all my modules, no matter the fact that most of them are Not in my requirements file. Therefore, it fails when it gets to pywin. This is what I have in requirements: certifi==2020.6.20 chardet==3.0.4 dj-database-url==0.5.0 Django==2.2.15 gunicorn==20.0.4 idna==2.10 psycopg2==2.8.5 pytz==2020.1 requests==2.24.0 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 This is the message I get after pushing: Enumerating objects: 101, done. Counting objects: 100% (101/101), done. Delta compression using up to 8 threads Compressing objects: 100% (84/84), done. Writing objects: 100% (101/101), 933.04 KiB | 4.22 MiB/s, done. Total 101 (delta 31), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.11 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.10 remote: Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) remote: Collecting async-generator==1.10 remote: Downloading async_generator-1.10-py3-none-any.whl (18 kB) remote: Collecting atomicwrites==1.4.0 remote: Downloading atomicwrites-1.4.0-py2.py3-none-any.whl (6.8 kB) remote: Collecting attrs==19.3.0 remote: Downloading attrs-19.3.0-py2.py3-none-any.whl (39 kB) remote: Collecting backcall==0.1.0 remote: Downloading backcall-0.1.0.tar.gz (9.7 kB) remote: Collecting bleach==3.1.5 remote: Downloading bleach-3.1.5-py2.py3-none-any.whl (151 kB) remote: Collecting blis==0.4.1 remote: Downloading blis-0.4.1-cp36-cp36m-manylinux1_x86_64.whl … -
Parallel Huey Tasks
I am trying to run some long computation through Huey async tasks which are being called through a DRF View. The sequential runs of such tasks are working fine. However when I start the first task, and simultaneously start the other one as well, the second task runs into errors with some postgres issues like Query matching doesn't exist, also the first task which had started to compute also ends into erroneous condition due to module not found. PS- There is no code issues as these tasks work perfectly well sequentially. Any suggestions so as to what I might be missing or how to debug this issue? -
I'm working on a Django blog, The error is
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/detail/python Raised by: main.views.blog_detail No Blog matches the given query. It says that the error is raised by "main.views.blog_detail", What am I missing or what could be the erroe? This is my urls.py: from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('' , views.test , name='test_view'), path('blog/', views.blog_list, name='blog_list'), path('<slug:category_slug>' , views.blog_list , name='blog_list'), path('detail/<slug:blog_slug>' , views.blog_detail , name='blog_detail'), ] This is my views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Blog,BlogCategory from django.shortcuts import get_object_or_404 # Create your views here. def test(request): template = 'base.html' # context = {'product_list':productlist, 'category_list':categorylist, 'category':category} return render(request, template) def blog_list(request, category_slug=None): category = None bloglist = BlogCategory.objects.all() if category_slug: category = get_object_or_404(BlogCategory,slug=category_slug) bloglist = bloglist.filter(category=category) template = 'main/blog.html' context = {'blog_list':bloglist} return render(request, template, context) def blog_detail(request, blog_slug): print(blog_slug) blogdetail = get_object_or_404(Blog, slug=blog_slug) template = 'Main/blog_details.html' context = {'blog_detail':blogdetail} return render(request, template, context) This is my models.py file: from django.db import models from datetime import datetime from django.utils.text import slugify # Create your models here. class Blog(models.Model): blog_title = models.CharField(max_length=200) blog_content = models.TextField() blog_published = models.DateTimeField('date published', default=datetime.now) blog_category = models.ForeignKey('BlogCategory', on_delete=models.SET_NULL, null=True) … -
Update variables passed with django include tag
I have a for loop that contains an include tag like the following: {% for thing in things %} {% block example %} {% include 'myapp/example.html' with thing=thing %} {% endblock %} {% endfor %} I expected that the html in example.html would get rendered with each thing within things but it only gets rendered with the first thing object. Is there a way to pass each of the thing objects within things to example.html? -
django polymorphic add as OneToOneField
I wanted to change database schema from : class Item(PolymorphicModel): class Module(PolymorphicModel): to: class Item(PolymorphicModel): class Module(Item): Since this introduced so many other problems and wanted to keep Module Polymorphic, i decided to keep Item as a OneToOneField: class Module(PolymorphicModel): item = models.OneToOneField(Item, on_delete=models.CASCADE, null=True, blank=True) Now i want to create Items for every existing entry in Module, so i wrote a management command like : class Command(BaseCommand): help = 'Create share items' def handle(self, *args, **kwargs): self.create_share_items() @transaction.atomic def create_share_items(self): for module in Module.objects.all(): share_item = Item.objects.create(id=module.id) share_item.polymorphic_ctype = ContentType.objects.get_for_model(Module) share_item.__class__ = Module share_item.save() module.item = share_item module.save() After running this command , it runs but when i try to access Items, returns error: polymorphic.models.PolymorphicTypeInvalid: ContentType 19 for <class 'exzaacademy.els.models.Module'> #86487203-02fa-45b8-bdf9-d866792e7f39 does not point to a subclass! My target is to make Module a type of Item, so when i run Item.objects.all() , it should also return Module instances. -
JsonResponse Returns NOT serializable error in Django view
I am trying to pass data to the template in Json format. JsonResponse returns an error TypeError: Object of type method is not JSON serializable Here is the code view that causes the error: if request.method == 'POST': ... SOME CODE HERE .... elif request.method == 'GET' and request.is_ajax(): df = pd.read_csv(project.base_file, encoding='ISO-8859-1') cols = df.keys return JsonResponse({'features': cols, }, status=200) else: form = mForm(project_id=pk) The Json Data should be processed in the following Ajax Code: $(document).ready(function(){ var id_number =$("#projectID").text(); $("#btnSelect").click(function(){ $.ajax({ url: '', method: 'GET', data: { project_id: id_number, }, success: function(response){ $("#id_features").text(response.features) } }); }); }); -
Why am i getting NoReserverMatch at /?
I am new to Python and trying to develop a simple blog application.I am getting NoReverseMatch at / error while trying canonical url. Tried different solution to fix this but i am getting help for django versions which are old. Please help me with a solution for updated Django version. ERROR: Reverse for 'post_details' with arguments '(2020, '08', '15', 'indian-software-industry')' not found. 1 pattern(s) tried: ['blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P\[-\w]+)/$'] This is my urls.py from django.contrib import admin from django.urls import path,re_path from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.post_list_view), re_path(r'^blog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>\[-\w]+)/$', views.post_detail_view,name='post_details'), This is my models.py (used for reverse url) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_details',args=[self.publish.year,self.publish.strftime('%m'), self.publish.strftime('%d'),self.slug]) This is my post_list.html {%extends 'blog/base.html'%} {%block title_block%} Sentamil's Blog Home Page{%endblock%} {%block content%} <h1>My Blog</h1> {%for post in post_list%} <a href="{{post.get_absolute_url}}"> <h2>{{post.title}}</h2></a> <p id='date'>Published on {{post.publish}} by {{post.author|title}}</p> {{post.body|truncatewords:30|linebreaks}} {%endfor%} {%endblock%} -
What changes i need to make before pushing my django app to github?
I have a django app and for production i'll use a dedicated linux server.So before moving to production i want to know what all changes i need to make it a production ready so that i can upload it to github and with only required server changes will able to set it up on server. The only thing that i had done from my side is making all absolute path to relative path. Django documentations looks very complicated to me . It would be really helpful if i could get a checklist that i can follow to make it to production ready state. Thanks in Advance -
UnicodeDecodeError: 'utf-8'. Django. Cannot run server [duplicate]
I have tried explicitly and implicitly specifying IP addresses. I changed my account to English letters. I went to related topics, nothing helped. Reinstalling python didn't help. D:\Django\myfirst>python manage.py runserver 127.0.0.1:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 15, 2020 - 20:38:21 Django version 3.1, using settings 'myfirst.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\threading .py", line 932, in _bootstrap_inner self.run() File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\threading .py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\commands\runserver.py", line 139, in inner_run run(self.addr, int(self.port), handler, File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\socketser ver.py", line 452, in __init__ self.server_bind() File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\s imple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\http\serv er.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Tairlan\AppData\Local\Programs\Python\Python38-32\lib\socket.py ", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd2 in position 0: invalid continuation byte -
Wagtail: How to use view_restrictions in ModelAdmin to filter query set?
I am trying to manage the access to certain PageModel pages in the Wagtail admin via Privat Pages and the associated PageViewRestriction model, using this post as a reference: class MyAdmin(ModelAdmin): model = MyPage [ ... ] def get_queryset(self, request): qs = super().get_queryset(request) user = request.user [ ... ] elif user.is_client: return qs.filter( Q(view_restrictions__restriction_type='groups', view_restrictions__groups__in=user.groups.all()) ) return None Nothing returns so I checked in the shell: qs = MyPage.objects.all() qs.first().get_view_restrictions() >>> <QuerySet [<PageViewRestriction: PageViewRestriction object (2)>]> qs.first().get_view_restrictions().first().groups.all() >>> <QuerySet [<Group: MyGroup>]> So the restrictions are set but trying the same query as above returns an empty qs: my_user.groups.all() >>> <QuerySet [<Group: MyGroup>] qs.filter(Q(view_restrictions__restriction_type='groups', view_restrictions__groups__in=my_user.groups.all())) >>> <PageQuerySet []> Something that confuses me further is the fact that the view_restrictions field on the MyPage instance is empty but the get_view_restrictions method returns the expected object. qs.first().specific.view_restrictions.all() >>> <QuerySet []> qs.first().specific.get_view_restrictions() >>> <QuerySet [<PageViewRestriction: PageViewRestriction object (2)>]> Can anyone shed some light on this? -
how to render row query with django_table2
hope you will find this message well. I am new to django and trying to understand all functionality (its hard for me!). Hope somebody can point me to right direction with small query below? I've been trying all morning to render 'row' sql query with django_table2 module but I can not make it work. #view.py def test(request): template = 'test.html' with connection.cursor() as cursor: cursor.execute('select * from EMC') arrays = cursor.fetchall() context = { 'arrays': arrays } return render(request, template, context) #test.html {% extends "base.html" %} {% load render_table from django_tables2 %} {% block content %} <h2> Test page</h2> <p class="text-justify font-italic"> {% render_table arrays %} </p> {% endblock %} I presume I am missing to setup table.py but not sure how to form it? Anybody can point me to right direction? With above I am getting following error: Expected table or queryset, not tuple... Thank you in advance... ZDZ