Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
index.html file Style background img url for python Django
style="background-image:url({% static 'images/home_slider.jpg' %})" Please see above code and correct me if i am wrong to writing this for loading background img in django using static load method because it is showing error in vs code.. please help me out -
how to see the table in my database after creating and migrating models in django
i tried to connect my sql cloud cluster to visual studio code and connected in settings.py as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':'aras', 'USER':'arasuser', 'PASSWORD':'**********', 'HOST':'mysql-numbers-0.cloudclusters.net', 'connection':'connect1', } } Later, i created a model and run migrations . but yet i am unable to see the table in my database. am i connecting it right ? -
How to add a text editor like Stack Overflow's to my website
I want to make it so users can submit articles to my website, that includes a text area with styling. It would be good if you can give me the code. I'm working with Django. Right now I have only text area. -
how to set the movies name in dropdown box by default in django?
i am trying to post the review followed by movies name by using the foreign key it gives the drop box of movies instead of setting it automatically i don't know what to do please help me views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Movies from django.contrib.auth.models import User class MoviesListView(ListView): model = Movies template_name = 'blog/home_movies.html' ordering = ['-date_released'] context_object_name = 'movies' paginate_by = 10 class MoviesDetailListView(ListView): model = Post template_name = 'blog/post_list.html' context_object_name = 'posts' paginate_by = 10 def get_queryset(self): user = get_object_or_404(Movies, name=self.kwargs.get('name')) return Post.objects.filter(name=user).order_by('-date_posted') class PostListView(ListView): model = Post template_name = 'blog/home_movies.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 class UserPostListView(ListView): model = Post template_name = 'blog/user_post.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post context_object_name = 'posts' class PostCreateView(LoginRequiredMixin,CreateView): model = Post context_object_name = 'posts' fields = ['title', 'content','name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content', 'name'] def form_valid(self, form): form.instance.author = self.request.user … -
How to connect one Django project user in other Django project?
When we see Google apps icon in a browser there we are many different google apps, I don't have an idea are they all deployed on same server or different. when we use anyone we don't need authentication again, I have created multiple Django project and deployed them on different servers, is there any way to connect all projects user, so that when he authenticate in one server no need to authenticate on a different server. -
django problems with css
having trouble linking css to my django project, right now im just a beginner and learning how to use the framework. i dont really know whats important and what's not so i'll put the full code. i checked some tutorials and did what they did but it still didn't work i tried some stuff from the documentation and still no luck. Can someone help me out. heres the settings.py file """ Django settings for ecommerce_site project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wfudi*u9lch97-&tq*sq+_5fi0u&e3khi@iy^(tzg9znkdql)s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store' ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] 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 = 'ecommerce_site.urls' TEMPLATES … -
Running django on a server
Im trying to run a django project through docker-compose while working on a Ubuntu 18.04 linux server at myIP that I've connected to using putty. I cant use the local host as this will run the project but I can't see it due to port forwarding. When I try to use the IP and port for my space on the server ($ python manage.py runserver myIP:myport) it seems to default to 0.0.0.0:myport and gives me an error telling me that there is something already running on it. Im working on the server on myIP, how can I get django to use this server IP amd port? Thanks in advance -
django - DecimalField act as float field with default value 0.00?
i have code below total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) for this total, i checked in admin its value is 0.0 and type(total) showing as Float instead of Decimal and if assign value Decimal('13.00') it show error like TypeError: unsupported operand type(s) for +=: 'float' and 'decimal.Decimal' why default=0.00 consider as float and giving this error? i am debuging below code @receiver(post_save, sender=CartEntry) def update_media_cart_on_create(sender, instance, **kwargs): line_cost = instance.media.price instance.cart.total += line_cost instance.cart.count += 1 instance.cart.updated = timezone.now() instance.cart.save() -
how to use graypy with django
I am working on a project that uses graylog server to logging, in settings.py I have the following: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'users/debug.log'), }, 'graypy': { 'level': 'WARNING', 'class': 'graypy.GELFUDPHandler', 'host': 'localhost', 'port': 12201, }, }, 'root': { 'handlers': ['graypy', 'console', 'file',], 'level': 'WARNING', }, 'loggers': { 'django.request': { 'handlers': ['graypy'], 'level': 'ERROR', 'propagate': True, }, }, } also, I made the input in graylog server and test it successfully with a python simple script, when I create a looger in my views.py, logs appear in file and console but the don't appear in graylog! please help me with this issue! my views.py: logger = logging.getLogger(__name__) def home(request): logger.debug('A debug message') return render(request, 'users/home.html') -
How to convert a Django HttpRequest object with data to a Django Rest Framework Request object?
I'm trying to turn a django.http.HttpRequest object that contains JSON POST data into a rest_framework.request.Request object, but the data ends up empty. I was asked to create the HttpRequest using the Django Rest Framework's APIRequestFactory. So I create it like this: from rest_framework.test import APIRequestFactory factory = APIRequestFactory() data = {'email': 'test@example.com'} request = factory.post('/', data, content_type='application/json') # also tried using json.dumps(data) instead of just data And then I try to convert it to a Request object using: from rest_framework.request import Request from rest_framework.parsers import JSONParser request = Request(request, parsers=[JSONParser]) I would expect request.data to contain the data from data, i.e. {'email': 'test@example.com'}. However, when in print it, I get <QueryDict: {}>. The only way I can get the request to contain the data is by setting the _full_data attribute after creating the Request object: request._full_data = data I'm looking to see if there is a way of populating the request's data without setting the attribute directly. I don't understand why it's not getting populating currently. -
How can i get LTCBTC ask price in my index.html page, I don't know what mistake I'm doing?
"byte indices must be integers or slices, not str" while rendering to index.html from flask import Flask from flask import render_template import requests URL = "https://api.binance.com/api/v3/ticker/24hr" var = requests.get(URL) var.json() app = Flask(__name__) @app.route("/") def index(): for currency_detail in var: if currency_detail['symbol'] == 'LTCBTC': result = currency_detail ASK = result['askPrice'] return render_template("index.html", price = ASK) app.run(debug=True) -
How can I use requests and make use of beautiful soup using class based views
I'm trying to usethis repository I found that is a Scraper and use it in Django to display the data obtained but I don't know how to do it using Django class based view and I have a small example using function views. Is it possible to do it using CBV? Here is the snippet: from django.shortcuts import render from bs4 import BeautifulSoup import requests def dj_bs(request): if request.method == "POST": website_link = request.POST.get('web_link', None) #requests url = website_link #url headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}#headers source=requests.get(url, headers=headers).text # url source #beautifulsoup soup = BeautifulSoup(source, 'html.parser') h1_val = soup.h1.string #h1 value return render(request, 'django-bs.html', {'h1_val':h1_val}) return render(request, 'django-bs.html') -
How to solve TemplateDoesNotExist at /account
I am getting TemplateDoesNotExist at /account issues in my website, all code is working perfect on my localhost but this issue is coming on server, please let me know where is the mistake. Here is my urls.py file... app_name='account' urlpatterns = [ path('account', views.accounts, name='useraccount'), ] here is my views.py file... def accounts(request): return render(request, 'account/account.html') my account.html file path is this....account(app name)/templates/account/account.html and this is link... <li> <a href="{% url 'account:useraccount' %}">Account</a> </li> here is the value of TEMPLATES in setting.py file... 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', 'mainpage.context_processors.context_categories', ], }, }, ] -
Django Validate Form with formset
I have a form with a formset. I'm trying to add custom validation to the form. The cust_acc_no has to be unique. However, in my view if form.is_valid() is false I'm getting the following error : local variable 'formset' referenced before assignment. How can I use the custom validation and display the original form before checking if it's valid? This is my views.py: def newcustomer(request): CustomerFormSet = inlineformset_factory(Customer, Customer_contact, fields=('company','contact_name','contact_tel', 'contact_email'), extra=15 ) form = CustomerForm(request.POST) if request.method == 'POST': if form.is_valid(): form_instance = form.save() customer = Customer.objects.get(company=form_instance) formset = CustomerFormSet(request.POST, instance=customer) form.save() if formset.is_valid(): formset.save() else: return HttpResponse("Formset is invalid") return redirect('custlist') else: form = CustomerForm() context = { 'form':form, 'formset':formset } return render(request, 'customers/newcustomer.html', context) This is my forms.py: class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' def clean_cust_acc_no(self): cust_acc_no = self.cleaned_data.get('cust_acc_no') if cust_acc_no is None: raise forms.ValidationError(_("This is unique.")) return cust_acc_no This is my template: {% extends 'base.html' %} {% block page_head %}Add New Customer{% endblock %} {% block navbar %} <navbar class="mr-auto"> <div class="container-fluid"> <ul class="nav navbar-expand"> <li> <button type="submit" form="c-form" class="btn btn-outline-secondary">Add Customer</button> <button class="btn btn-outline-secondary" onclick="document.location='{% url 'custlist' %}'">Close Without Saving</button> </li> </ul> </div> </navbar> {% endblock %} {% block content %} … -
indexing with django rest api
I'm using django and postgresql as my backend for my react app. my problem is every time I update and object django change its index to be sort it as the last object. For example, if i make a put request api.put('5/',text:"update text") on the follwing api [ { "id": 5, "tag": "div", "text": "change this", "src": null, }, { "id": 11, "tag": "div", "text": "first text", "src": null, }, ] the api will change to the flowing format where the object with id 11 will be the first object [ { "id": 11, "tag": "div", "text": "first text", "src": null, }, { "id": 5, "tag": "div", "text": "update text", "src": null, }, ] How can I use put without affecting the indexing? -
DRF Permission return anonymous user
I'm working on a blog, I'm trying to set custom permissions with drf. The predefined ones work but the custom ones don't. I displayed in the console what it returns to me and the user in the request is anonymous. permissions.py from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): if obj.author == request.user: #print(f'Author:{obj.author}, request: {request.user}') return True else: return False views.py from rest_framework.views import APIView from rest_framework import generics from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Response from rest_framework import permissions from rest_framework.authentication import TokenAuthentication from posts import serializers from posts import models from posts import permissions as custom_permissions from django.http import Http404 class PostListView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'posts/post-list.html' authentication_classes = [TokenAuthentication] def get(self, request, format=None): posts = models.Post.objects.all().order_by('-id') return Response({'posts': posts}) class PostDetailView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'posts/post-detail.html' authentication_classes = [TokenAuthentication] permission_classes = [custom_permissions.IsOwner] def get_object(self, pk): obj = models.Post.objects.get(pk=pk) print(f'obj_auhor: {obj.author}') self.check_object_permissions(self.request, obj) return obj def get(self, request, pk, format=None): post = self.get_object(pk) print(f'Post detail {post}') return Response({'post': post}) Github: https://github.com/Cezar398/Blog-Perm -
Best way to store matrix for AJAX data extraction
The matrix in question will be populated with very large GeoJSON strings and be at least 1000 rows by 1000 columns in size (most of the positions will be empty). This matrix needs to be stored in such a way that I can extract information from this matrix (via a HTTP get request) as efficiently as possible. I am running my server using Django with an SQLite database. Is there an ideal way to store this kind of data using SQLite and is it possible to store the data in a plain text file, or will this be less efficient than an SQL database, and if so, why? -
foreign key fields as text field
I am new to django. I want to develop an app to calculate the cost of project. I have one model for Items and their rates. This is a foreign key in the project cost model. I want that user should enter the quantity of the items then he/she should get the total cost of project. He/She can see the unit rates of the items as well. So, all the field in foreign key should be displayed in the form as text field in non-editable form. I am not getting any solution. Please help me. Hopefully, I am able to clearly define my problem. Thank you. -
Django web application and mobile application (flutter or react native)
I just finished a Django web application and planning to develop a mobile app which doing almost most of the functions in the Django web application. i am not considering the native development platform android and IOS just to save time which language you do recommend flutter or react native or if you have any other suggestions keep in mind that the mobile app should be able to run the camera and scan a QR code also need to send print request to a Bluetooth printers multiple printers also can i just use an REST API in the mobile app to link it with the web application functions to save time. -
How to send data in GET request in django rest api test
There are "Consultant" and "Price" tables in DB and "Price" has a foreign key to "Consultant". I want to get all price records that are related to specific consultant. But I get an error when I use APITestCase to send GET request. views.py: class PriceAPI(APIView): serializer_class = PriceSerializer def get(self, request): consultant_type = request.data.get('type', None) try: consultant = Consultant.objects.get(user=request.user, type=consultant_type) except Consultant.DoesNotExist: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) try: serializer = self.serializer_class(consultant.prices, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except: return Response(status=status.HTTP_400_BAD_REQUEST) test.py: class PriceTest(APITestCase): def setUp(self): ### def test_get_delete_price(self): response = self.client.get( reverse('price'), data=json.dumps( {'type': 'sports'}), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_200_OK) I get this error: Error Traceback (most recent call last): File "D:\programming\Pycharm\Projects\Django Projects\CAPP\capp_api\tests.py", line 394, in test_get_delete_price content_type='application/json' File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\rest_framework\test.py", line 286, in get response = super().get(path, data=data, **extra) File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\rest_framework\test.py", line 194, in get 'QUERY_STRING': urlencode(data or {}, doseq=True), File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\django\utils\http.py", line 113, in urlencode for key, value in query: ValueError: not enough values to unpack (expected 2, got 1) This error is about data that is sent in request. How can I do that in GET request? -
Question about creating and managing Django apps
I'm completely new to Django. I'm on macOS Sierra. I've installed Django using pip3 install django. I currently have a folder that will be used to contain all of my Django apps that I create in the future. Right now when wanting to create a new project I use: cd desktop, cd django_apps, mkdir (dirname), cd (dirname), virtualenv env, source env/bin/activate, django-admin.py startproject (projectname) The problem occurs when I try use python manage.py runserver, where I get an ImportError saying ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?. How I normally solve this is by then going into the project folder and using pip3 install django again. Is there a way for me to install Django into the django_apps folder so that all apps have access and I don't need to install Django into every one of the new apps I create. All I've tried is cd-ing into the django_apps folder and using the install command there, but that just installs it on some remote location. Any help would be really appreciated :) -
How to get the object of a specific user and make a check?
I need to check for a specific user for the presence of the same link that I just entered from the form. I enter two links in the field, the user is filled in automatically. I want to check if the user has the same link, but I don’t know how to get all the user objects. I get this error: 'LinksForm' object has no attribute 'request' models.py: class LinksModel(models.Model): user=models.ForeignKey(User,verbose_name="user", on_delete=models.CASCADE) full_link=models.CharField(verbose_name="full_link",max_length=250) short_link=models.CharField(verbose_name="short_link",max_length=250) def __str__(self): return f"{self.short_link}" forms.py: class LinksForm(forms.ModelForm): def __init__(self, *args, **kwards): super(LinksForm, self).__init__(*args, **kwards) self.fields['full_link'].widget = forms.TextInput(attrs={'placeholder': 'full_link'}) self.fields['short_link'].widget = forms.TextInput(attrs={'placeholder': 'short_link'}) class Meta: model=LinksModel fields=["full_link","short_link"] def clean_short_link(self): short_link_list=LinksModel.objects.filter(user=self.request.user) short_link=self.cleaned_data['short_link'] if short_link in short_link_list: raise ValidationError ("error") return short_link views.py: class LinksPage(LoginRequiredMixin,CreateView): model=LinksModel template_name="News/links.html" form_class=LinksForm success_url= reverse_lazy("links") def form_valid(self,form): form.instance.user=self.request.user return super().form_valid(form) def get_context_data(self, **kwards): ctx = super(LinksPage, self).get_context_data(**kwards) ctx['links']=LinksModel.objects.filter(user=self.request.user) return ctx -
OSError: cannot load library 'gobject-2.0': error 0x7e
I installed the package weasyprint according to the instructions Installing weasyprint (Django project). My system: win 10. I have installed gtk3 and it is present in my PATH import weasyprint ... @staff_member_required def order_admin_pdf(request, order_id): # Получаем заказ по ID: order = get_object_or_404(Order, id=order_id) # Передаем объект в функцию render_to через генерацию шаблона pdf.html HTML в виде строки: html = render_to_string('shop/orders/order_admin_pdf.html', {'order': order}) # Создаем объект овтета с типом содержимого application/pdf и заголовком Content-Disposition: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id) # Вызов метода weasyprint для получения PDF документа: weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css')]) return response OSError: cannot load library 'gobject-2.0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0' -
Django - assign authenticated user to post (automatically)
I'm making a little Twitter-like app that you can "tweet" with. I've already set up the logic to log in, log out, register and write new posts. But now, when a user is logged in, I want the username to be automatically assigned to the logged in user. models.py class Tweet(models.Model): image = models.ImageField(null=True, blank=True) text = models.TextField(max_length=300, default='') created_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class NewTweet(forms.ModelForm): class Meta: model = Tweet fields = ['image', 'text'] I only show the fields image and text. The created_at and user attributes should be filled in automatically. Now in my views.py I handle saving new posts (tweets): views.py @login_required def newTweet(request): if request.method == 'POST': new_tweet = NewTweet(request.POST) if new_tweet.is_valid(): new_tweet.cleaned_data['user'] = request.user new_tweet.save() return redirect('homepage') else: new_tweet = NewTweet() return render(request, 'homepage/new-tweet.html', { 'tweet': new_tweet }) I tried to assign the user via clean_data attr. and the request.user but that doesn't work and throws an error IntegrityError at /new-tweet NOT NULL constraint failed: homepage_tweet.user_id Inside the html file I just paste {{ tweet }} inside a form tag. I knew that I got the right user because when I print request.user the logged in user is shown correct. Does someone … -
NoReverseMatch reverse for .. is not a valid function or pattern name
I am completely new to Django and posting questions here so whilst I am following the guidelines on questions, I apologise in advance for any mistakes. I have used mptt to create a category model that allows for multiple subcategories. I am running into a problem when assigning hyperlinks to each of these categories. The error that I am getting looks as follows: NoReverseMatch at /accounts/profile/ Reverse for '/assets/furniture/office-chair/' not found. '/assets/furniture/office-chair/' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: Reverse for '/assets/furniture/office-chair/' not found. '/assets/furniture/office-chair/' is not a valid view function or pattern name. Exception Location: C:\Users\dwilliams\Documents\product-catalogue\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\dwilliams\Documents\product-catalogue\env\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\dwilliams\\Documents\\product-catalogue\\ecomstore', 'C:\\Users\\dwilliams\\Documents\\product-catalogue\\env\\Scripts\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'C:\\Users\\dwilliams\\Documents\\product-catalogue\\env', 'C:\\Users\\dwilliams\\Documents\\product-catalogue\\env\\lib\\site-packages'] Server time: Mon, 17 Aug 2020 10:16:07 +0000 I think the reason that the error is being thrown when accounts/profile is being rendered is because that page displays the category names and there is a problem with assigning urls to each of those names. urls.py for the app name (shop) looks as follows: from django.urls import path, include from .import views import mptt_urls app_name = …