Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostgreSQL: How to store and fetch historical SQL data from Azure Data Lakes (ADLS)
I have one single Django web application deployed on Azure with a transactional SQL DB i.e. PostgreSQL. At the beginning of every month, the older month's data needs to be dumped away into the ADLS repository. This unified ADLS repository will also be utilized by a Power BI portal to gain access into all the historical data it contains. Question. A) Is this scenario possible? Would the power bi portal be able to navigate through this huge heap of ADLS Data? Within the Django application, every day this historical data needs to be accessed (eg: to show the pattern over a period of years, months etc.) from the ADLS. However, the ADLS will only return a single/multiple Files, and my application needs an intermediate such as Azure Synapse to convert this unstructured data into Structured DB in order to perform Queries on this historical data to show it within the web application. Question. B) Would Azure Synapse fulfil this 'unstructured to structured conversion' requirement, or is there another Azure alternative. Question. C) Since Django is inherently tied to ORM (Object Relation Mapping), would there be any compatibility issues between the web app's PostgreSQL and Azure Synapse (i.e. ArrayField, JSONField etc.) … -
Unable to POST data in Django Rest Framework
I have developed a sample applications using Python Django Rest framework to implement basic CRUD operations. In this application , I am using MySQL database. I have created database named roytuts and a table named as user. In this user table i have declared various fields such as : id,name,email,phone,address . PROBLEM : The problem is I have declared id as AUTO INCREMENT. When i post data without providing id it gives error(although it should not give as id is auto increment). I have to manually provide id to POST data. Below are the screen shots Repository Github Link : https://github.com/mohitkrsharma/RestAPI.git Any solution please ? -
Django all auth facebook login with Use Strict Mode for Redirect URIs
Hi I am trying to implement Facebook login for my website using Django Allauth. As we can no longer disable Use Strict Mode for Redirect URIs I am getting an error when I try to login via facebook. The callback URL formed at the time of Facebook login is of this format - https://example.com/accounts/facebook/login/callback/?code=AQB7W48oY-1XxZv2xU9iahxS80ZPs4oBNLlXWTY7Y93dclyIElEPG-jWKB5ELV7Pv11ckcRYg3L67Wfcz6xqC8yhNLBaFaOQjd4F2AEp8nfScltnY3LoY79g9NjtslCSbQnSlc_hDdBm_rxQtScz-rLChNvAJaky3KYMG_USSTkm9qdyvw5lIMdcIHQjz3CTF8KdgmuFG1T8_WvVqdGDEpfhC_PD7w5tnkcChBEowHnWR656DYa1wrMR1fbP2rqxBocNn6fKPCy_GM_DZynPp8mx0F0YP55vzw2Kv8KchB2nxCaHwQ4dRvJq785w5CfCgDVc6REhbc3CNG2KqZxdxjuG&state=eukVyjHYk04X#_=_ This URL contains the query params code and state because of which it is not an exact match and I checked it via Redirect URI to Check which reported it as invalid. So on the authentication_error.html I get the following error. {'provider': 'facebook', 'code': 'unknown', 'exception': OAuth2Error('Error retrieving access token: b'{"error":{"message":"Can\'t load URL: The domain of this URL isn\'t included in the app\'s domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.","type":"OAuthException","code":191,"fbtrace_id":"AxoTkIBeoUSKsxuWvMx-Wg4"}}'',)} My Valid OAuth Redirect URIs has the following URL's https://example.com/accounts/facebook/login/callback/ https://www.example.com/accounts/facebook/login/callback/ Please help me with this issue, I have looked into all the existing issue but haven't found a solution. -
Django / Python: TypeError at / 'NoneType' object is not subscriptable
Hey pretty gals and boys, would you mind helping me out on this, please? Errors showing in views.py at line data = cartData(request) and utils.py cartItems = cookieData['cartItems'] Thanking you in advance angels :) views.py from . utils import cookieCart, cartData def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) utils.py def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} -
celery apply_async not clearing previous task
I'm using Django 2.2 and Celery for periodic tasks I have the following task configuration @celery.task(name='payments.recheck_payment_status') def recheck_payment_status(payment_id): """ Recheck payment status :param payment_id: Payment id for which recheck the status :return: """ logger.info('Checking status for payment %s' % payment_id) payment = Payment.objects.get(id=payment_id) if timezone.now() > payment.created + timedelta(days=1): logger.info('Payment done is more than 1 day. Sending email to the admin') send_incomplete_payment_email.apply_async(args=(payment_id,)) return if not payment.completed: logger.info('Payment status is incomplete. Checking payment status') payment_ = payment.recheck_payment() if payment_.completed: order = payment.order order.external_reference = payment.external_reference order.save() if not payment_.completed: logger.info('Payment %s is not completed yet.' % payment_id) recheck_payment_status.apply_async( args=(payment.id,), countdown=1800 ) And the task is called by recheck_payment_status.apply_async(args=(payment_id,), countdown=300) For a few payments, which failed to check after 300 seconds, are requeued by 1800 seconds again and again. But the past queue is not cleared and the task send_incomplete_payment_email is executed multiple times due to the previously scheduled tasks. -
Handling data during django migrations?
class Material(models.Model): name = models.CharField(max_length=50, blank=False) short_name = models.CharField(max_length=2, blank=False, unique=False, default='Al') def __str__(self): return self.name class Meta: db_table = 'material' I have created this model. Let suppose I have added a new field called status = models.IntergerField(default=1) After that If I run command python manage.py makemigrations, then django will add a new field status in table. Let's I have 3 rows in the table, then value will be as below: 1. Material1, M1, 1 2. Material2, M2,1 3. Material3, M3, 1 With this migration, I also want to change the status of every row and add new row also like 1. Material1, M1, 1 2. Material2, M2,0 3. Material3, M3, 0 4. Material4, M4, 1 Is there any way to handle data manipulation along the schema migration in django? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use school_name.set() instead
I was set that code with set still i'm getting this error there i modified in serializer file. model.py class Teacher(Model): name = CharField(max_length=64, db_index=True) mobile_number = CharField(max_length=12, blank=True, db_index=True) email = EmailField(max_length=32, blank=True, db_index=True) city = CharField(max_length=18, blank=True, db_index=True) school_name = ManyToManyField(School, related_name="teacher", null=True) associated_class = ManyToManyField( StudentClass, related_name="teachers", blank=True, ) subject = ForeignKey( Subject, related_name="teach", blank=True, null=True, on_delete=CASCADE, ) user = ForeignKey( User, null=True, blank=True, on_delete=CASCADE, ) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) class Meta: verbose_name = "Teacher" verbose_name_plural = "Teachers" this is my serializer.py file here i changed my code but still it's pointing that error in serializer. serializer.py class TeacherSignupSerializer(serializers.ModelSerializer): user = UserCreateSerializer() class Meta: model = Teacher fields = ( 'name', 'email', 'mobile_number', 'city', 'school_name', 'subject', 'associated_class', 'user', ) extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) teacher = Teacher.objects.create(**validated_data) teacher.set_user(user) return teacher this is views.py file here i declared that pulling the things which i mentioning in the serializer. views.py class TeacherSigupAPIView(generics.GenericAPIView): serializer_class = TeacherSignupSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): teacher = serializer.save() if teacher: return Response({ "status": True, "teacher": TeacherSerializer(teacher, context=self.get_serializer_context()).data, }) return Response({ "status": False, "message": "Teacher is already … -
python crash course 19-1 edit posts not working
This is the error I get when clicking on Edit post under any one of the posts. Would appreciate any help as all this django stuff is confusing me but trying my best to learn. My new post function works and clicking blog/posts to go to the overview page for the blog or to look at all the posts works as well. NoReverseMatch at /edit_post/1/ Reverse for 'posts' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/$'] Error during template rendering In template C:\Users\seng\Desktop\Python projects\c19\nineteen_one\blogs\templates\blogs\base.html, error at line 0 urls.py """Defines url paterns for blogs""" from django.urls import path from . import views app_name = 'blogs' urlpatterns =[ #Home page path('', views.index, name='index'), # Page that shows all posts/ path('posts/', views.posts, name='posts'), #Page for adding a new blogpost path('new_post/', views.new_post, name='new_post'), #Page for editing a post #maybe remove the id? path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'), ] views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm # Create your views here. def index(request): """The home page for blogs""" return render(request, 'blogs/index.html') def posts(request): """Show all blogposts""" posts = BlogPost.objects.order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) def new_post(request): """Add a new blogpost""" if request.method != 'POST': #No … -
dockerizing django, docker-compose works but not docker run
I have a django app (url shortener for k8s) here [https://github.com/MrAmbiG/shorty/tree/k8s][1]. The docker-compose version works with the same docker image but the docker run doesn't work (I cannot access from host). Docker and docker-compose up both are from docker.io and both are using the same docker image but why the difference? I apologize for not posting all the contents of the file but rather posting the github url itself. version: '3.7' services: django: image: gajuambi/shorty ports: - 80:8001 env_file: - ../.env Below Doesnt work docker run --name shorty -it --env-file .env gajuambi/shorty -p 8001:8001 -
Why does Okta-React Login redirect to blank page when using Django?
I am using Okta-React for authentication in my React project and when I run the React test server my login authenticates successfully and redirects to the account page. When I run the React build command and render the build files with Django, my login authenticates properly, but when it redirects back to my site I get a blank /implicit/callback page, no login token or user info, and the code & state gets stuck in the URL. Does anyone know why this is only happening when using Django, and what I can do to resolve this issue? Here is my authConfig: const config = { issuer: 'https://dev-#######.okta.com/oauth2/default', redirectUri: window.location.origin + '/implicit/callback', clientId: '#@#@#@#@#@#@#@#@#', pkce: true }; export default config; Here is my accountAuth import React, { useState, useEffect } from 'react'; import { useOktaAuth } from '@okta/okta-react'; import '../scss/sass.scss'; import "../../node_modules/bootstrap/scss/bootstrap.scss"; import 'react-bootstrap'; const AccountAuth = () => { const { authState, authService } = useOktaAuth(); const [userInfo, setUserInfo] = useState(null); useEffect(() => { if (!authState.isAuthenticated) { // When user isn't authenticated, forget any user info setUserInfo(null); } else { authService.getUser().then((info) => { setUserInfo(info); }); } }, [authState, authService]); // Update if authState changes localStorage.setItem("username", userInfo && userInfo.given_name) const login = … -
datetime.now() vs Django runserver
I have a simple function: from datetime import datetime def GetEmployeeLeaveV2(user, thisYear=datetime.now().strftime("%Y")) print ("GetEmployeeLeaveV2 thisYear: ",thisYear) print ("GetEmployeeLeaveV2 datetime.now(): ",datetime.now().strftime("%Y")) (.....) By default, when I call this function and I dont pass in a variable for thisYear, it takes the current year at the time its called. For the most part this works fine, especially in my local machine. Both print statements generate the expected same value by default. This same code was then uploaded to a cloud server, where it has been working fine. However, recently, the output for both the print statements began to differ. Here I reran the code on my local machine I changed my machine date to '2019', executed runserver and the print statements are generating the expected data. I then changed the date to '2020' without cancelling runserver to simulate the year changing in the cloud server and my output now do not match. What is happening here and how do I solve it? I would presume restarting of the cloud server would fix this, but the core issue I want to know is how to solve this without doing so, so that I dont have to restart it every year. Python 3.7 Django … -
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> …