Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Table not getting created from model in django rest api python
I have created a django project with 3 tables. I was able to create the connection to mysql and migrate succefully two of them. But, there is one table which is not getting created. I have tried deleting the migration folder and run the migration again using the makemigration command. Can you please help? This is the exception which I get. Exception Type: ProgrammingError at /admin/mitr_api/invitedetails/add/ Exception Value: (1146, "Table 'mitr.mitr_api_invitedetails' doesn't exist") This is the model which I created- class InviteDetails(models.Model): inviter_id = models.IntegerField( primary_key = True,) invitee_phonenumber = models.CharField(max_length = 10) invitecode = models.CharField(max_length = 5) invitee_name = models.CharField(max_length = 45) isd_code = models.CharField(max_length = 3) I have registered this model in admin.py and maintained other necessary connections and settings. from django.contrib import admin from .models import InviteDetails # Register your models here. admin.site.register(InviteDetails) -
How to filter queryset by the most recent datetime field using Django?
I have the following model which I want to perform a query to extract rows with the most recent created_at date given a list of names ordered by the most recent effective date: class Foo(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) effective_date = models.DateField() So for example the data can be the following: name | created_at | effective_date ================================== testA | 2022-01-01 | 2021-01-01 ---------------------------------- testA | 2022-02-01 | 2021-01-01 <--- pick this row since it has the most recent created_at ---------------------------------- testA | 2022-01-01 | 2021-02-01 ---------------------------------- testA | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at ---------------------------------- testB | 2022-01-01 | 2021-02-01 ---------------------------------- testB | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at ---------------------------------- Then given names = ['testA', 'testB'] I want to obtain the following results: name | created_at | effective_date ================================== testA | 2022-02-01 | 2021-02-01 ---------------------------------- testA | 2022-02-01 | 2021-01-01 ---------------------------------- testB | 2022-02-01 | 2021-02-01 ---------------------------------- Right now, I have tried the following queries: names = ['testA', 'testB'] # This doesn't isolate the rows with the most recent created_by date queryA = Foo.objects.filter(name__in=names).order_by("-effective_date") # This returns a single Foo object rather … -
(Django jwt) ValueError: not enough values to unpack (expected 2, got 1)
I have created a UserViewSetin my Django project to get user data via a get request, the viewset should be expecting a bearer type access token in the body. However, when I make the request through postman, it return a error: ValueError: not enough values to unpack (expected 2, got 1) My UserViewSet looks like this: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsAuthenticated,) def get_object(self): lookup_field_value = self.kwargs[self.lookup_field] obj = Account.objects.get(lookup_field_value) self.check_object_permissions(self.request, obj) return obj Now I know it is also expecting me to include a lookup field in the request, but I have not idea how and where to put it. My lookup field should be the id by default, so I just make the request by this endpoint: http://127.0.0.1:8000/account/auth/user/2/ in order to get user data of user id=2. Anybody has an idea why I am getting this error, and how to solve it? -
How to auto generate a field value with the input field value in Django Model?
I want to make an API that automatically generate a value to a field when POST to this api with Django. def gen_code(k): return # a value class generate_code(models.Model): code = models.CharField(max_length=100, default="", unique=True) generated_code = gen_code(code value) #generated with code Something like the code above. How can I make that -
How to resolve MultiValueDictKeyError in django
The purpose of the program is to give a user access to edit certain details in their database. This is the views.py file def edit_profile(request): user_info = UserInfo.objects.all() if request.method == 'POST': username_edit = request.POST['edit_username'] firstname_edit = request.POST['edit_firstname'] lastname_edit = request.POST['edit_lastname'] email_edit = request.POST['edit_email'] phone_number_edit = request.POST['edit_phone'] if len(phone_number_edit) == 11: if int(phone_number_edit) / 1 == 0: if User.objects.filter(username=username_edit).exists(): messages.info(request, 'Username already exists!') return redirect('edit') elif User.objects.filter(email=email_edit).exists(): messages.info(request, 'Email has already been used') return redirect('edit') else: new_user_info = User.objects.all() new_user_info.username = username_edit new_user_info.first_name = firstname_edit new_user_info.last_name = lastname_edit new_user_info.email = email_edit new_user_info.save() new_user_info_phone = user_info new_user_info_phone.phone_number = phone_number_edit new_user_info_phone.save() return redirect('profile') else: messages.info(request, 'Phone number not valid') return redirect('edit') else: messages.info(request, 'Phone number not valid') return redirect('edit') else: return render(request, 'profile_edit.html', {'user_info': user_info}) this is the html.file <form action="", method="post"> {% csrf_token %} {% for message in messages %} <p style="color: red;">{{message}}</p> {% endfor %} <h3>Click done after editing</h3> <p>Username: <input type="text", name="edit_username", value=" {{user.username}}"></p> <p>First Name: <input type="text", name="edit_firstname", value=" {{user.first_name}}"></p> <p>Last Name: <input type="text", name="edit_lastname", value=" {{user.last_name}}"></p> <p>Email: <input type="email", name="edit_email", value="{{user.email}}"></p> {% for user in user_info %} <p>Phone Number: <input type="text", value="{{user.phone_number}}", name="edit_phone"></p> {% endfor %} <input type="submit", value="Done"> </form> this is the urls.py file from django.urls … -
Testing views Error, where is the error please?
class Edit_RecipeViews(TestCase): """Unit Test Edit Recipe Page View""" def test_edit_recipe_page(self): response = self.client.get(f'/edit_recipe/{post.slug}') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'edit_recipe.html') -
create a superuser and adminuser using django restframework
i have a custom user model and i want to create a superuser from a view right, am currently using django restframework, below is my custom model and serializer with the views. model.py class CompanyUserManager(UserManager): def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email and passsword """ if not username: raise ValueError('The given username must be set') if not email: raise ValueError('The email must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_admin_user(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_admin', True) # if extra_fields.get('is_staff') is not True: # raise ValueError('Super user must have is_staff=True') # if extra_fields.get('is_admin') is not True: # raise ValueError('Super user must have is_admin=True') # if extra_fields.get('is_superuser') is True: # raise ValueError('Superuser must have is_superuser=False') return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Super user must have is_staff=True') if extra_fields.get('is_admin') is not True: raise ValueError('Super user must have is_admin=True') if extra_fields.get('is_superuser') is not True: … -
Can't print JSON for my GET request, Django
I have been trying to figure out Django and am confused with the views. I am not sure what I am doing wrong. The goal is to call Resource, a model, from the stored database and print serialized JSON on the webpage. @api_view(['GET']) def getResources(request): return Response(ResourceSerializer(Resource.objects.all()).data) Can you help me with this? -
MyPy, VSCode, Django, ModuleNotFound
I am working on a Django project. I want to be able to check the types in my project. For this purpose, I have installed django-stubs and mypy. Moreover, I want it to work with the VSCode extension. It saves time because I don't have to run mypy in terminal every time I have to check everything. However, MyPy simply crashes because it cannot find Django settings for some reason..... I have already tried moving around the mypy.ini file. It does not help. BTW, it works if I run MyPy in terminal. Error: ModuleNotFoundError: No module named 'my_project.settings' mypy.ini: [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = "my_project.settings" settings.json: { "python.linting.mypyEnabled": true, "python.linting.enabled": true, "mypy.runUsingActiveInterpreter": true, "mypy.configFile":"my_project/mypy.ini", "mypy.targets":[ "." ] } wsgi.py: """ WSGI config for web_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') application = get_wsgi_application() myvenv | | .vscode |---settings.json | my_project |----mypy.ini |----my_project | | | |--settings.py | | -
Django Rendering Form in HTML Issue
Hello so I'm attempting to render a form, in html and have tried the normal {{ form }}. However when I go to the site set up by: python manage.py runserver. I get the following where the form should go (highlighted section on screen-capture) webpage This is the code for the form in question. forms.py from django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node from .models import beacon class Command_Form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=beacon.objects.all(), widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=[ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ]) This is the html in question. I've removed non-relevant segments home.html </br> </br> <form action="" method=POST> {% csrf_token %} {{ form }} <button type="Submit" class="btn btn-secondary btn-sm">Submit</button> </form> </body> </html> Lastly I've included the views as I suspect it might have something to do with it but I'm not certain. I'm trying to make it so that when the form is submitted the page is reloaded. Views.py from … -
Javascript, resize an image and convert to base64
I want to resize image and convert it to base64 before sending via network. It takes so long if it is 10MB or more image so I need first to resize it on front, convert it and then send it to the server html: <div class="file__item ui-state-default current_ad current_ad_files"> <img width="88px" height="88px" src="{{ photo.image.url }}" alt=""> <input type="hidden" class="photo-base64" id="{{ photo.pk }}" value="{{ photo.get_base64_image }}" multiple> <a href="" class="file__delete" atr='sorok'></a> </div> js: function convertToBase64(file, inputId) { var reader = new FileReader(); reader.onload = function () { let base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); $(`#${inputId}`).val(base64String) } reader.readAsDataURL(file); } function getUploadedFileNode(file) { let randomId = getRandomID(); return { inputId: randomId, node: ` <div class="file__item ui-state-default file__item--sortable ui-sortable-handle"> <img width="88px" height="88px" src="${URL.createObjectURL(file)}" alt=""> <input type="hidden" class="photo-base64" id="${randomId}" value="" multiple> <a href="" class="file__delete"></a> </div> ` } } let addedFileNode = getUploadedFileNode(lastFile) // lastFile is an regular image from looping over multiupload convertToBase64(lastFile, addedFileNode.inputId) This issue is very urgent for me now, please help! Thanks a lot in advance! PS: front is written in pure javascript and jquery. -
Django subclass ContentTypeManager
I'm designing an app which has 3 models: Musician Album Song I'd like to code a custom ContentTypeManager method that I can call in views.py which allows me to access all three models with one method. e.g. music_data = ContentType.objects.get_music(musician='Beatles') This method would return a dictionary which I can pass to a template. The dictionary would look similar to the below: music_data = {'Abbey Road': ['Song 1', 'Song 2', 'Song 3', etc. ]} I have no issue writing the method that returns the music_data dictionary. However, I am not sure how to subclass ContentTypeManager to create a custom ContentTypeManager method. I tried creating a creating a model which inherits from ContentType and subclassing the manager in a similar way as a custom model manager would typically be created but this created a new database table and didn't reference the existing ContentType table. The code I tried is as follows: #models.py from django.contrib.contenttypes.models import ContentType from .managers import CustomContentTypeManager class CustomContentType(ContentType): objects = CustomContentTypeManager() #managers.py from django.contrib.contenttypes.models import ContentTypeManager class CustomContentTypeManager(ContentTypeManager): def = get_music(self): # Insert code to query models via ContentType model Any help would be greatly appreciated. -
Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/\\Z']
I am a beginner in learning code and am working on making a simple django site where users can click on other users to view their comments (by clicking their profile). However django keeps throwing this error when I run the site. My urls.py from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name='user-profile'), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>', views.updateRoom, name="update-room"), path('delete-room/<str:pk>', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>', views.deleteMessage, name="delete-message"), my template page 1(profile.html) {% extends 'main.html' %} {% block content %} <h1>{{user.username}}</h1> {% endblock content %} other template(feed component on my home page) <div> {% for room in rooms %} <div> {% if request.user == room.host%} <a href="{% url 'update-room' room.id%}">Edit</a> <a href="{% url 'delete-room' room.id %}">Delete</a> {% endif %} <a href="{% url 'user-profile' room.host.id %}">@{{room.host.username}}</a> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> my views.py def userProfile(request, pk): user = User.objects.get(id=pk) context = {'user': user} return render(request, 'base/profile.html', context) -
Django - Unable to pass page title as url parameter in template
I have a BIG problem. I need to pass article title to URL in the template This is my urls.py urlpatterns = [ *** re_path(r'^view/(?P<id>\w+)/(?P<title>\w+)/$', views.view, name='view'), *** ] view.py def view(request, id, title): return render(request, 'view.html', {'id' : id, 'title' : title}) At first I tried <a href="{% url 'view' id=3685 title='What a terrible weather' %}">What a terrible weather</a> And I got that error message: NoReverseMatch at /view/7/6999/ Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found. 1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$'] *** Error during template rendering In template D:\Django\gtunews\templates\view.html, error at line 8 Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found. 1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$'] *** Then I tried {% with thevarable= "What a terrible weather" %} <a href="{% url 'view' id=3685 title=thevarable %}">What a terrible weather</a> {% endwith %} The result: TemplateSyntaxError at /view/7/6999/ 'with' expected at least one variable assignment *** Error during template rendering In template D:\Django\gtunews\templates\view.html, error at line 8 'with' expected at least one variable assignment *** Also I tried {% with my_var = 'What a terrible weather'.replace(' ','_') %} <div>Hello, {{my_var}}!</div> {% endwith %} As a result I go the … -
'>' not supported between instances of 'decimal.Decimal' and 'QuerySet' How do you cange a QuerySet to a decimal or get access to the values in it?
I am trying to make an e-commerce site (CS50 Project 2) that allows the user to make a bid if their bid is greater than or equal to the listing price and greater than all other bids. I have been able to check if the bid is greater than the listing price but need help checking if it is greater than the other bids. I am receiving this error message. '>' not supported between instances of 'decimal.Decimal' and 'QuerySet'. I know that means I am comparing two different types of values, but how do I get change the QuerySet to a decimal or get direct access to the values within the QuerySet? views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) #code for forms listing_price = listing.bid comment_obj = Comments.objects.filter(listing=listing) comment_form = CommentForm() bid_form = BidsForm() comment_form = CommentForm(request.POST) bid_form = BidsForm(request.POST) bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.listing = listing comment.user = request.user comment.save() if bid_form.is_valid(): new_bid = bid_form.cleaned_data.get("bid") if (new_bid >= listing_price) and (new_bid > other_bids): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj }) else: return … -
Why is Django questionnaire app not recognizing answer choices after deploying with Apache and MySQL?
I am currently trying to deploy my Django project through Apache and MySQL. All of my project apps are working well except for my questionnaires app. I am not able to record responses in the database and getting an error that says [{'id': ['Select a valid choice. That choice is not one of the available choices.']}]. I am confused because this app was working well when I was running my project through my local server and Django's default SQLite database. There are two questionnaires in my app: one is a mood board where the user selects a picture that best represents how they are feeling (I am not trying to record the actual image, just the name of the image), and the second is the Edinburg Postnatal Depression Scale, it is a multiple-choice survey that has no pictures. Can someone please give me advice as to why the app is not recognizing the answer choices? Here is my models file: User = settings.AUTH_USER_MODEL class Questionnaire(models.Model): name = models.CharField(max_length=255) text = models.CharField(max_length=200) def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.text class Answer(models.Model): question = models.ForeignKey(Question, models.SET_NULL, blank=True, null=True, related_name='answerlist') questionnaire = … -
django FieldError: Cannot resolve keyword 'category_name_contains' into field. Choices are: category, description, id, image, name, order, price
I want to build a food delivering app, but facing this error. "FieldError: Cannot resolve keyword 'category_name_contains' into field. Choices are: catego ry, description, id, image, name, order, price" this is the query.py try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break this is the view.py from ast import Return from multiprocessing import context from django.shortcuts import render from django.views import View from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category_name_contains='Appetizer') main_course = MenuItem.objects.filter( category_name_contains='Main Course') desserts = MenuItem.objects.filter(category_name_contains='Dessert') drinks = MenuItem.objects.filter(category_name_contains='Drink') # pass into context context = { 'appetizers': appetizers, 'main_course': main_course, 'desserts': desserts, 'drinks': drinks, } # render the templates … -
currently learning Django and keep getting this error wheni try to runserver
i am a beginner learning using a tutorial. but i keep getting an error that isnt letting me move forward. I have attached an image with the full message ImportError: cannot import name 'Path' from 'django.urls' (C:\Python\Python310\lib\site-packages\django\urls_init_.py) -
Submit Button breaks HTML render with Django
I'm working on a simple site, just for learning some Django. I'm having troubles when trying to submit a form in order to search for something in my database. All the site is working fine, but when I look for something in that request, the web explorer just shows the raw HTML instead of rendering it. Here I share my view: from django.http import HttpResponse from django.shortcuts import render from AppFinal.models import Usuario, Direccion, Estudio from AppFinal.forms import UsuarioFormulario, def buscarUsuario(request): return render(request, 'AppFinal/buscarUsuario.html') def buscar(request): if request.GET['nombre']: nombre=request.GET['nombre'] usuarios = Usuario.objects.filter(nombre__icontains=nombre) return render(request, 'AppFinal/resultadoBusqueda.html', {'usuarios': usuarios}, {'nombre': nombre}) else: respuesta = 'No enviaste datos' return render(request, 'AppFinal/resultadoBusqueda.html', {'respuesta':respuesta}) def resultadoBusqueda(request): return render(request, 'AppFinal/resultadoBusqueda.html') This is the URLs file: from xml.etree.ElementInclude import include from django.urls import path from AppFinal import views import AppFinal urlpatterns = [ path('', views.inicio, name='Inicio'), path('buscarUsuario', views.buscarUsuario, name= 'buscarUsuario'), path('resultadoBusqueda', views.resultadoBusqueda , name= 'resultadoBusqueda'), path('usuario', views.usuario, name= 'usuario'), path('buscar/', views.buscar), ] This is the HTML where you look for a specific item in the database: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/AppFinal/buscar/" method="GET"> {% csrf_token %} <input type="string", name= "nombre", id= "nombre"> <input type="submit", … -
Django Html and plots to PDF
I am using the Django application to generate some graphs using Plotly so I tried to generate a pdf file of the following plots of my HTML page is: <center> <p class="lead"><strong><em>&nbsp;All Plots&nbsp;</em></strong></p></center> <div class="row"> <div class="col-md-6" > {{ sunburst|safe}} </div> <div class="col-md-6" > {{ sunburst2|safe}} </div> </div> and my url.py : path('export_pdf/', views.export_pdf, name='export_pdf'), and the views.py; def export_pdf(request): df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada') df2 = px.data.gapminder().query("continent=='Oceania'") fig2 = px.line(df2, x="year", y="lifeExp", color='country') chart = fig.to_html() chart2 = fig2.to_html() context= { 'sunburst':chart, 'sunburst2':chart2, } return render(request, 'Home/Reporting/part_pdf.html',context) I tried some code from this page but I can't generate the file any help? https://plotly.com/python/v3/pdf-reports/ are there any other methods for doing that (html page with plots and tables)? All my best -
Understanding CORS cookies
I have been trying for some time to deploy a web application i built, using reactjs for the Frontend and Django for the backend. After struggling with django configurations i managed to make the sessions work when both FE and BE are running locally, so the next step was deploying the BE on a remote host and i chose Heroku, with a docker setup, while i kept the FE running locally to test the BE deployment. This completely broke the django sessions i relied upon, as the BE was sending the relevant cookie to FE, but the FE was not including it in the next request, making it completely useless (include credentials did not solve the issue). After trying to mess with every CORS configuration on the Server side,(cors-headers) i came to the conclusion that browsers simply don't allow these cross-domain cookies. Meaning the FE can receive the Cross-domain cookie from the BE, but no matter what it will not include it in the next request. This leads me to 2 questions: Is my understanding of the issue correct? Meaning it really can't be done with cross-domain BE an FE? If so, is the only approach having FE and BE … -
Getting metrics on a website using django or JS?
I need to get metrics such as: Speed mouse movement, Click rate, and similar. There are 2 questions: How can I get these metrics from the site using JS, Django or other tools. Are there any other metrics that can be tracked? -
I can't find a host for my python and django website
I've created a website using Django framework. I have HTML CSS Python and SQL. I was able to put python into my index.html thanks to : https://docs.djangoproject.com/en/4.0/ref/templates/language/#variables Regarding python I have a script.py that generates a list of numbers L = [120, 140.65, etc] This script updates every 10 minutes because the numbers change L = [122.2, 140.85, etc] Then this list is imported into MySQL. So the DB changes every 10 minutes. Finally, a table is generated on my site using index.html and css with the updated numbers every 10 minutes. My website : --index.html --style.css --script.py --MySQL database The problem is, how can I find a website host who will automatically run my script.py (which will update my website every 10 minutes), which will understand python in html (this: {% for x in story_list %} ) and which will host my database. Thank you for your help! : Sorry for my bad english -
error 'FloatField' object has no attribute 'aggregate' - in a report in Django with sum of totals
I try to generate in a list with the total sales per month in the current year. In my model I have the total field, which is the total of each sale. I generate a loop (for) of 12 passes, one for each month, and I want to obtain the total of each of the months. This is the Model class Sale(models.Model): cli = models.ForeignKey(Client, on_delete=models.CASCADE) date_joined = models.DateField(default=datetime.now) subtotal = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) iva = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) def __str__(self): return self.cli.names def toJSON(self): item = model_to_dict(self) item['cli'] = self.cli.toJSON() item['subtotal'] = format(self.subtotal, '.2f') item['iva'] = format(self.iva, '.2f') item['total'] = format(self.total, '.2f') item['date_joined'] = self.date_joined.strftime('%Y-%m-%d') item['det'] = [i.toJSON() for i in self.detsale_set.all()] return item class Meta: verbose_name = 'Venta' verbose_name_plural = 'Ventas' ordering = ['id'] This is the view where the error occurs... from django.views.generic import TemplateView from datetime import datetime from django.db.models.functions import Coalesce from django.db.models import * from Curso3App.models import Sale class DashboardView(TemplateView): template_name= 'Curso3App/dashboard.html' def get_GraficoVentasPorMes(self): data=[] year = datetime.now().year for mes in range(1,13): total = Sale.objects.filter(date_joined__year = year,date_joined__month = mes) total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() #total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() data.append(total) print('total ',total) return data def get_context_data(self, **kwargs): … -
populate social account extra_data
I am new to Django, and I am trying to add social login with social applications (Facebook, Google, Twitter) for a flutter application with allauth + dj_rest_auth. However I am facing difficulties trying to populate the social account provided by allauth to my custom user model. The User model. (models.py) class UserManager(BaseUserManager): use_in_migrations: True def _create_user(self, email, name, password, **extra_fields): if not email: raise ValueError("The given email must be set") if not name: raise ValueError("The given name must be set") email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, name, password, **extra_fields) def create_superuser(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, name, password, **extra_fields) class Country(models.Model): name = models.CharField(max_length=255) flag = models.ImageField(upload_to="flags") code = models.CharField(max_length=3) def __str__(self): return self.name class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True, verbose_name="Email Address") # name = models.CharField(max_length=255) first_name= models.CharField(max_length=255) last_name= models.CharField(max_length=255) show = models.BooleanField(default=True) brithday = models.DateField(null=True, blank=True) gender = models.CharField( max_length=10, choices=( ("male", "Male"), ("female", "Female"), ("unknown", "Unknown"), ), default="unknown", ) country = models.ForeignKey(Country, on_delete=models.PROTECT) picture = …