Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
D3js Get the name of the data when it hovers
I'm working on an interactive graph project in django using d3js. I'm trying to create a scatter graph in d3js that displays a tooltip when the cursor hovers over a data node. However, I don't know how to get the name that corresponds to the pre-defined data when the cursor hovers over it. The scatter data I'm using is x : scatter x-coordinate y : scatter y-coordinate name : a unique name for the data I want to get the value of this name key during this hover. How can I reference the value of the original data corresponding to the data node with the key etc.? Thank you. My code is as follows. <div id="dc-graph"></div> // data from python (django) var graph_data = JSON.parse('{{ graph|safe }}'); var num = graph_data.num; var width = graph_data.width; var height = graph_data.height; var margin = graph_data.margin; var svgWidth = width + margin.left + margin.right; var svgHeight = height + margin.top + margin.bottom; var data = []; for (let i = 0; i < num; i++){ const adata = {x: graph_data.x[i], y: graph_data.y[i], name: graph_data.name[i]}; data.push(adata); } // svg var svg = d3.select("#dc-graph") .append("svg") .attr("class", "dc-graph-svg") .attr('width', svgWidth) .attr('height', svgHeight); // tooptip var tooltip … -
Update and create existing data in Django
I need to update and, if needed, create elements in a Django update view. Basically, I have a form where I am giving the user the chance of updating a row or inserting one or more new rows. The problem is that I am having issues in updating the "old" rows. If I update an existing row, it creates a new one. Here I post some code: views.py def edit_flight_mission(request, pk): mission = Mission.objects.get(id=pk) form = EditMissionForm(request.POST or None, instance=mission) learning_objectives = LearningObjective.objects.filter(mission_id=mission) context = { 'mission': mission, 'form': form, 'learning_objectives': learning_objectives, } if request.method == 'POST': learning_obj = request.POST.getlist('learning_obj') solo_flight = request.POST.get('solo_flight') if form.is_valid(): mission_obj = form.save() if solo_flight == 'solo_flight': mission_obj.solo_flight = True mission_obj.save() for lo in learning_obj: learning_objective, created = LearningObjective.objects.get_or_create(name=lo, mission_id=mission.id) if not created: learning_objective.name = lo learning_objective.save() return render(request, 'user/edit_flight_mission.html', context) models.py class Mission(models.Model): name = models.CharField(max_length=200) duration_dual = models.DurationField(blank=True, null=True) duration_solo = models.DurationField(blank=True, null=True) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) solo_flight = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class LearningObjective(models.Model): name = models.CharField(max_length=300) mission = models.ForeignKey(Mission, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) forms.py class EditMissionForm(forms.ModelForm): class Meta: model = Mission fields = ('name', 'duration_dual', 'duration_solo', 'training_course') widgets … -
Tags are not being stored in the database even after saving form in django
views.py def post(request): if request.method == 'POST': form = PostModelForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() # using the for loop i am able to save the tags data. # for tag in form.cleaned_data['tags']: # post.tags.add(tag) images = request.FILES.getlist('images') for image in images: ImagesPostModel.objects.create(post=post, images=image) return redirect('/Blog/home/') else: form = PostModelForm(request.POST) return render(request, 'post.html', {'form': form}) 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) tags = TaggableManager() def __str__(self): return str(self.user) post.html {% extends 'base.html' %} {% block content %} <form action="{% url 'post' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="file" multiple name="images"> <input type="submit"> </form> {% endblock %} After giving the input the data is stored in the tags field but, not saving in the database. I can manually insert data through the admin panel successfully but not as a non-staff user. I have installed taggit and placed it in the installed_apps in settings.py. Tags are being saved using post.tags.add(tag) inside for loop. What is the issue with the code? -
Found another file with the destination path 'admin'
I am trying to deploy the app on Heroku but when I run the following command: "python manage.py collectstatic" it returns multiple "Found another file with the destination path 'admin...". When I "git push heroku" the app, I can see the same error. Next, the application works, but /admin page doesn't have any format, like it is not reading css, font, etc. I've checked staticfiles/admin and it has its css,font,img and js folder with files. I've tried all the advices given here, but I'm not finding a solution. Here my settings: import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . . . # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #Heroku #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #ok for IBM Cloud STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') # if I comment this line and MEDIA_URL = '/media/' # this line, /admin page has correct css but I don't have images in the application # Extra places for collectstatic to find static files.(extra heroku) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) #django_heroku.settings(locals()) #if uncommented, application doesn't work And what I get when "git push heroku master" is: remote: Found another … -
write custom functions inside generic class based view in django rest framework
I have to write a custom function inside class based view which is like below: class ExampleView(ListCreateAPIView, UpdateAPIView, DestroyAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer def get(self, request, *args, **kwargs): /.........some code............./ def random_custom(self, request, *args, **kwargs): /.........some code............./ Here above I have a random custom function which I need to call from the url. Now I am not sure how to do that. If it was a modelviewset, we can do it easily like this: path("example/",users.ExampleView.as_view({"get": "random_custom"}), ), I have done it before in ModelVIewset,ie call custom functions like above but I am not sure how to do that is genericviews like above. -
How to convert JSON data in to python instance and save Django models multiple table with foreginkey (database sqllite)
*I am not able to save with id_category = models.ForeignKey please help me to solve ValueError: Cannot assign "21": "Categories.parent" must be a "Parents" instance. * View.py def GetProducts(request): endpoint = "[https://myurl.net/products/][1]" response = requests.request("GET", endpoint) data = json.loads(response.text) for cat in data['Category']: › pro_cat = ProCatData( id=cat['id'], name=cat['name'], image=cat['image'], ) pro_cat.save() for product in data['Products']: Products = ProductsData( id=product['id'], name=product['name'], id_category=product['id_category'], description=product['description'], image=product['image'], ) Products.save() model.py class ProCatData(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, null=True, blank=True) image = models.CharField(max_length=30) def __str__(self): return self.name class ProductsData(models.Model): id_category = models.ForeignKey(ProCatData, on_delete=models.DO_NOTHING,null=True, blank=True) image = models.CharField(max_length=300, null=True, blank=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, null=True, blank -
Access Certain Data in html page from cursor.execute used in views django
I have used this method in my views.py to access the certain kind of data from table in database def report(request): cursor = connection.cursor() cursor.execute('''Select active, count(name) as count from s_transaction group by active ''') report_list = cursor.fetchall() return render (request, 'report.html',{'report_list': report_list}) I'm using this for loop to get the entire data <tbody> {% for transaction in report_list %} <tr> <td>{{transaction.0}}</td> <td>{{transaction.1}}</td> </tr> {% endfor %} </tbody> and i'm getting the result like this active count yes 85 no 67 but i want to get the count no.s separately for different purpose in html, how do I get the no. 85 and 67 from count separately? -
Store DateTimeField without timezone
In settings.py of my Django project I have: TIME_ZONE = 'UTC' USE_TZ = False And I have set the timezone of my Postgresql database to 'UTC' too. However these two model fields are still stored with timezone (+330) in the database: created_on = models.DateTimeField(auto_now_add=True) expires_on = models.DateTimeField() What else I was supposed to do to have them both stored in UTC? -
while html to pdf converting with pisa hindi words are in coded way
while converting Hindi words in HTML to pdf by using the xhtml2pdf library in Django projects I am getting some coded words on how to convert in the correct way? def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
How can i get many to many relationship table data in django?
This is my models.py from django.db import models class Course(models.Model): Credits = ( ('1', '0.75'), ('2', '1'), ('3', '2'), ('4', '3'), ('5', '4'), ('6', '5'), ('7', '6'), ) course_code = models.CharField(max_length=20, default="CSE-101", unique=True) course_name = models.CharField(max_length=50, default="C Language", unique=True) course_credit = models.CharField(max_length=1, choices=Credits, default='4') def __str__(self): return self.course_code class Student(models.Model): std_name = models.CharField(max_length=40) std_id = models.CharField(max_length=50, primary_key=True) std_email = models.EmailField(max_length=50, unique=True, blank=True) course = models.ManyToManyField(Course) def __str__(self): return self.std_id when i input data in Student table, database create a table student_course, i want to get this student_course data. How can i get this data and show this data in webpage? I'm a noob to python and Django so any help would be greatly appreciated. -
FieldError at /category_list
I am facing this probelm in my e-commerce project when i try to pagination Cannot resolve keyword '' into field. Choices are: created_at, description, id, is_active, subcategories, thumbnail, title, url_slug views.py file ''' # CATEGORIES class CategoriesListView(ListView): model = Categories template_name = "admin_local/category_list.html" paginate_by = 3 def get_queryset(self): filter_val = self.request.GET.get("filter", "")`enter code here` order_by = self.request.GET.get("orderby", "id") if filter_val != "": cat = Categories.objects.filter( Q(title__contains=filter_val) | Q(description__contains=filter_val)).order_by(order_by) else: cat = Categories.objects.all().order_by(order_by) return cat def get_context_data(self, **kwargs): context = super(CategoriesListView, self).get_context_data(**kwargs) context["filter"] = self.request.GET.get("filter", "") context["orderby"] = self.request.GET.get("orderby", "") context["all_table_fields"] = Categories._meta.get_fields() return context ''' I am facing this probelm in my e-commerce project when i try to pagination This Is html file ''' <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <nav aria-label="Page navigation example"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="{% url 'category_list' %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.previous_page_number }} ">Previous</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">Previous</a> </li> {% endif %} <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="{% url 'category_list' %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.next_page_number }} ">Next</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">Previous</a> </li> {% … -
React On Click Prevent Download but show excel
I have a link from microsoft one drive which is generated when we upload file pythonically. I have linked this link to a button whichis supposed to show the file but not download however on click it is donloading the file so i neeed help regarding how to prevent download but show the excel file linked. Below is react code I have been using function Files(props){ let getFileOnClick=(fileAddress)=>{ window.location.href=fileAddress } return( <button style={{float:'right'}} onClick = {()=>getFileOnClick(props.link)} className="btn btn-primary"> Get File </button> ) } -
Retrieve field values to Django Admin using many to many relationships
I have a simple task: I need to expose player name related to Game in game list (Django Admin). Game object has ManyToMany relationship with Player object via 'players' attribute. The problem is that now I have empty 'players_list' field (empty list means I don't know what to do and just leave it here[enter image description here][1]), though I tried Player.objects.all() and obviously got all players even those who are not bound to particular game. I feel it has simple solution but my brain refuses to work after 55 opened tabs. Thanks in advance! This is my models.py from django.db import model class Player(models.Model): name = models.CharField(max_length=54, default="") email = models.EmailField(max_length=54) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Game(models.Model): name = models.CharField(max_length=254, default="") players = models.ManyToManyField(Player, blank=True, related_name='player_games') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) players_list = [] def __str__(self): return self.name and admin.py from django.contrib import admin from .models import Game, Player class PlayerInline(admin.TabularInline): model = Game.players.through @admin.register(Player) class Admin(admin.ModelAdmin): search_fields = ['name', 'email'] list_display = ('name', 'email', 'created_at', 'updated_at') inlines = [ PlayerInline, ] @admin.register(Game) class AdminAdmin(admin.ModelAdmin): list_display = ('name', 'created_at', 'updated_at', 'players_list') inlines = [ PlayerInline, ] exclude = ('players',) Pic as it looks … -
Trying startapp in Django and i get core exception update sqlite3
When starting project in Django no sqlite3 file created. Trying startapp i get core exception update sqlite3 later version required. How update? -
How to send images to DRF with json request?
I am working on a ecommerce project, and I want to add products from the frontend. The files in my product app in django is as follows models.py: from django.db import models from django.forms import CharField from PIL import Image from io import BytesIO from django.core.files import File # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=6, max_digits=6) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def create_thumbnail(self, image, size = (300,200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'JPEG') thumbnail = File(thumb_io, name=image.name) return thumbnail def get_image(self): if self.image: return f'http://localhost:8000' + self.image.url else: return '' def get_thumbnail(self): if self.thumbnail: return f'http://localhost:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.create_thumbnail(self.image) self.save() return f'http://localhost:8000' + self.thumbnail.url else: return '' def get_absolute_url(self): return f'/{self.slug}/' views.py: from sys import excepthook from unicodedata import category from django.http import Http404 from django.shortcuts import render from .serializers import ProductSerializer from rest_framework.views import … -
Serializer for status check
I have a Django project where a restaurant with orders and tables. You can see below the model: class Order(models.Model): STATUS_CHOICES = ( ("in_progress", "In_progress"), ('completed', 'Completed') ) table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=False, null=False, related_name='order_table') user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, related_name='order_user') status = models.CharField(choices=STATUS_CHOICES, null=True, max_length=15) I should restrict creating a new order if the table is still in progress. I guess it should be done through serializer but hove no idea about the validation and how to connect request with database information current serializer (standard): class OrdersModelSerializer(ModelSerializer): class Meta: model = Order fields = "__all__" current view: class OrdersFilter(filters.FilterSet): class Meta: model = Order fields = ( 'user', 'table__id', 'status', ) class OrdersModelViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrdersModelSerializer pagination_class = LimitOffsetPagination filter_backends = (DjangoFilterBackend, OrderingFilter) filter_class = OrdersFilter ordering_fields = ('table', 'user', 'status') -
Why is the system telling me that I don't have Python 3.10 in my system when I do?
I'm using pipenv for my virutal enviroment and am trying to install psycopg2 in Docker. However, when I try to install it, I get the following error. docker-compose exec web pipenv install psycopg2-binary Warning: Python 3.10 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python. You can specify specific versions of Python with: $ pipenv --python path/to/python I checked the python version within the virtual enviroment and it gives me 3.10.2. % python --version Python 3.10.2 I also checked the python version outside of the virtual enviroment(the system) but here, it gives me python 3.8.8 as default. python --version Python 3.8.8 Despite this, when I type python3.10 in the command line, it shows me that I have it installed in the system, so I'm unsure why it says 3.10 isn't found on my system. python3.10 Python 3.10.2 (v3.10.2:a58ebcc701, Jan 13 2022, 14:50:16) [Clang 13.0.0 (clang- 1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" for more information. Lastly, this all happens when I'm in using conda activate. I need conda activate for pipenv to work. When I do "conda deactivate" and type python --version , it gives me the following: conda deactivate % … -
How to customize the validation error message in Django?
I am trying to create a registration page in Django and to check fields validation. I wanna set a custom validation error message to the email field. Can you help me, please? Here is the view.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def newUser(request): form = NewUserFrom(request.POST or None) if not form.is_valid(): context = {'frmNewUser':form} return render(request,'login/newuser.html', context) return render(request, "login/welcome.html") Here is the forms.py: from ctypes import alignment from email import message from urllib import request from django import forms class NewUserFrom(forms.Form): error_css_class = 'error' username = forms.CharField(max_length=50, widget=forms.TextInput, label="Username") password = forms.CharField(widget=forms.PasswordInput, label="Password") confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput, label="Name") email = forms.EmailField(max_length=50, widget=forms.EmailInput, label="Email") def clean_password(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') # if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return cleaned_data def clean(self): cleaned_data = super(NewUserFrom,self).clean() email = cleaned_data.get('email') if email.strip() == "".strip(): # self.add_error('email','Email is reqiered.') raise forms.ValidationError('Email is reqiered.') else: fistPart, secPart = str(email).split('@') raise forms.ValidationError('Email error.') Here is the NewUser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for field in frmNewUser.fields %} {% … -
I tried updating django_site row to change the name but I have gotten ERROR: column "alt native" does not exist
I tried updating django_site to change the name (and later domain) to something more appropriate so that i could use these strings for email sending operations. I understand it is based on this: https://docs.djangoproject.com/en/4.0/ref/contrib/sites/ but I do not know what they are really talking about. Any help much appreciated. What I tried: postgres=# update django_site set django_site.name = "alt native"; ERROR: column "alt native" does not exist LINE 1: update django_site set django_site.name = "alt native"; ^ postgres=# select * from django_site id | domain | name ----+-------------+------------- 1 | example.com | example.com (1 row) -
How to install pillow on Namecheap server
Collecting pillow Using cached Pillow-9.0.1.tar.gz (49.5 MB) Preparing metadata (setup.py) ... done WARNING: Generating metadata for package pillow produced metadata for project name unknown. Fix your #egg=pillow fragments. Discarding https://files.pythonhosted.org/packages/03/a3/f61a9a7ff7969cdef2a6e0383a346eb327495d20d25a2de5a088dbb543a6/Pillow-9.0.1.tar.gz#sha256=6c8bc8238a7dfdaf7a75f5ec5a663f4173f8c367e5a39f87e720495e1eed75fa (from https://pypi.org/simple/pillow/) (requires-python:>=3.7): Requested unknown from https://files.pythonhosted.org/packages/03/a3/f61a9a7ff7969cdef2a6e0383a346eb327495d20d25a2de5a088dbb543a6/Pillow-9.0.1.tar.gz#sha256=6c8bc8238a7dfdaf7a75f5ec5a663f4173f8c367e5a39f87e720495e1eed75fa has inconsistent name: filename has 'pillow', but metadata has 'unknown' Using cached Pillow-9.0.0.tar.gz (49.5 MB) Preparing metadata (setup.py) ... done WARNING: Generating metadata for package pillow produced metadata for project name unknown. Fix your #egg=pillow fragments. Discarding https://files.pythonhosted.org/packages/b0/43/3e286c93b9fa20e233d53532cc419b5aad8a468d91065dbef4c846058834/Pillow-9.0.0.tar.gz#sha256=ee6e2963e92762923956fe5d3479b1fdc3b76c83f290aad131a2f98c3df0593e (from https://pypi.org/simple/pillow/) (requires-python:>=3.7): Requested unknown from https://files.pythonhosted.org/packages/b0/43/3e286c93b9fa20e233d53532cc419b5aad8a468d91065dbef4c846058834/Pillow-9.0.0.tar.gz#sha256=ee6e2963e92762923956fe5d3479b1fdc3b76c83f290aad131a2f98c3df0593e has inconsistent name: filename has 'pillow', but metadata has 'unknown' Using cached Pillow-8.4.0.tar.gz (49.4 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: pillow Building wheel for pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [144 lines of output] /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'project_urls' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/PIL copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageFilter.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageGrab.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageShow.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL … -
ImproperlyConfigured at /books/ Field name `Published_date` is not valid for model `Books`
I am building this rest api which gets data from database and shows all the fields regarding the books in database. models.py code: class Books(models.Model): Name = models.CharField(max_length=250) Author = models.ForeignKey('Authors', on_delete=models.CASCADE, default=None) Published_Date = models.DateField(blank=False) Pages = models.IntegerField() critics = models.IntegerField(default=0) def __str__(self) -> str: return self.Name serializer.py code: class BookSerializer(serializers.ModelSerializer): class Meta: model = Books fields = ['Name', 'Author', 'Published_date', 'Pages', 'critics'] urls.py code: urlpatterns = [ path('books/', views.BookList.as_view()), path('Bdetails/<str:pk>', views.BookDetail.as_view()), ] views.py code: class BookList(generics.ListCreateAPIView): queryset = Books.objects.all() serializer_class = BookSerializer class BookDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Books.objects.all() serializer_class = BookSerializer traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/books/ Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'genebox', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch response … -
Auto guess Profit/Loss from django and react
I'm creating and analysis website using Yahoo Finance API. models.py class Stock(models.Model): money_to_invest = models.CharField(max_length=100) stock_price = models.CharField(max_length=100) company = models.CharField(max_length=50) profit_or_loss = models.CharField(max_length=20) author = models.ForeignKey(User, on_delete=models.CASCADE) In profit_or_loss field want to auto save value Profit or Loss. if money_to_invest is greater than stock_price than is is Profit. How it can be possible through Django and React. I'm also using Redux for state management. -
How to check if an input value is exists and validate if yes in Django
I made a text input filed with jquery autocomplete where I query the users. So if I start typing the name of a user it shows the related users. It works fine but I like to avoid that if the user like note to choose from the pupped up list and possibly type all the name and it has a mistake. So I like to make a function that checks if the added value of the field is equals with any of the users in the database. How to do that? html <input type="text" class="form-control" placeholder="Type name here" name="kap_bar_01" id="kap_bar_01"> <script> $(function() { var names = [ {% for u in related_users %} "{{ u.user.last_name }} {{ u.user.first_name }}", {% endfor %} ]; $( "#kap_bar_01" ).autocomplete({ source: names }); }); </script> models.py class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) views.py def kapcsolodasok(request): profile = Profile.objects.get(user=request.user) related_users = Profile.objects.filter(projekt=profile.projekt) context = { 'related_users': related_users, 'profile': profile, } #lots of stuffs here return render(request, 'stressz/kapcsolodasok.html', context) Thank you in advance! -
Create a timer which resets itself after 24 hours but doesn't get restarted after the page is reset
i'm creating a web app and i'm trying to create a countdown timer for a certain product that is on discount and i'm wondering if there is a way to not reset the timer after the page has been refreshed and when it reaches 0 , wait 24 hours and then reset itself automatically. Here is a picture of a timer down below: Here is the code of a timer: var count = 420; var counter = setInterval(timer, 1000); function timer() { count = count - 1; if (count == -1) { clearInterval(counter); return; } var seconds = count % 60; var minutes = Math.floor(count / 60); minutes %= 60; document.getElementById("timer").innerHTML = (minutes).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) + ":" + (seconds).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}); // watch for spelling document.getElementById("timer2").innerHTML = (minutes).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) + ":" + (seconds).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}); // watch for spelling } -
Import issue in Djoser- Django
I'm trying to build an user authentication system with React and Django. I'm using JWT, Djoser for authentication model. serializers.py: from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("id", "email", "name", "password") settings.py: DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid},{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid},{token}', 'ACTIVATION_URL': 'activate/{uid}{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } But I get import error for Djoser, Import "djoser.serializers" could not be resolved I have tried changing names but nothing helped. The package isn't importing. I can edit and add more things like models.py and other things if they are necessary. Any help is appreciated.