Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect user to personal dashboard page after successful login
I am trying to redirect my user to his/her dashboard url after login: urls: (2 seperate apps) name = 'user' urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), ] name = 'register' urlpatterns = [ path('<slug>/dashboard/', DashboardView.as_view(), name='dashboard'), ] I have made a CustomLoginView to handle the custom succes url of the login. views (users app) class CustomLoginView(LoginView): def get_success_url(self, *args, **kwargs): return redirect('register:dashboard', kwargs={"slug": Bedrijf.slug}, Bedrijf=Bedrijf), Now I am getting the following error: Reverse for 'dashboard' with keyword arguments '{'kwargs': {'slug': <django.db.models.query_utils.DeferredAttribute object at 0x040A5970>}}' not found. 1 pattern(s) tried: ['(?P[^/]+)/dashboard/$'] I am guessing this is because the login is not yet successful and the query cannot get the slug for the logged in user to put use it in the url. Is this correct and does anyone have any suggestions to fix this? Or the used query is returning all of the slug fields in the database for every user and is therefore not capable to parse it right. Do I then need to pass a user=request.user or something? P.S. I am using Allauth to handle the authentication -
No module named 'requests' But it is showing in pip3 list
If I try to import requests then it is showing No module named 'requests'. If i try pip3 list then it is showing. pytz (2020.1) requests (2.24.0) rsa (4.6) setuptools (39.2.0) six (1.15.0) sqlparse (0.3.1) uritemplate (3.0.1) urllib3 (1.25.9) virtualenv (15.1.0) -
collectstaic command fails gives me post-processing error
While deploying my django-app to heroku I get this error .I disabled collectstatic and it pushed but when I went to the site it wasn't working.I tried a lot of things but nothing seems to work Post-processing 'vendors/owl-carousel/assets/owl.carousel.css' failed! Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect raise processed whitenoise.storage.MissingFileError: The file 'vendors/owl-carousel/assets/owl.video.play.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f580a2b32e8>. The CSS file 'vendors/owl-carousel/assets/owl.carousel.css' references a file which could not be found: vendors/owl-carousel/assets/owl.video.play.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. my settings.py looks like this """ Django settings for personal_portfolio project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import django_heroku import os # Build paths inside … -
django + table2: issue in view to load table
I am trying to redirect a user to table on a click of button. Little background: the user input a value in a search bar, infos show up and there is link to click on that guides the user to another page containing info related to this value. My issue is in the structure of the view of this page containing the additional infos. the code look like this: @method_decorator(login_required, name='dispatch') class Supplier_items(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): query = request.GET.get('search_res', None) if query and request.method == 'GET': queryset = supplier.objects.all(supplier = query) table = supplier_items_table(queryset) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("report_supplier_items.{}".format(export_format)) return render(request, 'Supplier_items.html', {'table':table}) else: return Response('Supplier.html') and the table look like this: class supplier_items_table(tables.Table): reference = tables.Column(gettext_lazy("item"),localize= True) stock_reel = tables.Column(gettext_lazy("stock on hand"),localize= True) en_cours_de_reception = tables.Column(gettext_lazy("on order"),localize= True) class Meta: model = Item fields = ('reference', 'demand_30_jours', 'stock_reel', 'en_cours_de_reception') template_name = "django_tables2/bootstrap4.html" Everytime, 'supplier.html' is returned meaning that it didnt work. I am confused about what is happening, can anyone see what I cannot? -
Django Forms: How to make form.fields by Model.QuerySet in dynamic?
I need to generate Django forms.Form object with filds not from Model.fields (Database Table Columns names), but by records in Model.Table. I have table Model in models.py: class MntClasses(models.Model): type = models.CharField(max_length=2, blank=True, null=True) class_subtype = models.CharField(max_length=45, blank=True, null=True) text = models.CharField(max_length=45, blank=True, null=True) explanation = models.CharField(max_length=45, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) views.py # Form generate class Form_classes(forms.Form): def __int__(self, *args, **kwargs,): super(Form_classes, self).__init__(*args, **kwargs) print("some") for fld_ in args: self.fields[fld_.name] = forms.BooleanField(label=fld_.text) #Main def page_Category_Main(request, post): db_table = MntClasses form_fld = db_table.objects.all() ''' This QuerySet 20 records returned of <MntClasses: MntClasses object (0-19)> type. QuerySet Filds Names: 'name','type','expalnation', 'text' ''': form_ = Form_classes(*form_fld) exit_ = { 'form': form_, } return render(request, template_name="category.html", context=exit_) It raise TypeError init() takes from 1 to 12 positional arguments but 20 were given So, i have no idea what does it mean this code taken from were: Auto-generate form fields for a Form in django: def __int__(self, *args, **kwargs,): super(Form_classes, self).__init__(*args, **kwargs) What is this "*args", how to use it? How can i generate Form.fields by QureySet form_fld.name in that case? -
Django | Error using class form-control in views field
When wanting to assign class to the fields (code_station and name_station) in the views, it returns an error. Instead if I apply class in forms there is no problem. What's going on? Thank you. Error: 'code_station'.widget.attrs.update({'class': 'form-control'}), AttributeError: 'str' object has no attribute 'widget' File: views.py: class StationUpdateView(LoginRequiredMixin,UpdateView): template_name = "station/update_station.html" model = Station fields = [ 'code_station'.widget.attrs.update({'class': 'form-control'}), 'name_station'.widget.attrs.update({'class': 'form-control'}), ] success_url = '/station/' login_url = reverse_lazy('users_app:user-login') -
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.