Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap4 Default Values Within Form
I have the following form that I am trying to customize using bootstrap4. It looks like the formatting is working, but when I try and default the values in my edit form to the current values, they appear in a second text box below the form I just created. How would I adjust this code so the values are defaulted in my desired text box? {{ form.non_field_errors }} <div class="form-group"> {{ form.employee.errors }} <label for="{{ form.employee.id_for_label }}"></label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Log the employee"> {{ form.employee }} <small id="emailHelp" class="form-text text-muted">Who does this individual report to?</small> </div> -
Using a class object in another class in models.py [Django]
I am writing a blog application in Django. In the models.py I have two classes: Post and LanguageCategory. In language category I would predefine which languages are applicable such as English, Italian, and this could be created by superuser in admin login. However, inside the Post class I want to use the LanguageCategory class as a property called languages as follows (code for models.py): from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. # https://stackoverflow.com/questions/29536180/django-blog-adding-published-date-field-to-new-posts-and-ability-to-login-as-non class Post(models.Model): title = models.CharField(max_length=300) keywords = models.CharField(max_length=300, default="some keywords here") author = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField(auto_now_add=True, blank=False, null=False) language = LanguageCategory() image = models.ImageField(upload_to='blog_images/', default='blog_images/myimage.png') body = models.TextField() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title + ' | ' + str(self.author) class LanguageCategory(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name When I try to make migrations I get the following error: line 15, in Post language = LanguageCategory() NameError: name 'LanguageCategory' is not defined How to fix this issue and how can I use LanguageCategory in the Post such that the blog posts has a field which selects the languages? -
Why I get "KeyError" exception in django instead of "This field is required" exception on the form validation
I'm new to Django, I have a registration form, Everything works fine If I fill all fields and when I don't fill all the fields. But when I submit a form without a username field I get a "Key Error" instead of "This field is required" Exception since I have declared the field is required on the form class. forms.py class UserRegistration(forms.ModelForm): first_name = forms.CharField(label='First Name', max_length=50) last_name = forms.CharField(label='Last Name', max_length=50) username = forms.CharField(label='Username', max_length=50) email = forms.EmailField(label='Email', max_length=50) password = forms.CharField(label='Password', widget=forms.PasswordInput, max_length=50, validators = [validators.MinLengthValidator(6)]) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput, max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2') def clean_username(self): username = self.cleaned_data['username'] email = self.cleaned_data['email'] if username and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError('This username address is already in use.') return username def clean_email(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use.') return email def clean_password(self): password = self.cleaned_data['password'] if len(password) < 6: raise forms.ValidationError("Password is too short") return password def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] views.py def register(request): if request.method == 'POST': form = UserRegistration(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.set_password( form.cleaned_data.get('password') ) … -
Multiple images are showing in django image grid
I am somewhat new to Django. I am making an image grid (html). But the images are shown multiple times in that grid. This is what I mean; Here are my files; Views.py from django.shortcuts import render photos = [ { 'user_im': 'https://thumbor.forbes.com/thumbor/fit-in/416x416/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5f47d4de7637290765bce495%2F0x0.jpg%3Fbackground%3D000000%26cropX1%3D1398%26cropX2%3D3908%26cropY1%3D594%26cropY2%3D3102', 'photo': 'https://images.unsplash.com/photo-1515199967007-46e047fffd71?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=975&q=80', 'date_shared': '4th January, 2020', 'caption': 'A wonderful pic', }, { 'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg', 'photo': 'https://images.unsplash.com/photo-1547500135-9f6e5a9a6aff?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80', 'date_shared': '4th January, 2020', 'caption': 'A nice picture', }, { 'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg', 'photo': 'https://i.guim.co.uk/img/media/6088d89032f8673c3473567a91157080840a7bb8/413_955_2808_1685/master/2808.jpg?width=1200&height=1200&quality=85&auto=format&fit=crop&s=412cc526a799b2d3fff991129cb8f030', 'date_shared': '4th January, 2020', 'caption': 'A nice picture', } ] def home(request): context = { 'photos': photos, } return render(request, 'photos/home.html', context) def explore(request): context = { 'photos': photos, } return render(request, 'photos/explore.html', context) grid.py {% extends 'photos/base.html' %} {% block content %} <h1><strong>These are some of the best</strong></h1> <h5 class="text-muted">Just for you...</h5> {% for photo in photos %} <div style="width:100%"> {% for photo in photos %} <div style="float:left; width:200px; height:200px;"> <img src="{{ photo.photo }}" height="200px" width="200px"> </div> {% endfor%} </div> {% endfor %} {% endblock content %} app urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('grid/', views.grid, name='grid'), ] I am passing in some context. Will it be fixed if I upload the images? Please give me … -
Parsing Bing Search API results for Django Template
I have a simple view to fetch bing search results using their official API (no scraping :) for example purposes I have hardcoded the query being Pfizer def bing (request): url = "https://bing-web-search1.p.rapidapi.com/search" querystring = {"q":"pfizer","mkt":"en-us","textFormat":"Raw","safeSearch":"Off","freshness":"Day"} headers = { 'x-bingapis-sdk': "true", 'x-rapidapi-key': "", 'x-rapidapi-host': "bing-web-search1.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) print (response.text) #return render (request, 'home.html', {'page':rows}) the print returns a very complex (for me :) JSON {"_type": "SearchResponse", "queryContext": {"_type": "QueryContext", "originalQuery": "pfizer"}, "webPages": {"_type": "Web\/WebAnswer", "webSearchUrl": "https:\/\/www.bing.com\/search?q=pfizer", "totalEstimatedMatches": 220000, "value": [{"_type": "WebPage", "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.0", "contractualRules": [{"_type": "ContractualRules\/LicenseAttribution", "targetPropertyName": "snippet", "targetPropertyIndex": 0, "mustBeCloseToContent": true, "license": {"_type": "License", "name": "CC-BY-SA", "url": "http:\/\/creativecommons.org\/licenses\/by-sa\/3.0\/"}, "licenseNotice": "Text under CC-BY-SA license"}], "name": "Pfizer - Wikipedia", "url": "https:\/\/en.wikipedia.org\/wiki\/Pfizer", "isFamilyFriendly": true, "displayUrl": "https:\/\/en.wikipedia.org\/wiki\/Pfizer", "snippet": "Pfizer Inc. (\/ ˈ f aɪ z ər \/) is an American multinational pharmaceutical corporation. One of the world's largest pharmaceutical companies, it is ranked 57 on the 2018 Fortune 500 list of the largest United States corporations by total revenue.. Headquartered in Manhattan, Pfizer develops and produces medicines and vaccines for a wide range of medical disciplines, including immunology ...", "deepLinks": [{"_type": "WebPage", "name": "Zoetis", "url": "https:\/\/en.wikipedia.org\/wiki\/Zoetis", "snippet": "Zoetis Inc. (\/zō-EH-tis\/) is the world's largest producer of medicine and … -
Wagtailtrans setup fails
Please, some help there? I'm trying to setup wagtailtrans to my project. Following this https://wagtailtrans.readthedocs.io/en/2.1/getting_started.html After added middlewere classes the app don't works 'wagtail.core.middleware.SiteMiddleware', 'wagtailtrans.middleware.TranslationMiddleware', output logs: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/bpvApp/bpvApp/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.8/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/usr/local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, … -
Is it possible to add parent to child for ForeignKey relationship?
Say I have a ForeignKey field called "parent" with a related_name of "children": class Item(PolymorphicModel): title = models.CharField() parent = models.ForeignKey( "self", related_name='children', null=True, blank=True, on_delete=models.CASCADE) class Parent(Item): pass class Child(Item): pass Why is it that I can only add the child to the parent but I get an error if I try to add a parent to the child? So this works: p1 = Parent.objects.create(title="Parent 1") c1 = Child.objects.create(title="Child 1") print(p1.children) #<PolymorphicQuerySet []> p1.children.add(c1) But this doesn't: p1 = Parent.objects.create(title="Parent 1") c1 = Child.objects.create(title="Child 1") print(c1.parent) # None c1.parent.add(p1) # AttributeError: 'NoneType' object has no attribute 'add' Do I just have to add to the Parent's children field each time? Is there no way to add to the Child's parent instead? Is there any reason why adding to the Child's parent doesn't work or shouldn't be used? I'm also a little confused about when/how to use "_set" in this circumstance (if that's relevant). So following the format of Django's Many-to-one example, the following doesn't work for me either: p1 = Parent.objects.create(title="Parent 1") c1 = Child.objects.create(title="Child 1") p1.children.add(c1) print(p1.children_set.all()) # AttributeError: 'p1' object has no attribute 'children_set' print(c1.parent_set.all()) # AttributeError: 'c1' object has no attribute 'parent_set' print(p1.item_set.all()) # AttributeError: 'p1' … -
Why does Django complain that a new model column is unknown instead of migrating it?
I'm using Django 3.0 with Python 3.6. I have a Model: class Data(models.Model): parameter = models.CharField( max_length=16, blank=True, null=True ) mode = models.CharField( max_length=8, blank=True, null=True ) value = models.PositiveSmallIntegerField( blank=True, null=True ) Everything was working fine. Then, I added one field to the Model: class Data(models.Model): parameter = models.CharField( max_length=16, blank=True, null=True ) mode = models.CharField( max_length=8, blank=True, null=True ) value = models.PositiveSmallIntegerField( blank=True, null=True ) code = models.CharField( max_length=64, blank=True, null=True ) Having done nothing else, I tried to run a migration. It results in this error: $ python3 manage.py makemigrations ... django.db.utils.OperationalError: (1054, "Unknown column 'appName_data.code' in 'field list'") Which, yeah, no shit it's an unknown column, that's why I want you to add it to the table. I've tried searching for this error, but all I can find is stuff on Stack Overflow from before 2008 that I can't make apply to my situation, and some old obscure bug reports that I can't even begin to read. What do I do? -
Static files not loading on django localhost while loading okay on heroku
I'm building a django web app. I can't get to display a static file (icon) in an html template when I run my app locally thru python manage.py runserver (to run with the wsgi from django) or heroku local (to simulate the heroku web server locally) while it actually works when running on heroku cloud. My project tree: django-project |_ ... |_ static |_ icons |_ graph-up.svg index.html {% load static %} <img src="{% static 'icons/graph-up.svg' %}" /> settings.py [...] BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') [...] urls.py urlpatterns = [ path('', views.home, name='index'), ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I've followed the instructions from https://docs.djangoproject.com/en/3.1/howto/static-files/ Any ideas or suggestions welcome! -
Django and React - Models for adding multiple data fields - Material UI
I am using Django for my backend and react for my frontend to build a web application that calculates cost based on the total volume (calculated using dimensions lwh) of some boxes. In order to do that, I created a form using React and Material UI in which there is an ADD MORE button to add the dimensions of multiple additional boxes. Although I managed to create a model in case there is only one box and store the values in the database, I don't know how this will work when I use the ADD MORE button. How can I create my Django model to store the dimensions and volume for each additional box of the form? I checked several other threads and found out about Formsets but I don't know how to apply it in my case. Thanks in advance for your help :) -
How do I do a post request with related serializers Django rest framework
I have model Package with Supplier and PackageSize, foreign keys and a field to which is also a foreign key of a Shipping model which contains where the supplier wants to ship the package so to make sure I a user can submit the whole information in one request, I created my serializers and linked them like such. serializers.py from users.models import Supplier from packages.models import Package , PackageSize , ShippingLocation , Shipping class ShippingLocationSerializer(serializers.ModelSerializer): class Meta: model= ShippingLocation fields = ['latitude','longitude'] def create(self, validated_data): return ShippingLocation(**validated_data) class PackageSizeSerializer(serializers.ModelSerializer): class Meta: model= PackageSize fields = ['length', 'width' ,'height' ,'weight'] def create(self, validated_data): """ docstring """ pass class ShippingSerializer(serializers.ModelSerializer): location = ShippingLocationSerializer(source='location_set') class Meta: model = Shipping fields = [ 'first_name', 'last_name', 'phone_number', 'email', 'street_address', 'village', 'district', 'country', 'location' ] def create(self, validated_data): """ docstring """ pass class SupplierPackageSerializer(serializers.ModelSerializer): size = PackageSizeSerializer(source='size_set') shipping_location= ShippingSerializer(source='to_set') class Meta: model = Package fields = ['supplier', 'name', 'size', 'shipping_location', ] read_only_fields = ['supplier'] def create(self, validated_data): user =Supplier.objects.get(username=self.context['request'].user) return Package(supplier=user, **validated_data ) and created my views like such view.py from rest_framework import generics from packages.models import Package from .serializers import , SupplierPackageSerializer from rest_framework.permissions import IsAuthenticated class SupplierPackageViewSet(generics.ListCreateAPIView): serializer_class = SupplierPackageSerializer queryset = Package.objects.all().order_by('-name') permission_classes … -
Python SMTP - [Errno 101] Network is unreachable on AWS EC2
I am trying to verify the email address of the user. When trying to connect to the user's host using MX record I always get a 'Network is unreachable' error on the AWS EC2 instance. However, it works perfectly fine locally. records = dns.resolver.query(domain, 'MX') mx_record = records[0].exchange mx = str(mx_record) smtp_server = smtplib.SMTP(host=mx) If I try to use: smtp_server = smtplib.SMTP_SSL(host=mx, port=465) I get the same issue. Please share any ideas. Thanks! -
How to show exactly the same bokeh plot twice in an html?
I have a sort of heavy plot rendering with bokeh in my website made with django. The thing is that exactly the same plot is shown in two different sections of the html, say a summary section + the specific section. I want to avoid rendering the plot twice because it takes a reasonable amount of time to render. But if i place the same {{script}} {{div}} variables twice in the html only one is shown because the divs have the same id (i guess). How can I present exactly the same plot twice? -
Loading a plotly dash app into html leave huge empty space at the bottom
I am trying to load a django-plotly-dash app onto a page in my django project, where I am building the pages using standard bootstrap components and css. However I am unsure why the dash app always creates a huge empty space below it, and was wondering if anyone has encountered a similar issue and has found a way around it. Thanks in advace Jason dashboard.py import dash import dash_html_components as html from django_plotly_dash import DjangoDash import plotly.express as px import pandas as pd import dash_core_components as dcc import dash_bootstrap_components as dbc external_stylesheets = ['dbc.themes.BOOTSTRAP'] app = DjangoDash('Example') # Define the app app.layout = html.Div(children=[ html.Div(className='row', # Define the row element children=[ html.Div(className='four columns', # style=fourColumnStyle, children = [ html.H2('Dash - TEST', style = {'color' : 'Azure'}), html.P('''Testing for empty space for Plotly - Dash''', style = {'color' : 'LightGrey'}), ] ) ]) ]) index.html <!-- Load CSS --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <!-- Custom styles for this template--> <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/solar/bootstrap.min.css" rel="stylesheet"> </head> <body id="page-top"> <div id="wrapper"> <div id="content-wrapper"> <div class="container-fluid"> {%load plotly_dash%} {% plotly_app name='Example' ratio=1 %}} <div>This is a test</div> </div> … -
django can't find full url but can find path
I've got gulp working with django, and I'm trying to serve everything from my myapp/static/myapp/ folder. I'm using the shell to troubleshoot and for some reason the resolver can find the path but not the full url. #enter shell with: # > ./venv/Scripts/python ./myapp/manage.py shell import django.urls as urls import os #no port urls.resolve('http://localhost/static/myapp/favicon/site.webmanifest.json') urls.resolve('http://127.0.0.1/static/myapp/favicon/site.webmanifest.json') #django dev server port urls.resolve('http://127.0.0.1:8000/static/myapp/favicon/site.webmanifest.json') urls.resolve('http://localhost/static/myapp/favicon/site.webmanifest.json') #browsersync port urls.resolve('http://127.0.0.1:3000/static/myapp/favicon/site.webmanifest.json') urls.resolve('http://localhost:3000/static/myapp/favicon/site.webmanifest.json') #all the above produce an error like below #output Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\jmarshall\source\venv\lib\site-packages\django\urls\base.py", line 25, in resolve return get_resolver(urlconf).resolve(path) File "C:\Users\jmarshall\source\venv\lib\site-packages\django\urls\resolvers.py", line 576, in resolve raise Resolver404({'path': path}) django.urls.exceptions.Resolver404: {'path': 'http://127.0.0.1:3000/myapp/favicon/site.webmanifest.json'} ############################################################################################ # now if I resolve with just the path: urls.resolve('/static/myapp/favicon/site.webmanifest.json') ##output ResolverMatch(func=django.views.static.serve, args=(), kwargs={'path': 'myapp/favicon/site.webmanifest.json', 'document_root': 'C:\\Users\\jmarshall\\source\\myapp\\myapp\\../static'}, url_name=None, app_names=[], namespaces=[], route=^static/(?P<path>.*)$) ############################################################################################ m = urls.resolve('/static/myapp/favicon/site.webmanifest.json') os.path.exists(os.path.join(m.kwargs['document_root'], m.kwargs['path'])) ##output True ############################################################################################ On the front end, the static files are most certainly 404. Any idea what's happening? -
How can I create an upload_to folder using a field belonging to the model that is simultaneously being created?
Context: I'm building a car dealership app using Django 3.1.4, and trying to implement a feature where by every time a new ad is created, so is a new folder (via the upload_to method) within /media/ that will only contain that newly created ad's photos. I've gotten this working somewhat using date formatting (see below) but I need this new folder to be named one of the fields belonging to the model(see the second code snippet). photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) For example, every newly created ad would use the title field.. class Vehicles(models.Model): CONDITION_CHOICES = [("Brand New","Brand New"),("Used", "Used")] FUEL_CHOICES = [("Petrol","Petrol"),("Diesel", "Diesel"),("Electric", "Electric"),("Hybrid", "Hybrid")] TRANSMISSION_CHOICES = [("Automatic","Automatic"),("Manual", "Manual")] title = models.CharField(max_length=200, default = "Ad Title & Folder Name") def folder_name(self, title): return self.title make = models.CharField(max_length=100) Ideally then, the media folder would look something like /media/ Opel Astra VXR/ Mercedes E200/ I understand that many others have done something similar but all the examples I found use the 'user' and instead I need to use a model field (belonging to the model that is being created) as the folder name. Closing notes: The function in the second code snippet was just something I was trialing. Also, this is still … -
Django 3.0 - View a PDF in the browser
I simply want to click a link and view, in the browser, a PDF that I have uploaded to my Django project. To be sure in the Django docs (https://docs.djangoproject.com/en/3.1/howto/outputting-pdf/) about how to create reports is not at all what I'm looking to do, I don't need to generate a PDF, I already have the ones I need. (This comes up a LOT in other answers.) No luck with: Render HTML to PDF in Django site (No surprise, it's 11 years) Or: Django - JS : How to display the first PDF page as cover (somewhat surprised this is not the only time that a suggestion containing pdf.js occurs, I simply get an empty white square on me page with no further errors). I have as well attempted embedding the PDF in a template with no luck. (Recommended way to embed PDF in HTML?) (Tried or , and as you see in the link pdf.js once more. No go.) How, generally, would one accomplish this specifically in Django 3.x? Thanks. -
Python/Django: No module named dj_database_url
I know this issue has been touched several times but in this case, I am trying to ask for advices more than 'whats going on with dj_database_url', which it has been answered already. I am a JS developer and therefore have worked exclusively with node environments, but I received a task to fix with a web application (server-side rendered) built with Django, something that is completely new to me. Anyway, I have been reading about this framework and so on, but before I start typing commands as crazy, I would like to hear you what should I consider first? The tasks are mainly styling and accessibly issues, so what I thought is "okey, I just need to fire the server and start fixing styling stuffs", but before that, I might need to download packages and doing some configuration?. In the repo that they sent me, it is only stated the run commands: Setup $ python manage.py migrate $ python manage.py runserver Cool, but there is when the issues come. MacOS, the system that I use, comes already with Python2.7 and 3.9, and some people state that when you run the commands, use the version, otherwise could not work (ex: python2.9 … -
Django must clean data from xml before save it to database?
I import the data from an xml file, using a script and not a form. products = tree.findall('item') for product in products: prod = Product() prod.name = product.find('title').text prod.description = product.find('description').text prod.save() If i use save() method, should I clean the data from xml before save it to database? Thank you -
Test case for a django view
I need help in understanding how to write a particular test case for a view and I can not get my head around it. I am basically using the polls app in Django docs example but I have extended it quite a bit. So I have a view called createQuestion that renders createQuestion.html. The user can add a question and can add a minimum of 1 and a max of 10 choices to each question. If the user tries to submit with completing the requirements an error will be shown and the form won't submit till at-least one choice is added or if the user tries to add more than 10 choices. I also check the number of choices submitted in the backend as well, if more than 10 come or less than 1 come the createQuestion.html will render again giving the error message "Incorrect number of choices". What I need help with I don't understand how I can write a test case for this view in tests.py to check if the page contains the error messages if the user tries to submit more than 10 or less than 1. Code Here is the code for models.py, view in views.py, … -
is there any way to connect a Django app and Java app using WebSockets?
At the moment I am in a project in which it is divided into three groups: the first in java that gathers information and exposes it through API Rest, the second (to which I belong) in django that brings the information from the first group, processes it and It exposes it to the third party that is the general front of the application. Currently the first group is exposing a WebSocket to which I want to connect and later through another WS exposing the information to the third. I was reviewing Django Channels to be able to do this and although I have been looking I can not find how to do it. I appreciate if you could guide me with any ideas to do this or if you have done something similar in the past. -
Any suggestions about how to refresh a js file in django, I changed the URL but its still loading the privious one
` Im getting this error GET http://127.0.0.1:8000/move/move_type_rapport 404 (Not Found) But as you can see below, the URL is http://127.0.0.1:8000/move/move_type_rapport const getChartData =() => { console.log("fetching"); fetch("/move/move/move_type_rapport") .then((res) => res.json()) .then((results) => { console.log("results", results); const type_data = results.move_type_data; const [labels, data] = [ Object.keys(type_data), Object.values(type_data), ]; renderChat(data, labels); }); }; document.onload = getChartData();` -
Django Rest Framework save data into not default database
I have model: class TableUser(models.Model): name = models.CharField(max_length=60) lastname = models.CharField(max_length=60) class Meta: db_table = 't_users' def __str__(self): return self.name serializer look like: class UserListSerializer(serializers.ModelSerializer): class Meta: model = TableUser fields = ('name', 'lastname') I would like to save new data into database (not default) { "name": "one", "lastname": "two" } Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'remote': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_db', 'USER': 'admin', 'PASSWORD': 'admin123!', 'HOST': 'localhost', } } views.py @api_view(['POST']) def saveuser(request): if request.method=="POST": saveserialize=UserListSerializer(data=request.data) if saveserialize.is_valid(): saveserialize.save(using='remote') return Response(saveserialize.data, status=status.HTTP_201_CREATED) return Response(saveserialize.data, status=status.HTTP_400_BAD_REQUEST) i get: t_users() got an unexpected keyword argument 'using' if I change saveserialize=UserListSerializer(data=request.data) to saveserialize=UserListSerializer(data=request.data, many=True) then I get Got AttributeError when attempting to get a value for field name on serializer UserListSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Please help me, what am I doing wrong -
Django: get_queryset after get_context_data
I am filtering the Project model objects by authenticated user in get_context_data in my ListView class myprojects(LoginRequiredMixin, ListView): model = Project template_name = 'my_project_list.html' ordering = ['project_title'] def get_context_data(self, *args, **kwargs): context = super(myprojects, self).get_context_data(**kwargs) context['my_projects'] = Project.objects.filter(engineer=self.request.user) return context In template {% for my_project in my_projects %} {{ my_project }} {% endfor %} I have a form in my template to search for projects and I use a get_queryset on the same ListView. I receive the search but it does not filter in the template class myprojects(LoginRequiredMixin, ListView): model = Project template_name = 'my_project_list.html' ordering = ['project_title'] def get_context_data(self, *args, **kwargs): context = super(myprojects, self).get_context_data(**kwargs) context['my_projects'] = Project.objects.filter(engineer=self.request.user) return context def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) search = self.request.GET.get('buscar', None) print(search) if search: context = context.filter( Q(project_title__icontains=search) | Q(category__title__icontains=search) ).distinct() return context Note: When i use {% for project in object_list %} instead of {% for project in my_projects %}, it searches without problems, but I no longer have the filter by user -
Dynamically add ordered number to each object in Paginated response from Django Rest
I'm currently getting a standard paginated response using Django REST framework, however I need to add a number to each object response in the order it is retrieved. 1,2,3,4,5 etc. It must be calculated each time dynamically if new results are added and retrieved by the user. It would go from this: { "next": "http://localhost:8000/api/home/?page=2", "previous": null, "count": 105, "results": [ { "title": "example1", "description": "foobar1", }, { "title": "example2", "description": "", }, ... ] to looking like this: { "next": "http://localhost:8000/api/home/?page=2", "previous": null, "count": 105, "results": [ { "key": 1, "title": "example1", "description": "foobar1", }, { "key": 2, "title": "example2", "description": "", }, ... ] This would also include the next page in the paginated response, e.g. 21, 22, 23, 24. If a user then refreshes the page and new data is found and retrieved it would recalculate and add key numbers again. How would one go about this? Thanks!