Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error when Django startup with runserver command
I have an django app that include sklearn, pandas and numpy libraries. I can run it without virtualenv however when I run it inside virtualenv I get his error. I am using Python3.8 on Ubuntu. I just want to use virtualenv to manage my packages easily. I re-installed packages in the virtualenv with PyCharm. My error include references to the joblib library too. I cannot find any solution: Matching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/suat/Belgeler/github/turnusol/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module … -
django.core.exceptions.ImproperlyConfigured Error
My main URLS.PY File from django.contrib import admin from django.urls import path,include from django.views.generic import RedirectView from catalog import urls from Demo import urls urlpatterns = [ path('admin/', admin.site.urls), path('catalog/',include('catalog.urls')), path('demo/',include('Demo.urls')), path('',RedirectView.as_view(url='catalog/')), ] when Iam run my work get following error Exception in thread django-main-thread: Traceback (most recent call last): File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\urls\resolvers.py", line 586, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "E:\MyWorks\django_projects\locallib\lib\site-packages\django\urls\resolvers.py", line 593, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'catalog.urls' from 'E:\MyWorks\django_projects\catalog\urls.py'>' does not appear to have any patterns in it. If you see valid patterns … -
django ckeditor SVG portions of page dissapearing
I am using Django CKEditorm3.5 with Django 2.2. I am writing a very crude CMS that will allow interns to edit content of selected pages. This is my code: settings.py CKEDITOR_UPLOAD_PATH = 'content/ckeditor/' CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', }, 'default': { 'toolbar': 'full', 'height': 300, 'width': 300, }, } models.py class WebPage(models.Model): breadcrumb = models.CharField(blank=False, null=False, max_length=128, unique=True) content = RichTextField() creator = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) is_published = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.breadcrumb views.py def test_page(request): from django.template import Context, Template from django.http import HttpResponse from webpage.models import WebPage page = WebPage.objects.get(breadcrumb='Main/Menu1') content = page.content return render(request, 'test_page.html', { 'content': content}) test_page.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> {% autoescape off %} {{ content }} {% endautoescape %} </div> {% endblock %} Sample content of WebPage Model This bit of HTML: <div class="d-flex flex-wrap text-center"> <!-- Counter Pie Chart --> <div class="g-mr-40 g-mb-20 g-mb-0--xl"> <div class="js-pie g-color-purple g-mb-5" data-circles-value="54" data-circles-max-value="100" data-circles-bg-color="#d3b6c6" data-circles-fg-color= "#9b6bcc" data-circles-radius="30" data-circles-stroke-width="3" data-circles-additional-text="%" data-circles-duration="2000" data-circles-scroll-animate="true" data-circles-font-size="14" id="hs-pie-1"> <div class="circles-wrp" style="position: relative; display: inline-block;"> <div class="circles-text" style= "position: absolute; top: 0px; left: 0px; text-align: center; width: 100%; font-size: 14px; height: 60px; … -
Button in the base template to switch between locations
I have a base.html template which lets me choose between shops- I want to use this setting to save a product in relationship to it's location. I already implemented a middleware that gives me a list of all shops for a logged in user and the current shop (is this a smart way?): from .models import Shop class ActiveShopMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): shops = Shop.objects.filter(user=request.user.id) request.current_shop = shops[0] request.shops = shops response = self.get_response(request) return response I create products using a form, and I want to add the current shop information to that. I want to be able to switch between shops like in the screenshot: I tried this in base template: {% if user.is_authenticated %} {% if request.num_shops > 1 %} <div class="dropdown" aria-labelledby="userMenu"> <button class="btn btn-primary dropdown-toggle mr-2" type="button" id="dropdownMenu0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">shop: {{ request.current_shop }}</button> <form method="post" action=""> {% csrf_token %} <div class="dropdown-menu" aria-labelledby="dropdownMenu1"> {% for shop in request.shops %} <input type="hidden" name="tessst" value="{{ shop.id }}"> <a class="dropdown-item" href="/">{{ shop }}</a> {% endfor %} </form> </div> </div> {% endif %} I want to get the shop_id variable in my index view: def index(request): shop_id = request.POST["tessst"] Is this an ok approach? … -
Rendering cyrillic fonts from html page to pdf in django project
I am trying to render an hmtl page in russian to pdf. Everything works fine except for russian fonts. The resulting pdf page shows either black squares or trash. That's my html to pdf page: {% load static %} <style> @font-face { font-family: 'Open Sans'; src: url({% static 'webfonts/OpenSans-regular.ttf' %})format('truetype'); } body{ font-family: 'Open Sans'; } </style> <body> олывоалыовалоылвоа <br> олыолваолыоалывоалы </body> That,s my project tree: -project/static/webfonts/OpenSans-Regular.ttf Please, help -
Show message in class based view in Django?
In function based view I can display some warning messages when the 2 passwords don’t match with each other or the email's already existed. But how can I do it in class based view. Noted that I use the custom form widgets. how I do it in function based view def register(request): if request.method == "POST": form = RegisterForm(request.POST) email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] # some other fields if User.objects.filter(email=email).exists(): messages.info(request, 'Email is already taken') return redirect('register') elif password1 != password2: messages.warning(request, 'Passwords are not matched!') return redirect('register') elif form.is_valid(): form.save() messages.success(request, 'Your account has created! You can log in now') return redirect('login') how I write in forms.py class form(UserCreationForm): class Meta(UserCreationForm): model = User fields = ['email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(form, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'Email Address', 'type': 'email', 'name': 'email-register', 'class': 'form-control mb-3 ml-3', }) self.fields['password1'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'New Password', 'type': 'password', 'name': 'password1-register', 'class': 'form-control mb-3 ml-3', }) self.fields['password2'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'Re-enter New Password', 'type': 'password', 'name': 'password2-register', 'class': 'form-control mb-3 ml-3', }) how I write in template {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} … -
How to use Django with Docker on Windows
I have a Django application running on AWS-Beanstalk server (using EC-2 Linux instance) This runs fine and trouble-free, but I am working on a Windows system and would like to work under the same system requirements to prevent problems. Now AWS offers a Linux instance with docker, but I couldn't do much with the documentation and have problems setting up my Windows 10 system with docker for aws. Does anyone know a tutorial or can help me in any other way? Jaron -
query list of attributes and values separately
I need to return attributes and values separately of particular product variant and my model looks like the following models.py class Product(models.Model): name = models.CharField(max_length=128) slug = models.SlugField() class Attribute(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) has_variants = models.BooleanField(default=False) def __str__(self): return self.name class VariantAttribute(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) value = models.CharField(max_length=100) def __str__(self): return self.value class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") variant = models.ManyToManyField(VariantAttribute, related_name="productvariants") name = models.CharField(max_length=255, blank=True) I need to return in such way variants: [ {'id': 1, name: 'variant 1', variant: [ { 'attribute': {'id': 1, 'name': 'Size'}, 'values': [ {'id':1, 'name': 'Medium', 'value': 'M'} ] }, { 'attribute': {'id': 1, 'name': 'Size'}, 'values': [ {'id':2, 'name': 'Large', 'value': 'L'} ] } ] } ] if i do product_variant = ProductVariant.objects.filter(product=product) product_variant[0].variant.all() then it lists all the variant attributes but I want to return attributes and values provided to that attribute separately like in above format without using rest framework. -
Override save method in Django not working
My goal with the following code is to create an athlete object and override the save method to automatically set the category for a given athlete based on the born_date. The Category class will be inherited in other models too. The list within the class serves as validation purposes for the save method and the tuples for choice fields (used in other models). Although everything seems right, I ran some test in the shell and the code is saving whatever born_date is inputed. Why is that the case? Can someone shed some light on the problem? Thanks from django.db import models from datetime import datetime class Category: list_categories = [ 'u12', 'u13', 'u14', 'u15', 'u16', 'u17', 'u18', 'u19', 'u20', 'u21', ] CATEGORIES = [ ('U12', 'u12'), ('U13', 'u13'), ('U14', 'u14'), ('U15', 'u15'), ('U17', 'u17'), ('U19', 'u19'), ('U21', 'u21'), ] class Athlete(models.Model, Category): name = models.CharField(max_length=120) born_date = models.DateField() category = models.CharField(max_length=3) def save(self, *args, **kwargs): year_now = datetime.date.today().year year_born_obj = datetime.datetime.strptime(self.data_nascimento, "%Y-%m-%d") self.category = 'u{}'.format(year_now - year_born_obj.year) if self.category in Category.list_categories: try: super(Athlete, self).save(*args, **kwargs) except ValueError: print('Category does not exist. Check born date') def __str__(self): return self.name Here is the shell output: >>> a1 = Athlete.objects.create(nome='Foo', born_date='1990-02-05') >>> a1.category … -
Where to put custom made functions in Django?
In my models.py I have this class. import time class Ticket(models.Model): username = models.CharField(max_length=50) booking_time = time.time() expired = models.BooleanField(default=False) I want the expired bool to turn to true if 1 hour has been passed since the booking_time but I don't have any idea where should I check for the same thing(I was thinking to make the function in views.py but views are only called when we go to a certain URL, in my case I want to check it every hour). -
not able to acess my product information on card
** settings.py** ''' MEDIA_ROOT=os.path.join(BASE_DIR,'/media/ecom/') MEDIA_URL='/media/' ''' from django.shortcuts import render from .models import Product from math import ceil Create your views here. from django.http import HttpResponse def index(request): products = Product.objects.all() print(products) n = len(products) nSlides = n//4 + ceil((n/4)-(n//4)) params = {'no_of_slides':nSlides, 'range': range(1,nSlides),'product': products} return render(request, 'ecom/index.html', params) def about(request): return render(request, 'ecom/about.html') def contact(request): return HttpResponse("We are at contact") def tracker(request): return HttpResponse("We are at tracker") def search(request): return HttpResponse("We are at search") def productView(request): return HttpResponse("We are at product view") def checkout(request): return HttpResponse("We are at checkout") ''' -
Django rest deferred task
I want to write an API method that will do a specific task (e.g task/create) But this task takes a long time. I want the user to run the task (task/create) and then polled the service until it was executed (task/status). As soon as the task is completed, the user can request the result (e.g task/result). What tools can I use to implement such a pattern? Can I put the task on a separate thread? -
How to get category anme from BelongsTomany Relation in Django?
I am trying to creating breadcrumbs in Django but i am unable to display data by category wise, I want to display subchild category data on product view page, please let me know how i can do that. and i have ManyToMany relation of SubChildCategory with Product model. Here is my models.py file... class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) class SubChildCategory(models.Model): subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category') name=models.CharField(max_length=50, default=None) slug=models.SlugField(unique=True, max_length=50) class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category') here is my views.py file.. def productview(request, slug): product = Product.objects.get(slug=slug) template_name='mainpage/product-view.html' context={'product':product} return render(request, template_name, context) here is my product-view.html file..I am trying to display data here in this format..Home/Category(Name)/SubCategory(Name)/SubchildCategory(Name), and where Name is Category, Subchildcategory, SubChildCategory fields name.. <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'mainpage:homepage' %}">home</a></li> <li class="breadcrumb-item active" aria-current="page">Category Name / Subcategory Name/SubChildCategory Name/Product name</li> </ol> -
Django Ajax div not reloading/disappearing after posting comment
I am trying to resolve the problem for few days. I want to post the comment without refreshing page. The problem is the div in which comments are is not reloading or disappearing after hitting post button. It depends on how i "catch" it: when I use the id like: $('#comments').append('<p>' + data.comment.content + '</p><small>' + data.comment.author + '/' + data.comment.date_of_create + '</small>'); it is not reloading and if i use class it disappears. When i refresh the page, comment is being add properly. This is my code below. views.py class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): if request.method == 'POST': new_comment = Comment.objects.create( author = self.request.user, post = self.object, content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.instance.post = self.get_object() form.save() return super(PostDetailView, self).form_valid(form) def get_success_url(self): return reverse('post_detail', kwargs={'slug': self.object.slug}) comments.js $(document).ready(function(){ $("#commentBtn").click(function(){ var serializedData = $("#commentForm").serialize(); $.ajax({ url: $("commentForm").data('url'), data: serializedData, type: 'post', dataType: 'json', success: function(data){ console.log(data); $('#comments').append('<p>' + data.comment.content + '</p><small>' + data.comment.author … -
Modify login view to use simple JWT
I am using Django REST framework with SimpleJWT. I am trying to let me user log in form use simpleJWT authentication. Roughly, I think my log in view should: Retrieve the username/password from the form, send a POST request to the TokenObtainPairView.as_view() view, collect the returned token and store it in local storage. How do I do that in my django code? Currently I only have a standard log in form that does not use JWT. Settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',),} My project urls: urlpatterns = [ path('admin/', admin.site.urls), path("", include("my_api.urls")), path('api-auth/', include('rest_framework.urls')), path('api/token', TokenObtainPairView.as_view()), path('api/token/refresh', TokenRefreshView.as_view()), ] This is the user login view. I think I should make a POST request to the 'api/token' with my username and password as my payload, get the returned token, and store it in local storage, but I dont know how to do that in Django. def login_view(request): if request.method == "POST": # Attempt to sign user in email = request.POST["email"] password = request.POST["password"] user = User.objects.get(email=email) if user.check_password(password): username = user.username user = authenticate(username=username, password=password) print("Login successful") login(request, user) return HttpResponseRedirect(reverse("welcome"))``` -
GDPR compliance for a web app (Vue.js, Django, Heroku)
I have build a web application using Django, Vue.js and deployed it on Heroku. It is a web application made for a big charity where you can win prizes by donating to the charity. The following information is collected: Name Username Email Password Which is pretty basic, I guess. The reason no payment information is stored is because, upon clicking 'Donate', the user is redirected to JustGiving (implemented the JustGiving API) where they enter their payment information and such and are then redirected back to our website. A few emails are sent: An email when somebody wins a prize An email if you are the winner of the prize An email when a new prize draw is taking place A receipt of your donation This will be the first time I properly publish a web application so wanted to ask what steps I need to ensure to make sure the web app is legal. I know I have to probably have a 'cookies' alert and a section where users choose to receive emails or not. What other steps must I take to make sure I am not breaking any rules? -
ModuleNotFoundError: No module named 'survey_responses'
After changing a couple of things in my Django app (unfortunately, I forgot what exactly I've changed) I'm seeing this weird error message: (hr-djang) ➜ hr_djang git:(data-isolation) ✗ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'survey_responses' survey_responses if one of my installed apps in the Django project. I've commented out all mentioned all references to survey_responses except for the one in installed_apps but the error doesn't change. I'm a bit lost on what could cause this … -
Python Django - Internal Error ProgrammingError relation does not exist
This might probably be a duplicated question, but I can't find a post to answer my questions yet. Any post that is similar to this may help is appreciated. I tried to host my Django app using heroku.com git add . git commit -m "(commit_name)" git push heroku master When I tried to test the website (/questions/1), the website shows an Error 500 (Internal Error). First it shows a ProgrammingError: relation does not exist. After that I did $ heroku run python manage.py migrate try to solve the problem. The original error disappeared, but instead this happened: 2020-08-29T11:05:42.668070+00:00 app[web.1]: Internal Server Error: /questions/1 2020-08-29T11:05:42.668070+00:00 app[web.1]: 2020-08-29T11:05:42.668070+00:00 app[web.1]: DoesNotExist at /questions/1 2020-08-29T11:05:42.668071+00:00 app[web.1]: Question matching query does not exist. Settings.py: import django_heroku from pathlib import Path import os #--------------------(ommited)--------------------# # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myweb.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myweb.wsgi.application' # … -
Django - changing value from db in place and save it to db
I have table on my page like that: And models.py like that: models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) category = models.IntegerField() offset_pages = models.IntegerField() read_pages = models.IntegerField() total_pages = models.IntegerField() book_path = models.CharField(max_length=200, default='') status = models.BooleanField(default=False) def __str__(self): return f'{self.category} | {self.title} | {self.author}' I would like to click on value in "Read pages" column (404 in this case) and then modify it and save to database. The only way I see it for now is to make an html input there with assigned value of 404, then change it within an input and submit it with additional button. I know how to do so, but it seems to me like there has to be way better solution. Does any onemay present me another solution? -
Creating a navigation menu custom tag in Django
Please accept my apology if this is answered somewhere in the Django docs or stackoverflow, but I couldn't track it down myself! I'm creating a portfolio app - mainly as a project to learn Django, but also potentially as a gift to a relative to promote their illustration work and save them some money. I'm creating a custom tag to render a main navigation menu. I've tested django-treebeard and django-mptt, but they feel excessive for a project on this scale, so I'm relying on ForeignKey relationships in my Page model to define parent-child pages. At the moment, I can render a list of all parent pages and all child pages, but of course I want to filter child pages by their parent. Would really appreciate any guidance, whether I do the filter in the templatetags file or in the template itself. My menu_tags.py (in 'Templatetags' dir for the app): from django import template from django.views.generic import ListView from pages.models import Page register = template.Library() @register.inclusion_tag('menus/main_menu.html') def main_menu(): parent = Page.objects.filter(is_parent=True) child = Page.objects.filter(is_parent=False) return { 'parent': parent, 'child': child, } And my template: {% for parent in parent %} <p><strong>{{ parent.title }}</strong></p> {% for children in children %} <p>{{ children.title … -
The page refreshes even when using Ajax
The page refreshes even when using Ajax, I also use csrf_exempt, but the problem was not solved.all java script work fine , all the console.log are displayed but the page was refreshed. i also use a uncompressed jquery file and then after i use jquery cdn link. but problem not solve. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="home"), path('save/', views.save_data, name="save"), ] views.py def save_data(request): # detail = Detail.objects.all() if request.method == "POST": form = DetailForm(request.POST) if form.is_valid(): name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] print(name) print(email) print(password) dt = Detail(name=name, email=email, password=password) dt.save() return JsonResponse({'status':'save'}) else: return JsonResponse({'status':0}) html file --------------------------- ------------------------------- <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" id="submitbutton" value="Save" class="btn btn-success"> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384- JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> AJAX <script> $('#submitbutton').click(function(e){ console.log('btn clicked') let nm = $('#nameinput').val() let em = $('#emailinput').val() let pa = $('#passwordinput').val() let csr = $('input[name=csrfmiddlewaretoken]').val() if (nm == ""){ console.log('enter name') }else if(em == ""){ console.log('enter email') }else if(pa == ""){ console.log('enter password') }else{ mydata = {name:nm, email:em, password:pa, csrfmiddlewaretoken:csr}; $.ajax({ url : "{% url 'save' %}", method : "POST", data : mydata, encode: true, success : function(data){ console.log(data.status); console.log(data); }, }) … -
Redirecting from the login page to signup page back to login page with the same parameters in the url in django
I may not have been descriptive in the title but what I want is that for example When a new user opens a page where login is required --> he is redirected to login page with the login url having a next parameter to the previous page.But as he is a new user he chooses to signup by clicking on a link on the login page which takes him to signup page ,now this is where the problem comes - The signup url gets no parameter and once user signs up he is automatically redirected to login page and after he logs in he is redirected to the index page instead of the page where login was required. This is my login view for my customer user model: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") next = request.POST['next'] if next != '': login_url = reverse('login') query_string = urlencode({'next': next}) url = '{}?{}'.format(login_url, query_string) # create the url return redirect(url) else: return redirect('login') else: return render(request,"login.html") And this is my … -
What is name of this block in Django?
i want to create similar block in Django admin panel , but what is this name ? i want to create similar section and group class , AUTHENTICATION AND AUTHORIZATION ,My_site and etc ... -
nested resolvers in Ariadne
When querying for list of products I need to show the product information along with variation. I mean i want products query to return something like this { "data": { "product": { "id": "1", "name": "Polo Shirt", "productType": { "name": "clothing" }, "category": { "name": "Men's" }, "variants": [ { "id": "1", "name": "S", "variant": [ { "attribute": { "name": "Size" }, "values": [ { "name": "S" } ] } ], }, { "id": "2", "name": "XL", "attributes": [ { "attribute": { "name": "Size" }, "values": [ { "name": "XL" } ] } ], }, ] } } } For such result, I have my schema for products as following type Query { products: [Product] } type Product implements Node { id: ID productType: ProductType! name: String! slug: String! description: String! category: Category! attributes: [SelectedAttribute] variants: [ProductVariant] articleNumber: String barcode: String } type SelectedAttribute { attribute: Attribute values: [AttributeValue] } type Attribute implements Node { id: ID name: String } type AttributeValue implements Node { id: ID name: String } type ProductVariant implements Node { id: ID! name: String! sku: String! product: Product! variant: [VariantAttributes] } type VariantAttributes { attribute: Attribute values: VariantAttribute } type VariantAttribute implements Node { id: … -
NOT NULL constraint failed: social_media_app_blogcomment.user_id
I'm making this comment system for my blogs.. I already made the model, the ModelForm and the view to display the comments and the blog. I'm just really confused how to save the comments related to a specific blog. I tried to save the comments with a view but I face an IntegrityError. A little help would be appreciated. Here's my views.py: @login_required #View to show the blogs and comments related to it def readblog(request, blog_pk): Blog = get_object_or_404(blog, pk=blog_pk) return render(request, 'social_media/readblog.html', {'Blog':Blog,'Form':CommentForm()}) @login_required #view to save the comments def commentblog(request,blog_pk): Blog = get_object_or_404(blog,pk=blog_pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Form = form.save(commit=False) Form.Blog = Blog Form.save() return redirect('usersfeed') Urls.py: path('commentblog/<int:blog_pk>', views.commentblog, name='commentblog'), path('readblog/<int:blog_pk>', views.readblog, name='readblog'), HTML Page to write and save comments (along with the blog): {{ Blog.title }} <br> {{ Blog.text }} <br> {% if Blog.image %} <img src="{{ Blog.image.url }}" alt=""> {% endif %} <br> <form action="{% url 'commentblog' Blog.id %}" method="post"> {% csrf_token %} {{ Form.as_p }} <button type="submit">Comment!</button> </form> {% for i in Blog.BlogComment.all %} {{ i.comment }} <b>user:{{ i.user }}</b> <br> {% endfor %}