Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Ajax no refresh
I have been trying to develop a form within detailview, which I did. Now I would like it to send data to the database and to display the new data on the same page without refreshing. So I found a way to send the data to the database without refreshing, however, when it comes to display the new data without refreshing it does not work. I followed this tutorial : tutorial from red eye coder club Here is my code. models.py class ImportantFacts(models.Model): collection_important_facts = models.ForeignKey(Collection, related_name="has_important_facts", on_delete=models.CASCADE, null=True) note = models.TextField(max_length=400, verbose_name='Note') forms.py class ImportantFactsForm(forms.ModelForm): class Meta: model = ImportantFacts fields = ['note'] views.py class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView): model = Collection form_class = ImportantFactsForm template_name = 'taskflow/collection_detail.html' success_url = None def get_context_data(self, **kwargs): context = super(CollectionDetail, self).get_context_data(**kwargs) context['important_facts'] = ImportantFactsForm() return context def post(self, request, *args, **kwargs): form = ImportantFactsForm(request.POST) tgt = self.get_object() if form.is_valid(): new_fact = form.save(commit=False) new_fact.collection_important_facts = tgt new_fact.save() return JsonResponse({'fact': model_to_dict(new_fact)}, status=200) else: return redirect('taskflow:collection_all') facts.js $(document).ready(function(){ $(".btn").click(function() { var serializedData = $("#createFactForm").serialize(); $.ajax({ url: $("createFactForm").data('url'), data: serializedData, type: 'post', success: function(response) { $("#canal1").append('<div class="card mb-1"><div class="card-body">' + response.fact.note + '<button type="button" class="close float-right"><span aria-hidden="true">&times;</span></button></div></div>') } }) $("#createFactForm")[0].reset(); }); }); collection_detail.html <div class="tab-pane active" id="Canal1"> … -
Replace image on mouse click using jQuery and Django doesn't work
so I want to replace an image when it is clicked using jQuery. Here is how my code looks like. HTML {% load static %} <div class="col-md-6 image"> <img class="map" src="{% static 'home/map.png' %}" class="doctors"> </div> jQuery $(document).ready(function() { $('.map').click(function() { $(this).attr("src", "{% static 'home/map2.png' %}"); }); }) I tried the code above and it didn't work. The location of the image and its image format is already correct but when I click the image it only shows a blank picture (the same display as when we write the wrong image format). I already tried to change the jQuery into this one too $('.map').click(function() { $(this).attr("src", "home/map2.png"); }); but it still didn't work. Anyone knows how to fix it? -
Input Type for ManyToMany Field with Graphene in Django
I am getting error when try Mutation on graphiql: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. How can i set it, what should i write for category = in types.py in InputObjectType based QuestionInput class? My files are below: models.py from django.contrib.postgres.fields import ArrayField from django.db import models from ..common.models import CommonFields from ..kategoriler.models import Kategori class Question(CommonFields): question = models.TextField() answer = ArrayField(models.TextField()) rightAnswer = models.TextField() category = models.ManyToManyField("Kategori") DIFFICULTY_CHOICES = ( ('Easy', 'easy'), ('Medium', 'medium'), ('Hard', 'hard'), ('Very Hard', 'very hard'), ) difficulty = models.CharField(max_length=10, choices=DIFFICULTY_CHOICES, default="medium") def __str__(self): created_at = self.created_at.strftime("%b %d %Y %H:%M:%S") return f"Q : {self.question[:7]} , Created at : {created_at}" types.py import graphene from graphene import relay, ObjectType, InputObjectType from graphene_django import DjangoObjectType from ..models import Question class QuestionNode(DjangoObjectType): class Meta: model = Question filter_fields = [] interfaces = (relay.Node, ) class QuestionInput(InputObjectType): question = graphene.String(required=True) answer = graphene.String(required=True) rightAnswer = graphene.String(required=True) category = graphene.????????? difficulty = graphene.String(required=True) create_question.py import graphene from graphene import relay from ...models import Question from ..types import QuestionNode, QuestionInput class CreateQuestion(relay.ClientIDMutation): class Input: question_inputs = graphene.Field(QuestionInput) question = graphene.Field(QuestionNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): question = Question.objects.create(**input.get("question_inputs")) question.save() return CreateQuestion(question=question) -
Why django geo map not working correctly?
I have already installed django ,postgresql, postgis, Qgis and GDAL Map show like this. Nothing to show on the map at models.py: from django.contrib.gis.db import models class Shop(models.Model): name = models.CharField(max_length=200) location = models.PointField() address = models.CharField(max_length=200) city = models.CharField(max_length=50) at setting.py: try: import gdal gdal_path = Path(gdal.__file__) OSGEO4W = os.path.join(gdal_path.parent, 'osgeo') os.environ["OSGEO4W_ROOT"] = OSGEO4W os.environ["GDAL_DATA"] = os.path.join(OSGEO4W, "data", "gdal") os.environ["PROJ_LIB"] = os.path.join(OSGEO4W, "data", "proj") os.environ["PATH"] = OSGEO4W + ";" + os.environ["PATH"] GEOS_LIBRARY_PATH = str(os.path.join(OSGEO4W, "geos_c.dll")) GDAL_LIBRARY_PATH = str(os.path.join(OSGEO4W, "gdal301.dll")) except ImportError: GEOS_LIBRARY_PATH = None GDAL_LIBRARY_PATH = None if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] -
SimpleLazyObject instead of User in re-usable Django app?
I used user model User in my Django app in filter or create queries like that: # FILTER queries self_posts = ( Post.objects .prefetch_related('stage') .filter(Q(stage__assignee__isnull=False, stage__assignee=request.user)) .exclude(stage__slug__in=['vault', 'published']) ) ... # CREATE one if form.is_valid(): post = form.save(commit=False) post.editor = request.user post.save() Then I packaged my app into re-useable Django module. As my User has several additional fields and methods compared to standard Django one, I created a proxy model. In my package it points to my local proxy model, but has access to actual "global" user, provided by main app auth system: class User(UserModel): # Proxy user model in packaged app class Meta: proxy = True class Meta: permissions = ( ("manage_authors", "Can manage authors"), ) ... Since that, inside my packaged app views I can't assign request.user directly to User-like fields, but still can use in filter queries. (Pdb) request.user <SimpleLazyObject: <User: koowpjcs>> (Pdb) request.user.user <User: John Doe> So, Post.objects.filter(foo=request.user) will still work, but post.editor = request.user wiil fail: Cannot assign "<SimpleLazyObject: <User: koowpjcs>>": "Post.editor" must be a "User" instance. Why it happend? Is it realated to re-usable app or with defining custom proxy model? Is it correct to replace all calls of request.user to request.user.user in re-usable … -
Django Documentation Tutorial NoReverseMatch at /polls/1/results/
Please help me, I'm new to django and I have error like this: """Reverse for 'vote' with no arguments not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']""" In polls.views def vote(request, question_id): question = get_object_or_404( Questions, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{'question':question, 'error_message':"You didn't select a choice."} ) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Questions, pk = question_id) return render(request,'polls/result.html',{'question':question}) polls url_patterns urlpatterns = [ path('',views.index,name='index'), path('<int:question_id>/',views.details, name='details'), path('<int:question_id>/results/',views.results, name='results'), path('<int:question_id>/vote/',views.vote, name='vote') ] And polls/result.html <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}} -- {{choice.votes}} votes {{choice.votes|pluralize}}</li> {% endfor %} </ul> <a href="{% url 'polls:vote' %}">Vote Again?</a> -
Required attribute is not working Djnago Template
Here, I am trying to build a quiz website. I want, all answers must be submitted. But the required attribute is not working. <section class="allquiz"> <div class="sectionarea"> <form action= '' method = "POST" > {% for question in questions %} <div class = 'question'>Q{{ question.question_name }} </div><br> <div id= "choices" class='select' required> <input type = "radio" name="{{forloop.counter}}" value="A{{question.pk}}">{{question.option_a}}<br> <input type = "radio" name="{{forloop.counter}}" value="B{{question.pk}}">{{question.option_b}}<br> <input type = "radio" name="{{forloop.counter}}" value="C{{question.pk}}">{{question.option_c}}<br> <input type = "radio" name="{{forloop.counter}}" value="D{{question.pk}}">{{question.option_d}}<br> </div> <br> {% endfor %} <div style="text-align:center"> <input style="padding: 10px 35px;font-size:120%;cursor: pointer;" type="submit" class="submit" id="submit" value="Submit"/></div> {% csrf_token %} </form> </div> -
IF clause in Django filter
I'm having a trouble on how can I translate my query to Django format, The problem is I'm wondering if it is possible to have a if clause inside Django queries, So I have this format , Is there any expert can help me with this format. query SELECT paid_by, IF(paid = 'Yes' || paid = 'YES', 'paid', 'unpaid') as paided, category, category_status, count(paid) FROM `app_person` What I tried app_person.objects.filter((paid = 'Yes' ||paid = 'YES', 'paid', 'unpaid')as 'paided', 'category', 'category_status', 'count(paid)') -
Unable to authenticate custom user in Django 3
I am unable to authenticate custom user in django==3.1.3 Here is Custom User Manager: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError(_('Users should have a username.')) if email is None: raise TypeError(_('Users should have a Email.')) user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError(_('Password should not be empty.')) user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user Here's the CustomUser model: from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import CustomUserManager class CustomUser(AbstractBaseUser): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email I have added AUTH_USER_MODEL = 'authentication.CustomUser' in settings.py (authentication is the app name) In the shell, if I run these, I get authenticated_user as None: user = CustomUser.objects.create(email='tejas@gmail.com', username='tejas12', password='tejas12') authenticated_user = authenticate(email='tejas@gmail.com', username='tejas12', password='tejas12') However, the User gets created successfully with given details. Also, check_password returns False: from django.contrib.auth.hashers import check_password user.check_password('tejas12') # returns False … -
Parsing returned json from Django async rest call
I am in process of learning Django to build a smaller application that consumes a swagger REST API. When I am testing the API, I get a lot of JSON output, that I need to take, filter(change values) and send back via PUT, POST (typical stuff.) I have tried the async client sessions with return of json_response like this: async def get_some_jsonrest_value_back(response): async with ClientSession() as session: async with session.get('http://example.com', headers={'X-API-KEY':' fdfsdfdfff', 'Content-Type':'application/json'}, json={}) as resp: response = await resp.json() return json_response(response, text=None, body=None, status=200, reason=None, headers=None, content_type='application/json') I do get the values like these: { "key1": "values1", "key2": { "@subkey1": "54534543", "@subkey2": "fdsfdsfdsf", "subkey3": [ "fdsfsdfdsf" ], "subkey4": "fdfsdfds", "subkey5": "8594593489" }, "key3": "8594859438594385943", "key4": "kfdlskfldsk" } And the values grow, with many sections of that JSON output. There can be like hundreds of those JSONs. My question would be , if someone could point me to some examples of django code, which consumes API, returnes the JSON values and for an example takes out only the subkeys from 1 to 5 (like in json example in output). After that it changes the values and returns back to the external REST API via POST/PUT. Thanks in advance. -
Reading .sql with python and using data
I am completely new to SQL, but I know Python a little. I just programmed Version 2 of another 10 years old project of mine. The old project has a .sql file. For the new project, I made same alterations in the database. Now to test it, I want to read the old .sql file, make some calculations with it's data and populate the new database with the old data and the newly made calculations. How is it best done? (I don't know wheter it makes a difference, but it's a django project and there I use an .sqlite3 at the moment.) -
Django Query Works on python shell but it didnt work in template and forms
i tried the same code on forms in shell. the code working like i want. but when it deploy from Forms.py to html template instead become [models_name].objects.all() in forms.py main_page_choices = MainPage.objects.filter(parent_check=2).values_list('id', 'page_link') main_page_choices_list = [] for main_page in main_page_choices: main_page_choices_list.append(main_page) class AdminCreateSubPageForm(forms.ModelForm): class Meta: model = SubPage fields = ( 'sub_title', 'sub_title_tag', 'sub_page_link', 'body', 'parent_page', 'meta_keyword', 'meta_description') widgets = { 'sub_title': forms.TextInput( attrs={'class': 'form-control', 'id': 'sub_title', 'onchange': 'autotypelink()'}), 'sub_title_tag': forms.TextInput(attrs={'class': 'form-control', 'id': 'sub_title_tag'}), 'sub_page_link': forms.TextInput(attrs={'class': 'form-control', 'id': 'sub_page_link'}), 'body': forms.Textarea(attrs={'class': 'form-control', 'id': 'body'}), 'parent_page': forms.Select(choices=main_page_choices_list, attrs={'class': 'form-control', 'id': 'parent_page'}), 'meta_keyword': forms.Textarea(attrs={'class': 'form-control', 'id': 'meta_keyword', 'rows': '4'}), 'meta_description': forms.Textarea(attrs={'class': 'form-control', 'id': 'meta_description', 'rows': '4'}), } my models.py class MainPage(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) category = models.ForeignKey(Category, default="", on_delete=models.CASCADE) parent_check = models.ForeignKey(ParentCheck, default="", on_delete=models.CASCADE) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) USERNAME_FIELD = 'user' REQUIRED_FIELDS = [] def __str__(self): return self.page_link def get_absolute_url(self): return reverse("main-list-admin") class SubPage(models.Model): sub_title = models.CharField(max_length=255) sub_title_tag = models.CharField(max_length=255) sub_page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) parent_page = models.ForeignKey(MainPage, default="", on_delete=models.CASCADE) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) USERNAME_FIELD = … -
I am new to python and django when I try to migrate my file i am receiving error
from django.db import models class employees(models.Model): GENDER_CHOICES= [ ('M,''Male'), ('F',"Female"), ] first_name= models.CharField(max_length=100) last_name=models.CharField(max_length=1000,blank=True) email_id =models.EmailField(max_length=255) phone_nuber = models.CharField(max_length=10) employees_gender = models.CharField(choices=GENDER_CHOICES,max_length=1) employees_address= models.TextField() employees_job=models.ManyToManyField('availableJobs',blank=True) date_of_birth= models.DateField() class availableJobs(models.Model): name = models.CharField(max_length=100) Received the following error: ERRORS: employees.employees.employees_gender: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. -
Change download location to "Downloads" in Pytube in Python
I want to change the download location to "Downloads" in pytube in Python. Can anyone tell me how to do this? Thanks in advance:) -
'ReturnList' object has no attribute 'get' in django restframework
I'm trying to create a custom render method in DRF , here are my code : serializers class SupplierSerializer(serializers.ModelSerializer): class Meta: model = models.Supplier fields = [ # "plan", "type", "created", "id", "name", "bio", "established", "logo", "last_updated", "is_active", "date_to_pay", "mobile", "password", ] the Renderer class ApiRenderer(BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, accepted_media_type=None, renderer_context=None): response_dict = { 'status': 'failure', 'data': {}, 'message': '', } if data.get('data'): response_dict['data'] = data.get('data') if data.get('status'): response_dict['status'] = data.get('status') if data.get('message'): response_dict['message'] = data.get('message') data = response_dict return json.dumps(data) settings RENDERER_CLASSES = ( 'market_control_panel.renderers.ApiRenderer', ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # <-- And here 'rest_framework.authentication.TokenAuthentication', # <-- And here ], # testing ftp upload after comment 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_RENDERER_CLASSES': RENDERER_CLASSES, } But I get this error when I try to open any API link : 'ReturnList' object has no attribute 'get' -
Is there a way to know if a website is in development mode or production mode in Django?
Because when in development and production, the setting file has to be so much different For example Development: DEBUG = true ... ALLOWED_HOSTS = [] ... EMAIL_PAGE_DOMAIN = 'http://127.0.0.1:8000' Production: DEBUG = false ... ALLOWED_HOSTS = ['example.com'] ... EMAIL_PAGE_DOMAIN = 'https://example.com' I don't know if there is a condition to check if the app is in development mode or production mode so that I don't hard-code it. The code should change automatically based on its mode. I imagine something like this if in-development-mode() == true: #code for devopmenet else: #code for production -
How to make video storage in django using youtube videos?
I am developing video content project, where videos are paid. when user pay for video, the videos should be available to users, otherwise videos are not available. Is it possible to use Youtube as video storage. I read about django-embed-video library, maybe it is for only public videos, my videos are private. When user buys video, then video should available for that user. -
Create an instance from TextInput in CreateView
I know the tittle doesn't make much sense, bear with me I can find shorter way to describe my problem. models.py class Aurthor(models.Model): name = models.CharField("Author Name", max_length=100) def __str__(self): return self.name class Article(models.Model): title = models.CharField("Title", max_length=100) content = RichTextField(blank=True, null=True) pub_date = models.DateTimeField("Publish Date", auto_now_add = True) aurthor = models.ForeignKey(Aurthor, on_delete=models.CASCADE) def __str__(self): return self.title Article has a foreign key Aurthor so in my html when creating an article select will be used, but I don't want to select from Aurthors, I want to input type='text' then use that input to create an Aurthor instance. Like the way I have don it here: views.py def blog(request): articles = Article.objects.all() context = { 'date': datetime.timetuple(datetime.now()).tm_year, 'articles': articles } if request.method == 'POST': aurthor = Aurthor(name=request.POST['aurthor_name']) article = Article(title=request.POST['article_title'], content=request.POST['article_content'], pub_date=str(datetime.now().date()), aurthor=aurthor) aurthor.save() article.save() blog.html <form action="" method="post"> {% csrf_token %} <h3>Write an Article here.</h3> <label for="article_title">Title</label> <input type="text" name="article_title" required> <textarea name="article_content" id="article_content" required></textarea><br /> <label for="aurthor_name">Aurthor Name</label> <input type="text" name="aurthor_name" required> <button type="submit">Post</button> </form> This works well, now the question is that I want to do this but using CreateView as my class based view and Django forms.py -
I am working on a django project. and my loops are iterating two times but I only want it to iterate one time
.I've used loops to display data from database.I want the contents of two tables to display next to each other in a card so I used two loops that is a loop within a loop {%for plan in plans%} {%for natural in naturals%} Card title Some quick example text to build on the card title and make up the bulk of the card's content. Go somewhere {{plan.name}} {{natural.name}} {{natural.amount}} function createPaymentParams() { // Create payment params which will be sent to Flutterwave upon payment {% autoescape off %} let pay_button_params = JSON.parse('{% if user.is_authenticated %}{% pay_button_params user_pk=user.pk plan_pk=plan.pk %}{% endif %}'); {% endautoescape %} paymentParams['{{ plan.name }} '] = { public_key: pay_button_params.public_key, tx_ref: pay_button_params.tx_ref, amount: '{{plan.amount}} ', currency: '{{plan.currency}}', redirect_url: pay_button_params.redirect_url, payment_plan: '', payment_type:'', customer: { email: '{{ user.email }}', name: '{{ user.first_name }} {{ user.last_name }}', }, customizations: { title: '', logo: 'https://edoctorug.com/static/img/edoctor.png', }, } } if ('{{ user.is_authenticated }}' === 'True') { createPaymentParams(); } {% if user.is_authenticated %} {{ plan.pay_button_text }} {% else %} User must be signed in {% endif %} function createPaymentParams() { // Create payment params which will be sent to Flutterwave upon payment {% autoescape off %} let pay_button_params = JSON.parse('{% if user.is_authenticated %}{% … -
When trying to use export as csv i get only id
I am using django export as CSV, i have this model: class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() disc_price = models.IntegerField(null=True, blank=True) date = models.DateTimeField(blank=True, null=True, auto_now_add=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE, null=True, blank=True) total = models.IntegerField(null=True, blank=True) transaction_id = models.CharField(max_length=255, blank=True, null=True, unique=True) i get everything but I am getting product id and order status id Here I want product name status name but I am getting product ID, status ID def export_orders(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Orders.csv"' writer = csv.writer(response) writer.writerow(['id', 'Customer', 'Full Name', 'Phone Number', 'address', 'product', 'quantity', 'price', 'total', 'Payment Status', 'Order Status']) orders = Order.objects.all().values_list('id', 'customer', 'fname', 'phone', 'address', 'product', 'quantity', 'price', 'total', 'status', 'order_status') for order in orders: writer.writerow(order) return response -
Field 'id' expected a number - Uploading ForeignKey to django-import-export
I am trying to import data from an csv file into a django db using django-import-export. My problem is trying to upload data with a ForeignKey as an object. I have migrated, followed docs, and still no solution. You can see my error below in the django admin: Here is my csv data with a blank 'Id' column: models.py from django.db import models from django.shortcuts import reverse from urllib.parse import urlparse class States(models.Model): name = models.CharField(max_length=96, blank=False, unique=True) abbrv = models.CharField(max_length=2, null=True, blank=True) class Meta: ordering = ['name'] verbose_name = 'State' verbose_name_plural = 'States' def __str__(self): return f'{self.name}' class Person(models.Model): last_name = models.CharField( max_length=255, help_text="Enter your last name.") first_name = models.CharField( max_length=255, help_text="Enter your first name or first initial.") address = models.CharField( max_length=255, blank=True, help_text="Enter your street address.") city = models.CharField( max_length=255, blank=True, help_text="Enter your city.") state = models.ForeignKey('States', to_field='name', on_delete=models.SET_NULL, null=True) zipcode = models.CharField(max_length=50) website = models.URLField( max_length=255, blank=True) profession = models.CharField(max_length=50, blank=True) # META CLASS class Meta: verbose_name = 'Person' verbose_name_plural = 'Persons' ordering = ['last_name', 'first_name'] # TO STRING METHOD def __str__(self): """String for representing the Model object.""" return f'{self.last_name}, {self.first_name}' admin.py: from django.contrib import admin from .models import Person, States from import_export.admin import ImportExportModelAdmin from import_export.widgets … -
Transferring 100+GB of data from a database table to UI using Django ReST apis
I am trying to show data in React UI from a database using Django ReST APIs. Since my table has more than a billion rows, I can't fetch all the data at once and keep it into memory. I can only display 10-20 rows at a time. While user scrolling down I would like to call apis to fetch the data(Approximately for every 200 rows I will call an API). In this case, I can achieve it by setting chunk_size in pandas using SQLAlchemy. In order to get next set of data the python session shouldn't be closed. But according to my knowledge, the python session is persistent to each API. But, I want to share same python session for multiple APIs. Kindly help me to handle this situation. -
Django - Customize Form, Specifically how fields look
I have a form class which has several fields. One of them is the first and last name field. My goal is to modify my form in my html file so that it can take in input and pass it into a model object. However, I want this to not change how my form displays. The problem is that the fields show up differently when I use django's template language. I tried to modify the first name field with django's template language by replacing the following bootstrap code with django template language code: <div class="form-group col-md-12"> <label for="{{ form.first_name.id_for_label }}">First Name</label> <input type="text" class="form-control" id="first_name" placeholder="Ex. John"> </div> has been changed to: <div class="form-group col-md-12"> {{ form.first_name.label_tag }} {{ form.first_name }} </div> This does not work. I want the first name field to display the same as the last name field. How can I do this? My full code right now: <div class="form-row"> {{ form.first_name.errors }} <div class="form-group col-md-12"> <!--<label for="{{ form.first_name.id_for_label }}">First Name</label>--> <!--<input type="text" class="form-control" id="first_name" placeholder="Ex. John">--> {{ form.first_name.label_tag }} {{ form.first_name }} </div> </div> <div class="form-row"> <div class="form-group col-md-12"> <label for="last_name">Last Name</label> <input type="text" class="form-control" id="last_name" placeholder="Ex. Doe"> </div> </div> -
Create model instance on subclassing
Prerequisite I want to implement abstract inheritance: class Base(models.Model): title = models.CharField() slug = models.SlugField() description = models.TextField() class Meta: abstract = True class ChildA(Base): foo = models.CharField() class ChildB(Base): bar = models.CharField() For multiple reasons I need a db representation of hierarchy of these classes. So I want to create a model like this one (left and right attributes allow us to identify instance's place in the node tree): class Node(models.Model): app_label = models.CharField() model_name = models.CharField() parent = models.ForeignKey('self', blank=True, null=True) right = models.PositiveIntegerField() left = models.PositiveIntegerField() The Problem I need something similar to this: class Base(models.Model): ... def __init_subclass__(cls): app_label = cls._meta.app_label model_name = cls._meta.model_name parent_id = ? # I am not sure how do we get parent's id for now, but it should be manageable obj = Node.objects.create('app_label'=app_label, 'model_name'=model_name, 'parent'=parent_id) obj.save() So, as we subclass an abstract model, a new node is created that represents this new model in the hierarchy tree. Unfortunately, it won't work. It seems __init_subclass__ is invoked before Model class is properly initialized, so cls._meta.model_name will return incorrect value (parent's model_name, in fact). Can we bypass this (or use some other hook)? Other concerns I am not sure if this whole idea … -
Overriding save method doesnt work Django
My goal was to autocomplete the reservation_days field based on the initial_day and days_delta fields so that the reservation_days field contains a list of dates from initial_day to days_delta models.py from django.db import models from django.contrib.auth import get_user_model from datetime import datetime, date, timedelta User = get_user_model() class Office(models.Model): workplaces = models.IntegerField(verbose_name='number of workplaces') price = models.IntegerField(verbose_name='full office price') class Workplace(models.Model): price = models.IntegerField(verbose_name='workplace cost') office = models.ForeignKey(Office, verbose_name='workplace location', on_delete=models.CASCADE, null=True) class Reservation(models.Model): RESERVATION_TYPES = ( ('office', 'office'), ('workplace', 'workplace') ) reservation_type = models.CharField(verbose_name='reservation type', choices=RESERVATION_TYPES, max_length=9) offices = models.ForeignKey(Office, verbose_name='offices for reservation', on_delete=models.CASCADE, null=True) workplaces = models.ForeignKey(Workplace, verbose_name='workplaces for reservation', on_delete=models.CASCADE, null=True) initial_day = models.CharField(verbose_name='days delta initial day', max_length=10, default='123') days_delta = models.IntegerField(verbose_name='days delta', null=True) reservation_days = models.CharField(verbose_name='list with reservation days', max_length=1000) def save(self, *args, **kwargs): for delta in range(2): self.reservation_days += ',' + date.isoformat(date.fromisoformat(self.initial_day) + timedelta(days=1)) super(Reservation, self).save(*args, **kwargs) user = models.ForeignKey(User, verbose_name='owner', on_delete=models.CASCADE) but when i send the request i get { "reservation_days": [ "This field may not be blank." ] } or { "reservation_days": [ "This field is required." ] }