Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing data from Django views to vue instance as JSON object
I have the following Django view method, being used to send information over to some Vue.js frontend code in details.html. I am basically wondering how do I send over the data to the vue template. How do I do JSON dumps? I think that is what I am messing up here. def works(request): heading_info = Heading.objects.order_by('-name')[:1] welcome_info = Welcome.objects.order_by('-title')[:1] skills_info = Skill.objects.order_by('position')[:5] projects_info = Project.objects.order_by('name')[:10] items = [] items.append({'heading_info':heading_info, 'welcome_info':welcome_info, 'path':path, 'path2':path2, 'skills_info':skills_info,'projects_info':projects_info}) # context = {} # context["items_json"] = json.dumps(items) context = {'heading_info':heading_info, 'welcome_info':welcome_info, 'path':path, 'path2':path2, 'skills_info':skills_info,'projects_info':projects_info} return render(request, 'home/details.html', context) And here is my html where I am trying to access this data. <script type='text/javascript'> var data = {{ projects_info|safe }}; </script> <div id="app"> [[projects_info_vue]] {% comment %} #Passing array as vue data. This gets rendered as QuerySet. How do I access these value in Vue. {% endcomment %} <div class="row"> {% for project in projects_info %} {% comment %} #Here is the array being rednered in Django. This array gets rendered as a QuerySet in Vue. {% endcomment %} <div class="col"> {{project.name}} </div> {% endfor %} </div> </div> <script> var app = new Vue({ delimiters: ["[[", "]]"], el: '#app', data: { projects_info_vue: '{{projects_info}}', }, }); </script> -
In django serializer response, how to get rid of absolute path (media_url prefix) for FileField?
I have used a models.FileField() in my model and I have created a simple ModelSerializer and CreateAPIView for it. As I am using AWS S3, when posting a file, I receive Json response that includes MEDIA_URL as prefix of filename i.e.: { "id": 32, "file": "https://bucket.digitaloceanspaces.com/products/capture_a50407758a6e.png" } What i would like to achieve instead is to either keep only a file name: { "id": 32, "file": "capture_a50407758a6e.png" } or to be able to change the prefix to some other: { "id": 32, "file": "https://google.com/capture_a50407758a6e.png" } The change should only be visible in Json response and and the database entry. The S3 details should be still sourced as they are from settings.py. Hope it makes sense. Let me know if anyone has any idea as I'm only able to find solution for providing full/absolute path. Thanks -
How to add images to individual model boxes?
So the problem am trying solve is how can I add images to separate model boxes? For example if I were to press on the Toyota Tacoma I would only see pictures of Toyota Tacoma and if I pressed on the Ford F-150 I would only see pictures of the Ford F-150. The closest I have gotten was getting the pictures to show up in the bottom of the model box but not in a separate one. function handleShowPopUp(e) { e.preventDefault() console.log(e) setSelectedPopUp(e.target.id) setShowPopUp(true) } const ref = useRef(null); useEffect(() => { function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target)) { setSelectedPopUp("") setShowPopUp(false); } } // Bind the event listener document.addEventListener("mousedown", handleClickOutside); return () => { // Unbind the event listener on clean up document.removeEventListener("mousedown", handleClickOutside); }; }, [ref]); const popUp = ( <div className="pop-up-wrapper"> <div className="pop-up-body" ref={ref}> <img src ={FordI}className="fordI" /> <img src ={FordI2}className="fordI2" /> <img src ={FordI3}className="fordI3" ></img> </div> </div> ) function chooseImage () { if (selectedPopUp === "toyotaTruck") { return(<img src={"toyota_truck"}></img>) } else if (selectedPopUp === "ford") { return(<img src={"ford"}></img>) } else if (selectedPopUp === "dodge") { return(<img src={"dodge"}></img>) } } const truckMenu = () => { return (<div><h1>Truck list - Ford F-150 Raptor</h1><img onClick={(e)=>handleShowPopUp(e)} id="Ford F-150 Raptor … -
Django: Creating multiple children at once on 1 parent
I'm having an issue passing several children OrderItem, a collection, when creating an Order parent instance. Although there a one to many relationship between Order and OrderItem models, I can't pass a list of children to the parent. What am I missing or doing wrong? Thanks for your responses! Here is an example of the request I try to make on this endpoint /api/orders/: { "bar_id": 2, "order_items":[ { "ref_id": 3 }, { "ref_id": 2 }, { "ref_id": 1 } ] } The error is as: { "order_items": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models from .model_order import * from .model_reference import * class OrderItem(models.Model): order_id = models.ForeignKey(Order, null=True, on_delete=models.CASCADE, related_name='order_items') ref_id = models.ForeignKey(Reference, null=True, on_delete=models.CASCADE, related_name='order_items') UPDATE: Here is the OrderViewSet: from rest_framework import viewsets from ..models.model_order import Order from ..serializers.serializers_order import * from rest_framework import permissions class OrderViewSet(viewsets.ModelViewSet): """ Order ViewSet calling various serializers depending on request type (GET, PUT etc.) """ queryset = Order.objects.order_by('id').reverse() # mapping serializer into the action … -
What is the better way to impleent sub menu in Django?
I want to make a page with a dynamically added list of children. Each child has its own list of events. An example is attached. I have a list of children and events. How to combine them? I tried to make tabs or a second menu. I mostly focused on the template. But have no idea how to make it work. I feel it should be done through views. Please share any idea in which direction to go. -
Celery - Received unregistered task of type 'core.tasks.scrape_dev_to'
Trying to get a celery-based scraper up and running. The celery worker seems to function on its own, but when I also run the celery beat server, the worker gives me this keyerror. File "c:\users\myusername\.virtualenvs\django-news-scraper-dbqk-dk5\lib\site-packages\celery\worker\consumer\consumer.py", line 555, in on_task_received strategy = strategies[type_] KeyError: 'core.tasks.scrape_dev_to' [2020-10-04 16:51:41,231: ERROR/MainProcess] Received unregistered task of type 'core.tasks.scrape_dev_to'. The message has been ignored and discarded. I've been through many similar answers on stackoverflow, but none solved my problem. I'll list things I tried at the end. Project structure: core -tasks newsscraper -celery.py -settings.py tasks: import time from newsscraper.celery import shared_task, task from .scrapers import scrape @task def scrape_dev_to(): URL = "https://dev.to/search?q=django" scrape(URL) return settings.py: INSTALLED_APPS = [ 'django.contrib.admin', ... 'django_celery_beat', 'core', ] ... # I Added this setting while troubleshooting, got a new ModuleNotFound error for core.tasks #CELERY_IMPORTS = ( # 'core.tasks', #) CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_BEAT_SCHEDULE = { "ScrapeStuff": { 'task': 'core.tasks.scrape_dev_to', 'schedule': 10 # crontab(minute="*/30") } } celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'newsscraper.settings') app = Celery('newsscraper') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() When I run debug for … -
DRF foreign key field is not showing when serializing object
I have a few models to represent a user. A user has a garden, a profile and a gardener_profile. When serialising the user objects, garden and profile are getting showed, but gardener_profile is not. All of them are one to one relations. Here is my user serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) garden = GardenSerializer(read_only=True) gardener_profile = GardenerProfileSerializer(read_only=True) class Meta: model = CustomUser fields = ['id', 'url', 'username', 'email', 'first_name', 'last_name', 'password', 'groups', 'profile', 'garden', 'gardener_profile'] extra_kwargs = {'password': {'write_only': True}} And here are the models: class CustomUser(AbstractUser): email = models.EmailField(unique=True) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) class Garden(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) grass = models.DecimalField(max_digits=6, decimal_places=2) terrace = models.DecimalField(max_digits=6, decimal_places=2) class GardenerProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) salary = models.DecimalField(max_digits=6, decimal_places=2) contract = models.FileField(null=True, blank=True) class WorkingHours(models.Model): gardener_profile = models.ForeignKey(GardenerProfile, related_name='working_hours', on_delete=models.CASCADE) weekday = models.IntegerField(choices=WEEKDAYS) from_hour = models.TimeField() to_hour = models.TimeField() class Meta: ordering = ('weekday', 'from_hour') unique_together = ('weekday', 'gardener_profile') -
Django expose session id when the site is being embedded inside an iframe
I have two django applications the first one expose a view: def render_demo_site(request: HttpRequest) -> HttpResponse: if not request.session.session_key: request.session.save() session_id = request.session.session_key return render(request, 'index.html', locals()) and the html: <html> <header> <title>DEMO</title> <script> const sessionID = '{{ session_id | safe }}'; console.log("sessionID", sessionID); </script> </header> <body> <h1> DEMO SITE </h1> <p>Session ID: {{ session_id }}</p> </body> </html> in the other Django application I have a site which expose a view where inside it's html I embed the other site inside an iframe: html: <html> <header> <title>DEMO</title> </header> <body> <iframe src="http://localhost:8005"></iframe> </body> </html> my goal is to extract the session id of the Django demo application in the later Django application Thanks -
How do I allow permissions so that i can run my python server?
I was trying to practice using django but when i tried to initially execute ' python3 manage.py runserver ' for some reason I received a permission denied when trying to run it and im not sure what that means, ive seen this before but im not sure how i would be able to allow permissions, i thought i enabled everything in start up but i feel as though i am missing something. I will post a picture here from when i went into the folder i started and tried to run the server. -
Why does Java script Self updating graph is not updating the plot?
I have written a code to plot a self-updating plot using JavaScript and Ajax, I am following this example (https://www.fusioncharts.com/charts/realtime-charts/speedometer-gague) and trying to implement in my project. The code I am using is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://epochjs.github.io/epoch/css/epoch.css" /> <link rel="stylesheet" href="https://epochjs.github.io/epoch/css/epoch.css" /> </head> <body> <div class="container"> <div id="chart-container"></div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- Latest compiled and minified CSS --> <!-- Latest compiled and minified JavaScript --> <script src="https://cdn.fusioncharts.com/fusioncharts/3.15.2/fusioncharts.js"></script> <script src="https://cdn.fusioncharts.com/fusioncharts/3.15.2/themes/fusioncharts.theme.fusion.js"></script> <script src="https://epochjs.github.io/epoch/js/epoch.js"></script> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> <script> FusionCharts.ready(function() { new FusionCharts({ type: "angulargauge", renderAt: "chart-container", width: "400", height: "300", dataFormat: "json", dataSource: { chart: { caption: "Fly Ash Generation Rate", subCaption: "Belews Creek Power Station<br>In Metric Tonnes", theme: "fusion", showValue: "1" }, colorRange: { color: [ { minValue: "0", maxValue: "0.4", code: "#62B58F" }, { minValue: ".40", maxValue: ".60", code: "#FFC533" }, { minValue: ".60", maxValue: "1", code: "#F2726F" } ] }, dials: { dial: [ { value: "0.6", toolText: "<b>$dataValue metric tonnes</b>" } ] } }, events: { initialized: function(evt, args) { var chartRef = evt.sender; function addLeadingZero(num) { return num <= 0.6 ? "0" + num : num; } function updateData() { $.ajax({ url:"{% url 'fetch_sensor_values_ajax' %}", success: function (response) … -
Django rest-auth How to get specific account user with user Token
the before response was: { key : Token } i want to change it to: { key : Token, username : username } but i have only the User Token and i can't figure out how to get the specific Account details I want to use Account.objects.get() but i have nothing except the Token my Account Model: class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30,primary_key=True, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) My Custom View response: class CustomLoginView(LoginView): def get_response(self): orginal_response = super().get_response() mydata = {"username": "TheUser_username"} orginal_response.data.update(mydata) return orginal_response Url: path('login/', CustomLoginView.as_view()), How do i get pass this? anyone? -
how to resolve SMTP error in pythonanywhere
i'm deploying my django project using pythonanywhere, in my code i will send an activation like to the user after he/she has opened an account, but that line isn't being run, i' getting an error which says: SMTPSenderRefused at / (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError q185sm6000383qke.25 - gsmtp', 'webmaster@localhost') -
django edit profile form does not save
The edit profile form does not save any data that is modified. i believe the problem might be with my get requests or my loops. No error shows on my terminal when i click add. it just redirects to the http response. I might be passing data wrongly also. ediprofile.html <form method="post">{% csrf_token %} {{form.first_name}} {{form.last_name}} {{form.email}} {{form.phonenumber}} {{form.state}} {{form.next_of_kin}} {{form.dob}} {{form.address}} <li class="btnn"><button type="submit" class="conf">Add</button></li> </form> <h1 class="cer">{{ form.errors.password1 }}{{form.errors.username}}{{form.errors.first_name}} {{form.errors.last_name}} {{form.errors.email}} {{form.errors.phonenumber}} {{form.errors.address}} {{form.errors.password2}} </h1> forms.py class EditProfileForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name') last_name = forms.CharField(max_length=100, help_text='Last Name') address = forms.CharField(max_length=100, help_text='address') next_of_kin = forms.CharField(max_length=100, help_text='Next of kin') dob = forms.CharField(max_length=100, help_text='Date of birth') state = forms.CharField(max_length=100, help_text='State') phonenumber = forms.CharField( max_length=100, help_text='Enter Phone number') email = forms.EmailField(max_length=150, help_text='Email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update( {'placeholder': ('Email')}) self.fields['address'].widget.attrs.update( {'placeholder': ('Address')}) self.fields['phonenumber'].widget.attrs.update( {'placeholder': ('Phone number')}) self.fields['first_name'].widget.attrs.update( {'placeholder': ('First name')}) self.fields['last_name'].widget.attrs.update( {'placeholder': ('Last name')}) self.fields['dob'].widget.attrs.update( {'placeholder': ('Date of birth')}) self.fields['state'].widget.attrs.update({'placeholder': ('State')}) self.fields['next_of_kin'].widget.attrs.update( {'placeholder': ('Next of kin')}) self.fields['first_name'].widget.attrs.update({'class': 'log'}) self.fields['last_name'].widget.attrs.update({'class': 'log'}) self.fields['email'].widget.attrs.update({'class': 'log'}) self.fields['phonenumber'].widget.attrs.update({'class': 'log'}) self.fields['address'].widget.attrs.update({'class': 'log'}) self.fields['dob'].widget.attrs.update({'class': 'log'}) self.fields['state'].widget.attrs.update({'class': 'log'}) self.fields['next_of_kin'].widget.attrs.update({'class': 'log'}) class Meta: model = User fields = ('first_name', 'last_name', 'phonenumber', 'email', 'address', 'dob', 'state', 'next_of_kin') views.py def edit_profile(request,id): profile = Profile.objects.get(user_id=id) user = get_object_or_404(Profile, pk=id, user=profile.user.id) if … -
Voice Modulator Using Django Framework
I want to make a voice modulator using python language. The backend framework i am using is django. But i am facing issue in finding an api written in python which could help me in integrate voice modulator in my platform. Or if no such api exists then can you please guide in how can i get started to make modulator. What stuff would be used?? -
How to get list of related object in annotion when using Greatest function in django models
I am having two models, a User model and a Payment model and there is on to many relationship between them. User has multiple Payments. What I am trying to achieve is sorting the User model as per the Payment's created_at field. I am trying to modify the Queryset and then I'll be using the annotated field latest_tran for sorting. def get_queryset(self, request): qs = super(ClubbedPaymentAdmin, self).get_queryset(request) qs = qs.annotate( latest_tran=Greatest(Payment.objects.filter(user=F('id')).values_list('created_at', flat=True))) return qs But I am having below error Greatest must take at least two expressions So it seems like I am making a mistake when evaluating the list of Payments. Or may be like I am taking a wrong approach. Any help would be much appreciated. Thank you. -
I am not able to run blockchain.py
I am new to flask . I am testing a blockchain that i found on github and i am facing this error: Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) [2020-10-04 21:37:54,221] ERROR in app: Exception on /mine_block [GET] Traceback (most recent call last): File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\T357\anaconda3\lib\site-packages\flask_compat.py", line 33, in reraise raise value File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\T357\Desktop\blockchain.py", line 84, in mine_block return jsonify(response), 200 File "C:\Users\T357\anaconda3\lib\site-packages\flask\json.py", line 251, in jsonify if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr: File "C:\Users\T357\anaconda3\lib\site-packages\werkzeug\local.py", line 347, in getattr return getattr(self._get_current_object(), name) AttributeError: 'Request' object has no attribute 'is_xhr' 127.0.0.1 - - [04/Oct/2020 21:37:54] "←[35m←[1mGET /mine_block HTTP/1.1←[0m" 500 - as you can see the error is AttributeError: 'Request' object has no attribute 'is_xhr' so can anyone lead me in the right direction ,i cant find a solution on my own. thanks -
Displaying 3 separate forms on the same page in django
So I'm working on a single page site which is to have 3 different forms on the same page. Tour form, flight form and bookform I created the forms using model form but how do I display the forms such that my site will know which form I'm submitting data to -
TemplateDoesNotExist at /groups/posts/in/first-post/ post/_post.html
I am following along on a tutorial (which is from two yrs ago so they are using an older version of django and python), i finished the blog, everything works fine, i can register, login, post a new forum, but when i click to see a blog post already created i get the error below. Overall, I'm not sure where the problem is, is it in in _post.html, views.py, models.py urls.py? TemplateDoesNotExist at /groups/posts/in/first-post/ post/_post.html here is my base.html: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Star Social</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> {# NOTE: To use the static, you must put the loadstatic files at the beggining #} <link rel="stylesheet" href="{% static 'simplesocial/css/master.css' %}"> </head> <body> {# mynav is my own class to setup my css#} <nav class="navbar mynav" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand mynav" href="{% url 'home' %}">Star Social</a> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'posts:create' %}">Post</a></li> <li><a href="{% url 'groups:all' %}">Groups</a></li> <li><a href="{% url 'groups:create' %}">Create group</a></li> <li><a … -
Value repeated inside get function in Django serializer
I try to get value from django serializer inside another serializer class to update it. Getting the value is done with serializers.SerializerMethodField() and get. But when I loop the Json value inside the API it returns too much queries (30 raws return 30 queries) I expected [1, 2, 3,] I have [1, 2, 3] [1, 2, 3] [1, 2, 3] The code: class SerializerA(serializers.ModelSerializer): dimension = serializers.SerializerMethodField() @staticmethod def get_dimension(self): list_apps = SerializerB.objects.values_list('list_apps', flat=True)[0] dim = [item['wth'] for item in list_apps] return dim class Meta: ... If I put list_apps and dim outside the def it works well. I don't know how to do (exit list_apps and dim outside the def or get I expected (one line)). Thanks ! -
Serialize relations in django
I have 2 models --> Candidate and Grade. 1 Candidate have many Grade. I want to return from rest API average grade from many grades that one Candidate can receive. How can I doing this. My model: class Candidate(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Grade(models.Model): value = models.IntegerField(blank=True, null=True) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='grades') My serializers.py from rest_framework import serializers from .models import Candidate, Grade class CandidateSerializer(serializers.ModelSerializer): pk = serializers.SerializerMethodField('get_pk_from_candidate') full_name = serializers.SerializerMethodField('get_full_name_from_candidate') grades = serializers.SlugRelatedField(many=True, read_only=True, slug_field='value') class Meta: model = Candidate fields = ['pk', 'full_name', 'avg_grade', 'grades'] def get_pk_from_candidate(self, candidate): return candidate.id def get_full_name_from_candidate(self, candidate): data = (candidate.first_name, candidate.last_name) full_name = ' '.join(data) return full_name I want my JSON format like below: { "pk": 3, "full_name": "rafał małek", "avg_grade": "", "grades": [ 12, 4, 13, 5 ] }, -
ModelForm has no model class specified.[django]
In my forms i have: class SignUpForm(UserCreationForm): username = UsernameField(label=_("Username"), widget=forms.TextInput(), ) email = forms.EmailField(max_length=254, label="Email", widget=forms.EmailInput(), validators=[EmailValidator]) class Meta: model = locate(settings.AUTH_USER_MODEL) <--- HERE fields = ("username", "email", "password1", "password2") in user app in models: class Profile(AbstractUser): def __str__(self): return self.username In my project settings.py I set up AUTH_USER_MODEL = 'user.Profile' And it gives me ValueError at /user/register ModelForm has no model class specified. When I change class Meta in my form to: class Meta: model = Profile <--- HERE Everything is OK. Why my model = locate(settings.AUTH_USER_MODEL) doesnt work? -
How to create a line chart indicating which month a user wrote more or less blogs?
This is how I want the output - According to the above chart, the user wrote lots of posts between March and April, and then in the month of July the number is decreased. I worked with tables and pie charts but couldn't make this one work. Here is a sample of the Django model can be used for this purpose: class Blog(models.Model): title = models.CharField(max_length=160) ... created_at = models.DateTimeField(auto_now_add=True) I know the data to be used here can be extracted from created_at field but I don't know how to do the JavaScript part. If I pass {"blogs": Blog.objects.all()} context in template how do I plot above like line bar. Please help. Thank You. -
How can I render new HTML content in Django template?
I'm a beginner in Django. In my template file, I have the following: <select id="selectbox"></select> <div id="containerdiv"></div> Within the containerdiv, I can return a HttpResponse such as: <form> <!-- some more input elements here --> </form> so now I will have a new form within the div. The content of the form will change depending on the value of selectbox. However, I also have {% csrf_token %} tag within the rendered HttpResponse which is not being rendered properly. Is this even the correct way to work with Django? -
Django+Channels+Heroku deployment with Daphne: Closing Postgre connections
My Django webapp deploys fine, however my db connections max out after a few queries to Postgres. Here is my understanding of my problem: Db connections to Postgres are opened for every query but not closed and this results is a db timeout once max connections is reached. Heroku documentation for this error, but I think that whatever new number of connections are enabled through an upgrade, those connections will also max out fast. (Or am I wrong?) pg:killall is not a solution to my problem. The solution must not be manual in this application. I have used Heroku documentation for Concurrency and DB connection in Django This SO question is related but answers don't solve my problem Debug error FATAL: too many connections for role "DB_username" Running heroku pg:info --app appname in cmd === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 20/20 <<<<<<<<<<<<<<<<<<<<< PG Version: 12.4 Created: 2020-09-11 16:57 UTC Data Size: 9.3 MB Tables: 15 Rows: 85/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-infinite-00894 Here are the things I have tried: setting dj_database_url.config(conn_max_age==0,...) Using Pgbouncer to pool connections Disabling server side cursors Settings.py # PRODUCTION SETTINGS MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware') DATABASE_URL = os.environ['DATABASE_URL'] DISABLE_SERVER_SIDE_CURSORS = True SECRET_KEY = … -
Object value is not showing in frontend (react js) | django
Though my code is working fine at backend. But can't figure out why data is not passing through react.js. Hopefully, it's just a simple error. Why these {this.state.article.title} and {this.state.article.content} values are not showing? view.js export default class ArticleDetail extends React.Component { state = { article: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`).then( res => { this.setState({ article: res.data }); } ) } render (){ return ( <div> <Card title={this.state.article.title}> // it's not showing <p> {this.state.article.content} </p> // it's not showing </Card> <CustomForm/> </div> ) } } models.py class Article(models.Model): title = models.CharField(max_length=20) content = models.TextField()