Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django objects.all() not updating without server restart [closed]
django objects.all() only seems to be updating after server restart. For example, I would make a category called 'Education' and it shows up on the admin site, but when I'm using in the form, it will not show up unless I restart the live server. forms.py: def tuplelistmaker(list): output = [] for x in list: newtuple = (x.pk, x) output.append(newtuple) print(output) return output class PostForm(forms.Form): title = forms.CharField(max_length=100, label='Post Title') short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) content = forms.CharField(widget=CKEditorWidget()) status = forms.NullBooleanField(label='Ready to Publish?') image = forms.ImageField(label='Select a cover image:') captioned_image = forms.ImageField(label='Select a captionable image:') caption = forms.CharField(max_length=200) category = forms.ChoiceField(choices = tuplelistmaker(list(PostCategory.objects.all()))) embed = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) tags = forms.CharField(widget=forms.Textarea(attrs = {"rows":1, "cols":150})) models.py: class PostCategory(models.Model): category = models.CharField(max_length=100) categorySlug = models.SlugField(max_length=100) def __str__(self): return self.category class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') short_description = models.TextField() updated_on = models.DateTimeField(auto_now=True) content = RichTextField() created_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=Status, default=0) cover_image = models.ImageField(upload_to = 'coverimages', null =True, blank = True) captioned_image = models.ImageField(upload_to = 'captionedimages', null=True, blank = True) caption = models.CharField(max_length=300) featured = models.IntegerField(choices=Featured, default=1) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE, null=True, blank=True) embedded_code = models.TextField(blank=True, null=True, default='null') tags = models.TextField(blank=True, null=True) class Meta: … -
filtering in serializers Django rest framework
I am new to Django, in my probject a room has different statues for example: registered, available, each status has a start date, I have to get the start_date when the status is registered. how can I do that in serializer? Thanks in advance! in model.py: class RoomStatus(models.Model): room = models.ForeignKey(Room, on_delete=models.DO_NOTHING, related_name='rooms') class RoomStatusChoices(models.IntegerChoices): REGISTERED = 1 RESERVED = 2 AVAILABLE = 3 room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE) start_date = models.DateTimeField(default=timezone.now()) In serializers.py: class RoomStatusSerializer(serializers.ModelSerializer): class Meta: model = RoomStatus fields = ['id', 'start_date'] class RoomSerializer(serializers.ModelSerializer): rooms = RoomStatusSerializer(many=True) class Meta: model = Room fields = ['id', 'rooms'] in views.py: class RoomViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet, UpdateModelMixin): queryset = Room.objects.all() serializer_class = RoomSerializer -
Django - Change client encoding from WIN1252 to UTF8
So I have my Django application deployed on a Heroku server and when I try to query for Post I get this. How I query // Command to get into postgres heroku pg:psql // Query SELECT * FROM posts; What I get back ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252" I'm decently sure what is happening is that someone created a post where the body has an emoji in it. I'm using Postgresql it supports UTF8 for storing. I'm just not sure what part of Django is causing it to encode to WIN1252 instead of UTF8. How change client encoding from WIN1252 to UTF8 models.py class Post(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) Setup: Postgresql Django 3.2.9 -
Dynamic URL in DRF Modelviewset
I'm working on a url where I'm filtering the News according to category. So all i am doing is passing the name of the category in url in this manner 127.0.0.1:8000/news/category/sports/ or 127.0.0.1:8000/news/category/entertainment/. Here's my code snippet views.py class CategoryAPI(viewsets.ModelViewSet): serializer_class = CategorySerializer # lookup_field = 'slug' # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get_queryset(self): category = Category.objects.all() return category @action(methods=['get'], detail=False, url_path=r'list/(?P<name>[\w-]+', url_name='category') def get_category(self, request, category=None): return Category.objects.all().order_by(name) class PostAPI(viewsets.ModelViewSet): serializer_class = PostSerializer # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get_queryset(self): news_post = News.objects.all() return news_post serializers.py class PostSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) dislikes = serializers.SerializerMethodField(read_only=True) views = serializers.SerializerMethodField(read_only=True) # author = serializers.StringRelatedField() # category = serializers.StringRelatedField() def get_likes(self, obj): return obj.likes.count() def get_dislikes(self, obj): return obj.dislikes.count() def get_views(self, obj): return obj.views.count() class Meta: model = News fields = ('id','category','post_type','title','content','hash_tags','source','author','views', 'likes','dislikes','status') class CategorySerializer(serializers.ModelSerializer): posts = PostSerializer(many=True, read_only=True) parent = serializers.StringRelatedField() class Meta: model = Category fields = ['name', 'slug', 'parent','posts'] urls.py router = DefaultRouter() router.register('news', views.PostAPI, basename='news'), router.register('category', views.CategoryAPI, basename='category'), router.register('news-images', views.NewsImageAPI, basename='news-image'), router.register('comment-room', views.CommentRoomAPI, basename='comment-room'), router.register('comment', views.CommentAPI, basename='comment') urlpatterns = [ ] urlpatterns += router.urls So all I want to do is instead of passing the name of the category in the url, how can I create it dynamically. Otherwise … -
I made an emailing client using django for backend and js at the frontend. 2 users were logged in at the same time. A weird issue happened
Question Contd.... So my email host was smtp.gmail.com. One registered user logged in with correct credentials of their gmail account whereas the other had not given a correct password during registration but was logged in. So when user 2(with wrong credentials) clicked on the send button, with me as the recipient of the mail, I received a mail from user 1's account. Requesting some insights on the problem. Views.py given below from django.http.response import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse from django.shortcuts import redirect, render from django.urls import path from Email.regForm import registrationForm from Email.loginForm import loginForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.core.mail import send_mail import json from django.conf import settings #Create your views here. user = None password = None def loginPage(request): form = loginForm() if request.method == 'POST': global user user = authenticate(request,username = request.POST['email_id'],password = request.POST['password']) try: if user is not None: global password password = request.POST['password'] print(password) settings.EMAIL_HOST_PASSWORD = password print(type(user)) print(user.get_username()) login(request,user) return redirect("https://mailitappbyrb.herokuapp.com/emailpage") else: return HttpResponseBadRequest("Invalid Attempt") except: return Http404("Something Went Wrong..Please Try Again") return render(request,'loginpage.html',context={'form':form}) def registrationPage(request): form = registrationForm() if request.method == 'POST': form = registrationForm(request.POST) if form.is_valid(): try: User.objects.create_user(username … -
Getting all the objects in the JavaScript from Django
I want to get all my object models from the database and store them in someway, the model I have is: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() I'm sending them in views.py: device_list = list(Device.objects.all()) context = {"filename": filename, "deviceList": device_list, } In JS I managed to get each object like that: {% for item in deviceList%} console.log( "{{item}}" ); {% endfor %} What I want is to store those objects in some way, but I don't really know how, because they are coming like that Model object (1). -
Pycharm Shell script and Python
In Pycharm configuration, I want to execute a shell command before running Python script I used the Before launch section but the problem is it executes the shell in another terminal which makes the python script doesn't see the configs I set in the shell file Is there a way to solve that without need to write a Python file that runs both inside same terminal? -
Why am i getting a NotImplementedError when implementing o365-python
I'm trying to implement o365-python in our Django backend and want to log users in using o365. I am using the "With your own identity" flow and get a valid token back from the service. I am using the exact same code as in the documentation with the flask example. But when I get the authorization code with account.con.get_authorization_url(redirect_uri=redirect_uri, requested_scopes=scopes), I get the following error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/dashboard/views/authentication.py", line 55, in login_step1 url, state = account.con.get_authorization_url(redirect_uri=callback, requested_scopes=config365.scopes) File "/usr/local/lib/python3.9/site-packages/O365/connection.py", line 462, in get_authorization_url auth_url, state = oauth.authorization_url( File "/usr/local/lib/python3.9/site-packages/requests_oauthlib/oauth2_session.py", line 165, in authorization_url self._client.prepare_request_uri( File "/usr/local/lib/python3.9/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 139, in prepare_request_uri raise NotImplementedError("Must be implemented by inheriting classes.") NotImplementedError: Must be implemented by inheriting classes. Does anyone have an idea on what I do wrong? -
CSRF verification failed while admin login in heroku
I've just deployed my Django website on Heroku but when I try to login into the admin panel, it throws me with the CSRF verification failed error. I have created a superuser using the heroku run python manage.py createsuperuser command. Any reasons for this error? -
<int:pk> not working inside router in Django REST framework
I've the following code inside urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import SentenceListViewSet, SentenceViewSet router = DefaultRouter() router.register('lists', SentenceListViewSet, basename='SentenceList') router.register('lists/<int:pk>/sentences/', SentenceViewSet, basename='Sentence') app_name = 'api_app' urlpatterns = [ path('', include(router.urls), name='lists') ] It's the second router registry that's causing problem. I get "page not found" if I navigate to localhost:8000/lists/8/sentences. However, I can access localhost:8000/lists/<int:pk>/sentences. How can I make DRF capture 8 as a URL parameter instead of int:pk getting treated as a literal part of the URL? -
HTTPConnectionPool(host='5001', port=80): Max retries exceeded
I am trying to build a simple blockchain application by referring to https://medium.com/@vanflymen/learn-blockchains-by-building-one-117428612f46 I have Successfully built the app and have tested it using different ports on the same machine, but I want to run the same with different devices on the network, as explained here I tried doing this by running the same application on a different device on the same network, and I am able to get responses when tried with the postman application but I am getting the Max retries exceeded error from line 83 of this when one application tries to connect with the endpoint of the other application Note that the same is working perfectly with ports running on the same device what am I doing wrong Thank you..! -
Multiple staff for company db design in django?
Lets say i have a predone django system in which there are 5 models. 1.User, 2.Agency, 3.Institution, 4.Application, 5.Students. By said that, this is how my system works. Agency or Institution can create new application using students and managet that, so each application record would have a foreign key to Agency or Institution. Now my problem is that, i have a new requirement by which each Agency or Institution can have one or more admin staffs under them. So they can login and do certain tasks and etcs. The problem comes here, how to share data Agency or Institution's data to the newly created staff ? As all the applications are linked with Agency or Institutions now how can a staff view all these ? Am totally stuck at this point, i need to create staff as users and also show only the applications belongs to the Agency or Institution they are owned by. Please suggest something, and i dont know what code to share so please bare with me. And also if you need any thing to share please comment - will update the question with need -
Django sorting and filtering objects in template based on url parameters
my problem is about sorting and filtering objects in .html template. I have both functions working but if I use one of them then second is not working. My template: <form action="{% url 'adverts' %}" method="get"> <div class="form_field"> <label for="formInput#search">Search Adverts</label> <input style="width: 400px;" class="input input--text" id="formInput#search" type="text" value="{{search_query}}" name="search_query" placeholder="Search by Adverts title, brand or description"> </div> </form> <main> <div class="search"> <h2>Number of adverts: {{num}}</h2> <form action="{% url 'adverts' %}"> <span>Sort by:</span> <select name="sort"> <option value="new">newest</option> <option value="old">older</option> <option value="price_low">price low</option> <option value="price_high">price high</option> <option value="mileage_low">mileage lowest</option> <option value="mileage_high">mileage higher</option> <input type="submit" value="Sort"> </select> </form> {% for advert in adverts %} <div class="mainAdvert"> <a href="{% url 'single-advert' advert.id %}"> <div class="row"> <div class="column"> <img src="{{ advert.featured_image.url }}" class="advertImage"> </div> <div class="column1"> <span class="titleAdvert"><b>{{advert.title}}</b></span> <ul> <li class="header">{{advert.year_of_production}}</li> <li class="header">{{advert.mileage}}km</li> <li class="header">{{advert.fuel_type}}</li> <li class="header">{{advert.variant}}</li> <li class="header">{{advert.created}}</li> </ul> <span class="location"><img class="address-icon" src="images/pin.png" alt="" /><b>Adres: </b>Rogowo, Poland</span> </div> <div class="column"> <span><h2 class="price">{{advert.price}}PLN</h2></span> </div> </div> </a> </div> {% endfor %} My views.py function: def adverts(request): page = 'adverts' adverts, search_query = searchAdverts(request) adverts = Advert.objects.all() sort_by = request.GET.get('sort') if sort_by == 'new': adverts = Advert.objects.all().order_by('-created') elif sort_by == 'old': adverts = Advert.objects.all().order_by('created') elif sort_by == 'mileage-high': adverts = Advert.objects.all().order_by('-mileage') elif sort_by == 'mileage-low': adverts … -
How to upload multiple images using CreateView in Django
I have a page, where user can create post. I want to give him a possibility to add multiple images to this post at the same page, but I don't know how to do it. There is my code: models.py class Blog(models.Model): ACTIVITY_CHOICES = [ ('active', 'Active'), ('inactive', 'Inactive') ] title = models.CharField(max_length=100, verbose_name='title') description = models.TextField(verbose_name='description') tag = models.CharField(max_length=50, verbose_name='tag') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='author') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) activity = models.CharField(max_length=10, choices=ACTIVITY_CHOICES, default='inactive') class Meta: verbose_name = 'post' verbose_name_plural = 'posts' def __str__(self): return self.title def get_absolute_url(self): return reverse('blog_detail', args=[str(self.pk)]) class Image(models.Model): blog = models.ForeignKey(Blog, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path) forms.py class BlogForm(forms.ModelForm): class Meta: model = Blog fields = '__all__' class ImageForm(forms.ModelForm): file_field = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': 'multiple'})) class Meta: model = Image fields = ('image', ) views.py class BlogCreateView(CreateView): model = Blog template_name = 'blog/create_blog.html' fields = ['title', 'description', 'tag'] def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) create_post.html <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>Create post</title> </head> <body> <h2>Create post</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="save">Create post</button> </form> </body> </html> I think models, forms and html are ok and all I need … -
after rename and many changes code was stop working - python django?
File "C:\Users\User\Desktop\microservice\project\app\urls.py", line 2, in from . import views File "C:\Users\User\Desktop\microservice\project\app\views.py", line 5, in from project.main import linkmaker ModuleNotFoundError: No module named 'project' I changed name of the project itself and entered the change where it was necessary, and also added get requests, after which django project stopped working views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib import messages from .forms import * from project.main import linkmaker from linkmaker import * from ..main.linkmaker import get_response def main(request): form_name = '' form_email = '' form_phone = '' if request.method == "POST": form = Form(request.POST) if form.is_valid(): ModelsForm.objects.get_or_create( name=form.cleaned_data['name'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'] ) messages.success(request, 'Form has been submitted') return redirect('/') # create a contact form # contact = [form['name'], form['email'], form['phone']] # create a... form_name = form.cleaned_data.get("name") form_email = form.cleaned_data.get("email") form_phone = form.cleaned_data.get("phone") contact = {'form': form, 'name': form_name, 'lastname': form_email, 'phone': form_phone} return render(request, contact) else: return HttpResponse("Invalid data") else: form = Form() return render(request, 'app/main.html', {'form': form}) def get_contact(request): if request.method == "GET": if get_response.status_code == "200": messages.success(request, 'Successful search') # return redirect('/') else: return HttpResponse("Invalid data") else: pass # add contact using request.method post with "https://letswritefuckingcode.amocrm.ru/api/v4/contacts" linkmaker.py import requests from requests import Response from project.app.views import main … -
Django/ HTML: Read more doesn't work on a main blog page
I am developing locally django page and have some issues when I click on "Read more" button. For post called "test" it is working fine, I putted there random text. for posts: "Projekty: API do spradzania pogody 2" and "Projekty: API do spradzania pogody " it doesn't work. I putted inside some yt links .When I click o "Read More" nothing happens. Also when I hover over button no link is shown. Do you know why I cannot click there? index.html: {% extends "base.html" %} {% block content %} <style> body { font-family: "Roboto", sans-serif; font-size: 18px; background-color: #fdfdfd; } .head_text { color: black; } .card { box-shadow: 0 16px 48px #E3E7EB; } </style> <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 mt-3 text-black"> Welcome to my awesome Blog </h3> <p class="text-light">We Love Django As much as you do..! &nbsp </p> </div> </div> </div> </div> </header> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p class="card-text">{{post.content|safe|slice:":200" }}</p> <a href="{% … -
GraphQL add json from related table as field in GraphQL query
I have a few tables - magic_sets, magic_sets_cards, magic_sets_tokens, magic_setssealed_products - the latter three tables all have foreign keys to a specific record in magic_sets table. I am trying to create a GraphQL schema to bring back a specific set along with its related cards, tokens and sealed_products. I have it so it brings back a specific set but the cards field is returning a error code: class MagicSetsIndividual(DjangoObjectType): cards = GenericScalar() class Meta: model = magic_sets fields = ['id', 'code', 'keyrune_code', 'release_date', 'non_foil_only', 'foil_only', 'digital', 'cards'] def resolve_cards(self, info, **kwargs): return magic_sets_cards.objects.filter(set_id=self).all() class MagicSetsIndividualQuery(graphene.ObjectType): magic_sets_individual_cards = graphene.List(MagicSetsIndividual, code=graphene.String()) def resolve_magic_sets_individual_cards(self, info, code=None, **kwargs): return magic_sets.objects.filter(code=code).all() query: { magicSetsIndividualCards(code: "SS1") { id code keyruneCode releaseDate nonFoilOnly foilOnly digital cards } } error: TypeError at /magic/api/v1/sets/individual/cards/\nObject of type QuerySet is not JSON serializable\n\nRequest Method: -
Django channels crashes whenever made a database call
I have this code and I am making a database call in the connect method. The code runs fine if I comment the database call async def connect(self): pk: int = self.scope['url_route']['kwargs']['pk'] params: str = self.scope['query_string'].decode("utf-8") email: str = params.split('=')[1] # self.project: Project = await self.get_project(pk) self.room_name = "Room name!" self.room_group_name = 'chat_%s' % pk await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() @database_sync_to_async def get_project(self, pk: int) -> Project: return Project.objects.filter(id=pk).first() Can someone help me with this ? Thanks in advance -
Get data from another table foreign key python
I have two tables called User and Duty. The common value in these two tables is account_id (for User) and ID (for Duty) I would like to get another value in table Duty called work_id. Should I use prefetch_related? User uid name last_name state account_id 1ldwd John Black active 123 2fcsc Drake Bell disabled 456 3gscsc Pep Guardiola active 789 4vdded Steve Salt disabled 012 Table Duty uid rate hobbie id work_id 1sdeed part football 456 007 3rdfd full hockey 789 022 45ffdf full regbie 123 4567 455ggg part fishing 012 332 -
django token authentication access the logged in user
how do i know a user is authenticated when i use token authentication?....i have tried accessing request.user and auth but it outputs anonymousUser.....when i set the authentication class to TokenAuthentication and permission class to isAuthenticated,and the URL endpoints as restframework.urls,i get a 401 "Authentication credentials were not provided" exception.....when i remove the TokenAuthentication settings,the app works perfectly....in short,i want to access the user logged in when i use token authentication method...thanks alot -
How get user's input from html form, and use it in my function in Django app
How do I get the user's input, and use it in my Python function? This button creates a PDF document. I need the name that the user enters to be added to this pdf file. -
: AttributeError: 'str' object has no attribute 'resolve' o
I am new to django i am using a mac os system , i am trying to do a simple hello world program in django framework The initial set up and launching works fine , but while creating a helloworld program by creating a new app and deploying it i am getting below error can some one help how to resolve this issue. **Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/ushanandhini/Desktop/djngo/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/ushanandhini/Desktop/djngo/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ushanandhini/Desktop/djngo/hello/views.py", line 8, in home return HTTPResponse("hello Nikhil") File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 256, in __init__ self.fp = sock.makefile("rb") Exception Type: AttributeError at / Exception Value: 'str' object has no attribute 'makefile' Thanks, Sid** -
Django testing models.py file
I am performing the Django for my models.py file Here is my models.py file import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) farm_health … -
How to import .py file from django's static dir from within a brython.html template?
Like the title says, I'm running a django webapp using Brython (NOT Javascript), hosted on Heroku, and would like to import a .py file located in the static folder. I am able to import and display the contents of the .py file, but when I try to import it, the webpage remains blank (white screen) with no errors (status 200). My debugging is possibly not developed enough to catch the error, but usually I will get a traceback when I have errors as debugging is on. So, the status 200 and blank white screen are important, I believe. Although debugging is not the subject of my post, any short insights into why I'm getting this result would be of interest. Here's the code I'm trying in the html template with a couple failing examples, and one suboptimal solution that does run mostly as hoped: <body onload="brython()"> <script type="text/python"> from browser import document, html # This line works and displays the contents of the .py file in browser, # used to rule out my staticfile options in settings document <= html.H1( open("{% static 'my_py_script.py' %}").read(), Id="main") # Here is one method I've tried that causes the browser to remain blank on … -
Django address city-district-neighbourhood choisefield
I have been trying to build a form in which can be chosen address city-district and neighborhood data according to city-district relation. For example when the user choose city then I want to see districts of the city. I am new at Django and coding and I've been searching and trying for a couple days. Here are my codes: Models.py: class Adresler(models.Model): il = models.CharField(max_length=50,verbose_name="il", null=True) ilçe = models.CharField(max_length=50,verbose_name="ilçe", null=True) mahalle = models.CharField(max_length=50,verbose_name="mahalle", null=True) PK = models.CharField(max_length=50,verbose_name="PK", null=True) def __str__(self): return self.mahalle class Fukara(models.Model): uyruk = models.CharField(max_length=50,verbose_name="Uyruk", null=True) kimlik_no = models.CharField(max_length=50,verbose_name="Kimlik No", null=True) ad_soyad = models.CharField(max_length=50,verbose_name="Ad Soyad", null=True) telefon = models.CharField(max_length=50,verbose_name="Telefon", null=True) meslek = models.CharField(max_length=50,verbose_name="Meslek", null=True) cinsiyet = models.CharField(max_length=50,verbose_name="Cinsiyet", null=True) yaş = models.IntegerField(verbose_name="Yaş", null=True) calisan_sayisi = models.IntegerField(verbose_name="Çalışan Sayısı", null=True) aylik_gelir = models.IntegerField(verbose_name="Aylık Gelir",null=True) durum= models.CharField(max_length=50,verbose_name="Durum", null=True) fert_sayisi = models.IntegerField(verbose_name="Aile Ferdi Sayısı", null=True) talep = models.CharField(max_length=150,verbose_name="Talepler", null=True) aciklama = models.CharField(max_length=150,verbose_name="Açıklama", null=True) adres_il = models.CharField(max_length=50, null=True,verbose_name="İl") adres_ilce = models.CharField(max_length=50, null=True,verbose_name="İlçe") adres_mahalle = models.CharField(max_length=50, null=True,verbose_name="Mahalle") adres_adres = models.CharField(max_length=50,verbose_name="Adres", null=True) kayit_eden = models.CharField(max_length=50,verbose_name="Kayıt Eden", null=True) kayit_tarihi = models.DateField(verbose_name="Kayıt Tarihi", null=True) dagitim_turu = models.CharField(max_length=50, verbose_name="Şahıs/Kurumsal", null=True) kurum_vergi_no = models.IntegerField(verbose_name="Vergi/Kimlik No", null=True) sorumlu_kisi = models.CharField(max_length=50, verbose_name="Sorumlu Kişi", null=True) il_listesi = models.ForeignKey(Adresler,on_delete=models.SET_NULL, null=True) def __str__(self): return self.kimlik_no "Adresler" class contains city-district-neighborhood data and in Fukara class adres_il …