Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
append to request.sessions[list] in Django
Something is bugging me. I'm following along with this beginner tutorial for django (cs50) and at some point we receive a string back from a form submission and want to add it to a list: https://www.youtube.com/watch?v=w8q0C-C1js4&list=PLhQjrBD2T380xvFSUmToMMzERZ3qB5Ueu&t=5777s def add(request): if 'tasklist' not in request.session: request.session['tasklist'] = [] if request.method == 'POST': form_data = NewTaskForm(request.POST) if form_data.is_valid(): task = form_data.cleaned_data['task'] request.session['tasklist'] += [task] return HttpResponseRedirect(reverse('tasks:index')) I've checked the type of request.session['tasklist']and python shows it's a list. The task variable is a string. So why doesn't request.session['tasklist'].append(task) work properly? I can see it being added to the list via some print statements but then it is 'forgotten again' - it doesn't seem to be permanently added to the tasklist. Why do we use this request.session['tasklist'] += [task] instead? The only thing I could find is https://ogirardot.wordpress.com/2010/09/17/append-objects-in-request-session-in-django/ but that refers to a site that no longer exists. The code works fine, but I'm trying to understand why you need to use a different operation and can't / shouldn't use the append method. Thanks. -
O365 API, python sendmail:: Throttle Error: Application is over its IncomingBytes limit
I'm receiving this throttling error and there is no mention anywhere regarding why this error occurs. Error Message: Application is over its IncomingBytes limit. Can someone please help me. -
DRF copy object with FK
My model class Book(models.Model): user = models.ForeignKey(User, models.CASCADE, related_name="books") name = models.CharField(max_length=255) shop = models.ForeignKey(Shop, models.CASCADE, related_name="shops") My view: @action(methods=['POST'], detail=True) def dublicate(self, request, *args, **kwargs): book_instance = self.get_object() book_instance.pk = book_instance.id = None book_instance.save() return Response(self.serializer_class(book_instance).data) How can I also copy all FK that my current model have , like shops? -
problem with django form when set instance parameter and has file field - django form
my django form has a logo_path fields that is image field. when i want edit my object i have this problem : if i don't get request.FILES to form form = CompanyForm(request.POST,request.FILES or None,instance = company) image field doesn't edited. and if else i get request.FILES to form class form = CompanyForm(request.POST or None,instance = company) other fields become empty in my html form. this my code in view: company = Company.objects.get(id=id) form = CompanyForm(request.POST,request.FILES or None,instance = company) if form.is_valid(): form.save() messages.success(request, 'ویرایش با موفقیت انجام شد.') return redirect('./') context = { 'form' : form } return render(request,"staff/companies/store.html",context) and this is my code in django form : class CompanyForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'عنوان'})) commission = forms.DecimalField(widget=forms.TextInput(attrs={'placeholder':'کارمزد'})) class Meta: model = Company fields = [ 'title', 'commission', 'type', 'logo_path', 'is_active' ] def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['logo_path'] = "http://app.fara-ertebat.ir/static/%s"%(self.fields['logo_path']) -
query top seller products in django
i have two models like this class Product(models.Model): title = models.CharField(max_length=100) class Order_item(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.PositiveSmallIntegerField(default=0) order = models.ForeignKey(Order, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) now i want to query "top 10 most seller products between date x and y" from Order_item. how should i do? -
Auto-generated field 'contactinformation_ptr' clashes with declared field of the same name
django.core.exceptions.FieldError: Auto-generated field ‘contactinformation_ptr' in class 'ContactEmail' for parent_link to base class 'ContactInformation' clashes with declared field of the same name. enter image description here ..I have followed all the steps from this article.. https://www.kidstrythisathome.com/2016/10/wtf-django-moving-models-part1.html.. ..also tried deleting all migrations and creating new migrations...but still facing same error