Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AbstractModel Inheritance and migrations
Want to clarify my understanding of Django abstract model inheritance and migrations since I've had difficulty finding clear documentation on this. Say I've got a package pckg.app.models defining an AbstractModel: class AbstractObj(models.Model): name = CharField(max_length=100) class Meta: verbose_name = _("Obj") abstract = True def __str__(self): return str(self.label) It is possible to change the name field via inheritance? Or could that package be imported so the 'name' field can be migrated and changed? In my app's models.py, if I import and subclass it: from pckg.app.models import Obj Class NewObj(Obj): name = CharField(max_length=200) def __str__(self): return self.label this would create a migration such as: from __future__ import unicode_literals from django.db import migrations, models from forms_builder.forms import fields import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('foo', 'bar'), ] operations = [ migrations.CreateModel( name='NewObj', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=200)), ], ), ] but this won't work because NewObj is an instance of Obj, not Obj: django.core.exceptions.FieldError: Local field 'name' in class 'NewObj' clashes with field of the same name from base class 'Obj' is there a way to migrate or change AbstractObj without defining it within my Django app and creating the dedicated … -
Django - How to get self.id instance when creating new object
I am working with two classes, when i save the first one it will automatic create the other one, the field called "transaction" should be filled by self.id. But i get this error message: NOT NULL constraint failed: portfolios_portfoliotoken.transaction_id this is the code that i am using: PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl+last.total_today_brl, order_value=self.total_cost_brl) More details is possible to see below: class Transaction(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(("Date"), default=date.today) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) total_cost_brl = models.FloatField(editable=False) ... def save(self, *args, **kwargs): self.share_cost_brl = round(self.share_cost_brl, 2) self.total_cost_brl = round(self.shares_amount * self.share_cost_brl, 2) ... PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl+last.total_today_brl, order_value=self.total_cost_brl) super(Transaction, self).save(*args, **kwargs) class PortfolioToken(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) total_today_brl = models.FloatField() order_value = models.FloatField() date = models.DateField(("Date"), default=date.today) ... -
How can I add a mimetype?
I am building a web app that allows users to upload files. I wanted to restrict the mimetype so users can only upload audio files. However, the site cannot accept .amr files. How can I add amr files? ''' if form.is_valid(): #validate file file = request.FILES['file'] valid_mime_types = ['audio/AMR','audio/amr-wb+','audio/mpeg','video/mp4','audio/AMR-WB','audio/amr','Audio/Amr',] file_mime_type = magic.from_buffer(file.read(1024), mime=True) if file_mime_type not in valid_mime_types: raise ValidationError('Unsupported file type.') valid_file_extensions = ['.amr','.mp4','.AMR','.mp3'] ext = os.path.splitext(file.name)[1] if ext.lower() not in valid_file_extensions: raise ValidationError('Unacceptable file extension.') #save the file instance = MyModel(upload=request.FILES['file']) instance.save() return HttpResponseRedirect('/somewhere/') ''' Other file types work fine, but this isn't working. -
How to add choice field in UserCreationForm
I am trying to ask (with the forms.Select maybe) whether the user is a Korean student or an international student when the user is registering. I have tried other answers to similar questions but did not work well. Maybe it is because of the User class definition. How do I add it? This is how my User class is defined: from .models import User Choices = (('I', "International"), ('K', "Korean")) User.add_to_class('scheduleData',models.ManyToManyField(UserSelect, blank=True)) User.add_to_class('lang',models.CharField(max_length=2, default="EN")) User.add_to_class('you_are',models.CharField(max_length=1, choices=Choices, default=False)) And this is how my NewUserForm is defined: (It shows "You are:" with nothing on the right side in the page) class NewUserForm(UserCreationForm): Choices = (('I', "International"), ('K', "Korean")) widgets = {"you_are": forms.CharField(widget=forms.Select(choices=Choices), max_length=2)} class Meta: model = User fields = ("username", "password1", "password2", "you_are") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) if commit: if user.you_are == "K": user.lang = "KR" user.save() return user Thank you in advance. -
How to specify a template for a Snippet in a StreamField when using SnippetChooserBlock
I want to use a snippet in a StreamField: @register_snippet class Advert(models.Model): url = models.URLField(null=True, blank=True) text = models.CharField(max_length=255) def __str__(self): return self.text class MyPage(Page): body = StreamField([('Snippet', SnippetChooserBlock( target_model='web.Advert')]) my_page.html: {% for block in page.body %} {% include_block block %} {% endfor %} However, when rendering the Advert it renders only the str representation of self.text. How can I specify a template layout for the snippet block, e.g. like a StructBlock? There is no documentation for SnippetChooserBlock. -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. Heroku
I am trying to set up my Django project on Heroku. It's my first time doing so. When deploying it succeeds but when opening up the view I get this message: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. (full traceback below). I am using Heroku Postgres and Heroku Redis add-ons. What am I doing wrong? Procfile release: python manage.py migrate web: daphne test_cs.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=test_cs.settings -v2 runtime.txt python-3.10.2 asgy.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import main.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_cs.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( main.routing.websocket_urlpatterns ) ) }) Full traceback 2022-02-14T22:14:52.566118+00:00 heroku[release.1702]: State changed from starting to up 2022-02-14T22:14:55.258559+00:00 app[release.1702]: Operations to perform: 2022-02-14T22:14:55.258595+00:00 app[release.1702]: Apply all migrations: admin, auth, contenttypes, main, sessions, social_django 2022-02-14T22:14:55.283487+00:00 app[release.1702]: Running migrations: 2022-02-14T22:14:55.283489+00:00 app[release.1702]: No migrations to apply. 2022-02-14T22:14:55.877375+00:00 heroku[release.1702]: Process exited with status 0 2022-02-14T22:14:55.963114+00:00 heroku[release.1702]: State changed from up to complete 2022-02-14T22:14:59.550199+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-14T22:15:05.339497+00:00 heroku[web.1]: Starting process with command `daphne test_cs.asgi:application --port 47797 --bind 0.0.0.0 -v2` 2022-02-14T22:15:06.845859+00:00 app[web.1]: Traceback (most recent call last): 2022-02-14T22:15:06.845875+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2022-02-14T22:15:06.845948+00:00 app[web.1]: … -
Get all events of user
So currently I can login and store my refresh token(if need be I can also store the access token) in a db using Google OAuth2 while using python social auth. models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): refresh_token = models.CharField(max_length=255, default="") I have a url /calendar that needs to retrieve the Google calendar events of the currently logged user. I also have a regular login that if the user has a refresh token which means that he has linked his google account to his account. How would I use get_events to just give all of the events associated with that account. from googleapiclient.discovery import build def get_events(request): print(request.user.refresh_token) credentials = AccessTokenCredentials(get_access_token(request), scopes=SCOPES) service = build('calendar', 'v3', credentials=credentials) google_calendar_events = service.events().list(calendarId='primary', singleEvents=True, orderBy='startTime').execute() google_calendar_events = google_calendar_events.get('items', []) return google_calendar_events def get_access_token(request): social = request.user.social_auth.get(provider='google-oauth2') return social.extra_data['access_token'] views.py def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return redirect('home') else: messages.error(request,'User blocked') return redirect('login') else: messages.error(request,'username or password not correct') return redirect('login') else: form = AuthenticationForm() return render(request, 'registration/login.html',{'form':form}) -
Group by and filter by on a particular field for all data in Django ORM
I have following model: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) I have entered data like: >>> leo_tolstoy = Author.objects.create(name=”Leo Tolstoy”) >>> alexandre_dumas = Author.objects.create(name=”Alexandre Dumas”) >>> Book.objects.create(title=”War and Peace”, author=leo_tolstoy) >>> Book.objects.create(title=”Anna Karenina”, author=leo_tolstoy) >>> Book.objects.create(title=”Resurrection”, author=leo_tolstoy) >>> Book.objects.create(title=”The Three Musketeer”, author=alexandre_dumas) >>> Book.objects.create(title=”The Count of Monte Cristo”, author=alexandre_dumas) I want to print the author’s name and all the books he wrote. For all the authors we have in the database. Like this: Leo Tolstoy: “War and Peace”, “Anna Karenina”, “Resurrection” Alexandre Dumas: “The Three Musketeers”, “The Count of Monte Cristo” I want to find the best solution for it but cannot find much. Any sort of help will be appreciated, I'm quite new to this. -
why i get TemplateDoesNotExist at /accounts/login/?
I'm trying to set my authentication views in my locallibrary site and these are my codes : My projects urls.py file has these from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ path(r'^accounts/', include('django.contrib.auth.urls')), re_path(r'^accounts/', include('django.contrib.auth.urls')), ] templates : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['./templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Pass data from JS to Python via Django
I want to send data from python to JS in Django. I successfully see the data in the response in the browser, but JS returns as . What would be the reason? trying to fetch information; def XXX(request): message_id=request.POST.get('messageid') return render(request, 'XX.html') sender; y = json.loads(response.text) ts = str(y["file"]["shares"]["public"]["XX"][0]["ts"]) return render (request, 'problemduyurusucreate.html', {'ts':ts}) JS; ... var test = "{{ ts }}"; $.ajax({ type: "POST", url: "{% url 'slack' %}", data: { "messageid": test, csrfmiddlewaretoken: '{{ csrf_token }}' } ... but I am displaying in my browser that I have successfully pulled the data -
Serialization of GeoJson with Django Rest (Different features in one collection)
How is it possible to serialize/desirialize a GeoJson with Django (GeoDjango or django-rest-gis) with multiple different type of features ( Points, Polygons, Lines) I got different models for each of the geo types, which are connected to a model named Route: class Marker(Model): route = ForeignKey(Route, on_delete=CASCADE) popup_html = TextField() point = PointField() class Meta(Model.Meta): pass class Polygon(Model): route = ForeignKey(Route, on_delete=CASCADE) polygon = PolygonField() class Meta(Model.Meta): pass class Route(Model): name = CharField(max_length=255) class Meta(Model.Meta): pass And my Serializer looks like this class RouteMarkerSerializer(GeoFeatureModelSerializer): class Meta: model = Marker geo_field = "point" class RoutePolygonSerializer(GeoFeatureModelSerializer): class Meta: model = Polygon geo_field = "polygon" And i want to get a output for the viewset something like this: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 8.88393, 51.038918 ], [ 9.039142, 51.085495 ], [ 9.100952, 50.945624 ], [ 8.88393, 51.038918 ] ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 9.066102, 51.024539 ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 8.951007, 51.010103 ] } } ] } I dont get to figure it out, how to do this. If i'm serializing … -
Date sorting in Datatable in the format of mm/dd/yyyy
I used the Datatable plug-in in my Django project. My data is dynamic data from a working google sheet. The date format of the first column of my data is mm/dd/yyyy, which cannot be sorted properly by Datatable. I converted the date to other formats, but it still cannot be sorted properly by Datatable. I tried the following codes in my HTML file: <td data-sort='YYYYMMDD'>{{element.date}}</td> It can be sorted by the correct date sequence in this way. However, the sequence will be "fixed" and I cannot sort the date with a reverse sequence by clicking the "sorting" option -
Pass nested dictionary from views to template django
So, I'm new to Django and I'm trying to pass data from my view to a template. I've understood how to pass the classic dictionary but I now need to use a nested dictionary. For instance, I have a dictionary as below my_dictionary = {0: {'title': 'Beyond the Soul', 'id': '2Uy66My5oKcBEIW7DvVk3V'}, 1: {'title': 'The Groove Cartel Selection', 'id': '1pHtICGI68RmWEKnnP5wGr'}, 2: {'title': 'STMPD RCRDS TOP 50', 'id': '1OIzwJTbrOeZTHvUXf5yMg'}, 3: {'title': 'House Party by Axwell', 'id': '1tl4L77FJju5zp9bJC83u8'}} From my view I'm returning return render(request, 'show_playlist.html', my_dictionary ) but If I use {{ main_playlist[0] }} it gives Could not parse the remainder error Is there a way to access nested dictionary in templates? -
Django Forcing BigAutoField even though Default is set to AutoField
so I upgraded from django 3.1 to 3.2 and on two of my models when I make migrations it keeps forcing me to change the auto id to BigAutoField even though I have (and had) DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' in my settings file before I updated. operations = [ migrations.AlterField( model_name='device', name='id', field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ) What is strange is that it is only affecting a couple models, but the rest are fine and they all use AutoField as well. I am not against using BigAutoField but the migration fails because of foreignkey constraints. I have deleted the migrations in question and also scrubbed them from the applied migrations table in the database. How can I stop Django from forcing this migration? I am at a loss right now. -
django - React - Axios: Data not being saved in database
I am trying to create products through a react js component using axios post request. In django log i see an OPTION request geting a 200 status code, but data not being saved in the DB. when doing it through postman it is working fine, which makes me think the problem is in the axios request. Thanks in advanced. models.py class Product(models.Model): title = models.CharField(max_length=32) notes = models.TextField() picture = models.ImageField(upload_to='product_images', null=True, blank=True) amount = models.IntegerField(default=0) @receiver(post_save, sender='product.Transaction') def update_amount(sender, **kwargs): product = Product.objects.get(title=kwargs['instance'].product) if kwargs['instance'].transaction_type == 'IN': product.amount += kwargs['instance'].amount product.save() else: if product.amount - kwargs['instance'].amount > 0: product.amount = product.amount - kwargs['instance'].amount product.save() def __str__(self): return self.title views.py class ProductCreateView(generics.CreateAPIView): serializer_class = ProductSerilizer permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializers.py class ProductSerilizer(ModelSerializer): class Meta: model = Product fields = '__all__' settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'rest_framework', 'corsheaders', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DATETIME_FORMAT': '%d-%m-%Y', } CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_ALL_ORIGINS = True AddProducts.js import React, {useState} from 'react'; import axios from 'axios' import { useNavigate } from "react-router-dom"; function AddProduct() { const [medicineTitle, setMedicineTitle] = useState(''); … -
how to return status in Response in json using django
I am creating an app where I am calling an API but there are five conditions, but the issue is I dont want to return after each conditon rather I want 5 response varibles and return that variable afterward which ever ran, but i am getting error unhashable type: 'dict' res = Response() if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) return (res) but the issue when I add status along with each data inside the res, i am getting this above error, for now I am return five statements each with their own status, but this doesn't look, so is it possible to return status along with all those statements. -
Latency for complexe request (DJango SQL)
I'm running a ("complex") query in SQL. Results returned to me in 0.3193ms from a MariaDB CLI. I transpose the query to Django through raw SQL, I get a return in 765.38 ms. The "Project" table contains 6000 entries. Here is my query (I'm getting bad results using the ORM's query system): Projet.objects.raw("SELECT P.id_projet AS id_projet, P.code_projet AS code_projet, S.nom_commercial AS id_societe__nom_commercial, P.date_initial AS date_initial, E.label_entite AS id_entite__label_entite, TC.label_type_contract AS id_type_contract__label_type_contract FROM HOME_PROJET AS P, HOME_TYPE_CONTRACT AS TC, HOME_ENTITE AS E, HOME_SOCIETE AS S WHERE id_projet IN ( SELECT Z.PK FROM ( SELECT primary_key_id AS PK FROM HOME_OBJECTS_H_PERM WHERE id_user = 1 AND objects_type = 'Projet' AND (id_type_perm IN (2, 5)) UNION SELECT primary_key_id AS PK FROM HOME_OBJECTS_H_GROUPPERM WHERE (id_group IN (1, 2)) AND objects_type = 'Projet' AND (id_type_perm IN (2, 5)) ) AS Z ORDER BY Z.PK ) AND P.id_type_contract = TC.id_type_contract AND P.id_societe = S.id_societe AND P.id_entite = E.id_entite;") SQL aliases are configured to map to model fields. Which solution(s)? -
How to store and display datetime field of a Model according to the end user's location in django?
models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) def __str__(self): return str(self.user) .html {% extends 'base.html' %} {% block content %} {% for post in posts %} {{post.date_time}} <br> {{post.title}} <br> {{post.body}} <br> {% for image in post.imagespostmodel_set.all %} <img src="{{image.images.url}}" alt="postimage" style="width: 300px;"> <br> {% endfor %} <hr> <hr> {% endfor %} {% endblock %} I have to specifically set the timezone in setting.py, but I want to display the time according the user location. -
Is this possible to add more required Fields in django rest framework (while log in)
At first i wanna say that my code is not important here. I wanna understand logick how this works. So when i try to Login with Django Rest Framework i need to pass 2 fields "Password and Username". Is this possible to add more required fields for example i need to pass email to log in. And How do i make it compare to data that i passed while registering user. (sorry for eanglish) I wanna make this: enter image description here Fields only required to log in: enter image description here Images Fixed -
Django Form - Conditional field display using JQuery
Disclaimers: I've been hitting many dead ends. After trying 10+ different questions and answers on Stack Overflow alone I've hit a wall. I am hoping I can accomplish this with a direct question. Please be gentle. I have spent days searching Stack Overflow and the Interwebs to try and get this working. There are MANY suggestions, and none of them have worked for me so far. I will confess I am not very knowledgeable with JS and this is likely why I'm stumbling hard over this requirement. If you have feedback on the quality of this question please comment with constructive criticism. Just telling me it's a poorly framed question won't help. However, sharing specific examples of what I could have done to frame the question in a more helpful manner would be great. Hopefully, you will be able to ascertain that I have gone to great efforts to post a substantive summary of the desired objective along with what I have tried. This implementation is using Django 4.0 and Bootstrap5 with CrispyForms. Objective: The user selecting a value in one field determines whether another field is shown or hidden. By default, the conditional field has a value of "No". … -
Reverse query in Django Many to Many
I have a problem in django reverse many to many. Basically, I think I am missing something that I couldn't understand properly yet. I have these models and views. models.py class TheorySyllabus(models.Model): name = models.CharField(max_length=100, null=True, blank=True) subject_duration = models.ManyToManyField( SubjectDuration, related_name='subject_durations') course_type = models.ForeignKey( CourseType, on_delete=models.DO_NOTHING, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Theory Syllabus' class TheoryCourse(models.Model): name = models.CharField(max_length=100) student = models.ManyToManyField(Student, related_name='theory_courses') theory_syllabus = models.ForeignKey( TheorySyllabus, on_delete=models.DO_NOTHING, null=True, blank=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.PROTECT, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.PROTECT, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.first_name + ' ' + self.user.last_name views.py class CourseListView(ListView): model = TheoryCourse queryset = TheoryCourse.objects.filter( is_active=True).order_by('-created_at') template_name = 'theory/course_list.html' context_object_name = 'theory_courses' paginate_by = 10 template <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap table-bordered"> <thead> <tr> <th>Course … -
Why I can't fetch the json response of django using javascript fetch API?
I am new to JavaScript. I'm working on a project in which I'm using Django in the backend. My Django views function will produce a JSON response which my javascript fetch will get it. Here is my Django views function that produces a JSON response. My motive is to make a like button that will update the like button's appearance and the number of likes by clicking on that button without reloading the whole page. This is the last requirement of my project. I am trying for a long time, a couple of days. def likepost(request,posts_id): posts = NewPost.objects.get(id = posts_id) is_like = False for like in posts.likepost.all(): if like == request.user and request.method == "POST": is_like = True break if not is_like: posts.likepost.add(request.user) else: posts.likepost.remove(request.user) posts.save() # serialize_obj = serializers.serialize("json",posts_id) return JsonResponse({ "is_like" : is_like, "num_like" : posts.likepost.count() },safe=False) My javascript will make an API of the JSON data generated the above views function using fetch. Here is my javascript full code. document.addEventListener("DOMContentLoaded",function(e){ // const colon = document.createElement('div'); // colon.setAttribute('id','colon') e.preventDefault() // const likebtn = document.createElement('button'); // likebtn.setAttribute('class','likebtn btn btn-primary'); // likebtn.setAttribute('class','likebtn'); // document.querySelector('.card-footer').appendChild(likebtn); // document.querySelector('.likebtn').innerHTML = "Like"; document.querySelector(`#likebtn${posts_id}`).onsubmit = like_function(); // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost')); }) // let is_like … -
How to solve this friend-request system error in my django project?
So in my django project i have this friend request system, it works for the most part (i think), i can send friend requests and then those respective users actually recieve the friend request, but when i try to accept that friend request it shows this error:error these is my views.py( the views i use in the friend request system have friends or something in their name, everything else is for other staff) from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import UserRegistration, UserEditForm,PostForm from django.views import generic from .models import Post,Friend_Request from django.contrib.auth.models import User # Create your views here. def friends(request): users = User.objects.all() return render(request, 'authapp/friendrequest.html', {'allusers':users}) def friends_accept(request): all_friend_requests = Friend_Request.objects.all() current_user = request.user to_user = User.objects.get(id = current_user.id) all_friend_requests = Friend_Request.objects.filter(to_user = to_user) return render(request, 'authapp/friends_request.html', {'all_friend_requests':all_friend_requests}) def download(request): context = { "welcome": "Welcome to your dashboard" } return render(request, 'authapp/download.html', context=context) def index(request): queryset = Post.objects.all() context= {'post': queryset} return render(request, "authapp/post.html", context) def blogs(request): posts = Post.objects.all() posts = Post.objects.filter().order_by('-created_on') return render(request, "authapp/post.html", {'posts':posts}) class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'authapp/post.html' class PostDetail(generic.DetailView): model = Post template_name = 'authapp/post_detail.html' @login_required def send_friends_request(request,userID): from_user = request.user to_user = User.objects.get(id = userID) … -
Django Update Instance with Email from 2 Related Objects
I have these models: class Contact(models.Model): email = models.EmailField(max_length=200, blank=False, null=False) class Account(models.Model): #account owner contact = models.OneToOneField(Contact, on_delete=models.CASCADE) class IndividualProfile(models.Model): account = models.OneToOneField(Account, blank=False, null=False, default='', on_delete=models.CASCADE) and I want to import an IndividualProfile, through django-import-export. In the sheet I'm importing, I have an email field that I will use to see if the Contact exists. Here is the logic I currently have been working on: class IndividualProfileResource(resources.ModelResource): class Meta: model = IndividualProfile clean_model_instances = True def before_import_row(self, row, row_number=None, **kwargs): self.temp_email = row["email"] def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Contact entries prior to importing rows. Create any missing Account entries prior to importing rows. """ if self.temp_email: # create contact first contact, created = Contact.objects.seal().get_or_create(email=self.temp_email) # # check if account exists account, created = Account.objects.seal().get_or_create(contact=contact) # # check if profile exists instance.account = account but doing this marks an error in the preview when I try to upload with an existing email. I was expecting it to update the existing IndividualProfile instance, but it did not. How may I fix this? Any help is appreciated. -
Adding list data in a JavaScript line chart - Django project
I created a list and defined it in my views.py: mydata = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, {'date': '2020-01-03T00:00:00Z', 'value': 2}, {'date': '2020-01-06T00:00:00Z', 'value': 5}] I want to add my own data in a template js chart in my HTML file: <script> var chart = am4core.create("chartdiv", am4charts.XYChart); chart.paddingRight = 20; var data = []; var visits = 10; for (var i = 1; i < 50000; i++) { visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10); data.push({ date: new Date(2018, 0, i), value: visits }); } chart.data = data; var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.grid.template.location = 0; dateAxis.minZoomCount = 5; dateAxis.groupData = true; dateAxis.groupCount = 500; var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); var series = chart.series.push(new am4charts.LineSeries()); series.dataFields.dateX = "date"; series.dataFields.valueY = "value"; series.tooltipText = "{valueY}"; series.tooltip.pointerOrientation = "vertical"; series.tooltip.background.fillOpacity = 0.5; chart.cursor = new am4charts.XYCursor(); chart.cursor.xAxis = dateAxis; var scrollbarX = new am4core.Scrollbar(); scrollbarX.marginBottom = 20; chart.scrollbarX = scrollbarX; var selector = new am4plugins_rangeSelector.DateAxisRangeSelector(); selector.container = document.getElementById("selectordiv"); selector.axis = dateAxis; </script> I know I should change the chart.data = data, but when I replaced it with chart.data = {{mydata}}, the chart didn't displat anything. I tried chart.data = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, {'date': '2020-01-03T00:00:00Z', 'value': 2}, …