Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For a query set of a single element, indexing 0th element of a (query_set[0]) and and query_set.first() give different values - Django 2.2.7
I am running this code: city_state_location = ( Location.objects.filter(city=city, state=state) .values_list("city") .annotate(long=Avg("longitude"), lat=Avg("latitude")) ) print( city_state_location, city_state_location[0], city_state_location.first(), len(city_state_location), ) Which outputs: <QuerySet [('New York', -73.9422666666667, 40.8382)]> ('New York', -73.9422666666667, 40.8382) ('New York', -73.9501, 40.8252) 1 Why does this happen? The query set only contains one element so I'm confused why indexing the first element is any different then calling .first() This is running on Django 2.2.7 -
create tether wallet on django sites
I have decided to set up a store website for myself. On this website, my customers buy products with Tether(USDT). The customer charges his wallet and every time he buys a product, it is deducted from his wallet. This wallet is for the site itself and has nothing to do with currency wallets. framework : Django 3.2 how could i do that -
Django - How to iterate comlicated JSON object?
I have json object like [{'Group Name': 'asdfasdf', 'inputs': [{'DataType': 'data2', 'DataName': 'asdfasdf'}, {'DataType': 'data1', 'DataName': 'asdfasd'}, {'DataType': 'data2', 'DataName': 'asdfas'}]}, {'Group Name': 'asdfasdf', 'inputs': [{'DataType': '', 'DataName': 'asdfasdf'}]}] Data type and data name fields can be multiple in one group name. Group name can be multiple with at least one data type and data name field. This multiplication is dynamical due to user's choice. However, I am new in python and django. I didn't understand loop mechanism of them. How can I build a loop mechanism for group name count and data inputs count? -
How to run a function in django within a specified time?
views.py from django.shortcuts import render, redirect from .models import Product from .tasks import set_firsat_urunu from datetime import datetime # Create your views here. def index(request, id): product = Product.objects.get(id=id) if request.method == 'POST': product.name = request.POST.get('name') product.description = request.POST.get('desc') product.deadline_at = request.POST.get('deadline_at') product.firsat_urunu = [False, True][bool(request.POST.get('check'))] product.save() set_firsat_urunu.apply_async(args=[id],eta=datetime(2021,8,17,0,10)) return redirect(request.META.get('HTTP_REFERER')) return render(request, 'product.html', {'product':product}) tasks.py from celery import shared_task,current_task from .models import Product @shared_task(bind=True) def set_firsat_urunu(id=1): p = Product.objects.get(id=id) if p.firsat_urunu == True: p.firsat_urunu = False return 'done' I want to run a task with celery and make changes to a record in the database when the time I specify comes. When I run the code blocks I mentioned above, although the celery states that the relevant function has been received, I can't see anything in the django admin Celery Result section and at the same time, the celery task does not work even if the specified time has passed. Also, when I give apply_async ' args=[id] with @shared_task(bind=True), set_firsat_urunu gives an error because you gave 2 parameters but it takes only 1. -
widgets for ChoiceField in modelform
I'm using a modelform for my form Post and I'm using a bootstrap starter code as my base.html but because I use the {% csrf_token %} {{form.as_p}} on my add_blog page, bootstrap doesn't work and because of that it needs class='form-control', I have managed to do that on all of my fields but Choice input, if I do include my author(choicefield) in the widgets I get a TypeError: init() got an unexpected keyword argument 'attrs' class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "author", "body") widget = forms.Select(attrs={"class": "form-control"}) widgets = { 'title': TextInput(attrs={'class': 'form-control'}), 'title_tag': TextInput(attrs={'class': 'form-control'}), 'body': Textarea(attrs={'class': 'form-control'}), 'author': ChoiceField(attrs={'class': 'form-control'}) } -
Creating a simple form using django and searching a SQL database
I am trying to create a form that will allow users to search a database. The intended language is django. I have created the backend database for a simple student schema, and I will eventually have a stored procedure that takes different parameters, if any of the parameters are provided a search will be done on the database and results returned. For the purposes of this exercise, a simple table will also suffice for searching. I did some reading up and I have been able to come up with the below, however it feels like a log way from what I am trying to achieve, a prototype can be seen below of what I am trying to achieve. The back end database is SQL server, I have configured the database with django and created the table/tables. I would also like to understand how to play with stylesheets to create nice looking yet simple pages. On my views.py. This is what I have. from django.shortcuts import render from reporting_project.models import sqldbconnection import pyodbc def connsql(request): conn=pyodbc.connect('Driver={sql server};' 'server=localhost\DEV2;' 'Database=django_reporting;' 'Trusted_connection=yes;') cursor = conn.cursor() cursor.execute("select student_id, firstname, lastname, fullname, gender , enrollment_date from tbl_students") result = cursor.fetchall() return render(request, 'index.html',{'sqldbconnection':result}) if 'searchfield' … -
Issue with dropped decimals in JavaScript with Django template
I'm consulting with a small business using a POS software that runs javascript with Django template. I don't have control on what is in the Sale.TaxClassTotals.Tax array, but I'm trying to add the values to group taxes together. This is the code I'm trying to modify {% for Tax in Sale.TaxClassTotals.Tax %} {% if Tax.taxname and Tax.rate > 0 %} <tr><td data-automation="receiptSaleTotalsTaxName" width="100%">T.P.S : {% if options.tps_number != '' %}[{{ options.tps_number }}]{% endif %} ({{Tax.subtotal|money}} @ {{Tax.rate}}%)</td><td data-automation="receiptSaleTotalsTaxValue" class="amount">{{Tax.amount|money}}</td></tr> {% endif %} {% if Tax.taxname2 and Tax.rate2 > 0 %} <tr><td data-automation="receiptSaleTotalsTaxName" width="100%">T.V.Q : {% if options.tvq_number != '' %}[{{ options.tvq_number }}]{% endif %} ({{Tax.subtotal2|money}} @ {{Tax.rate2}}%)</td><td data-automation="receiptSaleTotalsTaxValue" class="amount">{{Tax.amount2|money}}</td></tr> {% endif %} {% endfor %} I've attempted to modify it to the following: {% set tps_total = 0 %} {% set tvq_total = 0 %} {% for Tax in Sale.TaxClassTotals.Tax %} {% if Tax.taxname and Tax.rate > 0 %} {% set tps_total = tps_total + Tax.amount %} {% endif %} {% if Tax.taxname2 and Tax.rate2 > 0 %} {% set tvq_total = tvq_total + Tax.amount2 %} {% endif %} {% endfor %} T.P.S : {% if options.tps_number != '' %}[{{ options.tps_number }}]{% endif %} ({{Tax.subtotal|money}} @ {{Tax.rate}}%){{tps_total|money}} T.V.Q : {% … -
Django form wont change to html format
I am trying to apply a ModelChoiceField as a Field, which seems to work as intended, but for some reason It wont match the format of the template. The image on the left is how its suppose to look, and image on the right is how it looks. I created a Form but still it wont ammend these changes. It usually works when i assign a form to the field, and it worked with other methods. Here is my Forms.py class dv_Form(ModelForm): class Meta: model = dv_model fields = '__all__' Metric_name_dv = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Metric_name_dv', flat=True),widget=forms.Select) My views.py (Just incase) def Auditor(request): model = auditsModel.objects.filter(qs_login=request.user) dv_models= dv_model.objects.all() form = auditForm() form_dv = dv_Form() if request.method == "POST": form = auditForm(request.POST) form_dv = dv_Form(request.POST) if form.is_valid() and form_dv.is_valid(): form.save() form_dv.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form, 'dv': form_dv} return render(request, "main/auditform.html", context) HTML PAGE {% load static %} <!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>QS Tool Demo 1</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"/> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/> <!-- Lightbox --> <link href="path/to/lightbox.css" rel="stylesheet"/> <!-- Stylesheets --> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" … -
Close Window button doesn't work on my website
Hey i am using the freelancer bootstrap from https://startbootstrap.com/previews/freelancer If you scroll down, click on some portfolio and then if you try to press the "close window" button nothing happens. How can i fix that? -
Using Waitress yields "This page isn’t working" for django project however works fine with python manage.py runserver
I am working on uploading my django project to heroku for beta testing, however am encountering an issue using waitress. $ waitress-serve --listen=*:8000 mysite.wsgi:application I used this line of code on the gitbash to test if waitress was working - got this as a result: INFO:waitress:Serving on http://[::]:8000 INFO:waitress:Serving on http://0.0.0.0:8000 I clicked on both of the links, but both of them result in "The Page isn't working" and an "ERR_EMPTY_RESPONSE" However, when I run python manage.py runserver, it works totally fine, and my django project gets pulled up and functions properly. I was wondering if anyone could provide any advice on how to fix this? -
Accessing the values of a ManyToManyField in Django
I've created a Many to Many relationship in my project like this: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Address'), unique=True) user_name = models.CharField(_('User Name'), max_length=150, unique=True) # and a lot of other fields and stuff class Course(models.Model): user = models.ManyToManyField(CustomUser, related_name="enrollments", blank=True, null=True) course_name = models.CharField(_("Course Name"), max_length=200) In Django Admin site, I created some courses and added users to it. What I need is to get a list of courses that a unique user is enrolled and a list of users enrolled in a unique course. I know that I can access the Related Manager like this: user.enrollments <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f4df159c0a0> And I know also that I can access the intermediate m2m class using: user.enrollments.through <class 'core.models.Course_user'> What I could not get (or find in the docs or even in internet at all) is how I can access the values contained in this relation (courses a user is enrolled and users enrolled in a course). Any help will be appreciated. -
django-graphql-jwt JWT_COOKIE_SAMESITE not working
I'm using Django GraphQL JWT Library and Django GraphQL Auth I keep getting this error google chrome error With this react code (trimmed for relevancy) on both http://localhost:3000/ and https://localhost:3000/ const [login] = useMutation(LOGIN_MUTATION, { variables: { email: email, password: password }, onCompleted: ({ tokenAuth }) => { if (tokenAuth.success) { setToken(tokenAuth.token); } } }); Now when I run this mutation from the graphiql page it works and I end up with a JWT cookie but not on the react site mutation { tokenAuth( email:"********" password:"*********" ){ token refreshToken success errors } } This doesn't work GRAPHQL_JWT = { "JWT_COOKIE_SAMESITE": 'None', "JWT_ALLOW_ARGUMENT": True } Adding these didn't work "CSRF_COOKIE_SECURE": True, "SESSION_COOKIE_SECURE": True, "CSRF_COOKIE_SAMESITE": 'None', "SESSION_COOKIE_SAMESITE": 'None', "JWT_VERIFY_EXPIRATION": True, Adding these to django settings also didn't work SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' I've been stuck on this for about 3 days now and am about ready to throw myself in a river and go build tables. Please help. -
Deploying Django error: Failed with result 'exit-code'. Gunicorn and VPS
I'm trying to set up a VPS server with ubuntu for my Django project. However, I am running into some trouble when running gunicorn status. sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Web ExecStart=/home/ubuntu/Web/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock project.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2021-08-16 19:38:28 UTC; 8min ago Main PID: 10466 (code=exited, status=1/FAILURE) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: self.stop() Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 393, in stop Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: time.sleep(0.1) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: self.reap_workers() Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Aug 16 19:38:28 vps-bdd44ecc systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Aug 16 19:38:28 vps-bdd44ecc systemd[1]: gunicorn.service: Failed with result 'exit-code'. I believe the error lies within ExecStart=/home/ubuntu/Web/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock project.wsgi:application, but I am not sure, any help? -
Customize One-To-One Relation Dropdown in Django Admin
I have a One-To-One relation on my users that connects them to their account how do i go about editing this dropdown that is provided by Django so as it will provide me with more detailed information directly in the dropdown box. right now it says Profile Object(1035) I would like it to say something like Username(ID) -
Django dynamic installed apps
I'm trying developing an app where basically represents plugin architecture. Each plugin consist an app where can be developed separatelly and builded in a tar.gz file. This file then uploads to the server and gets installed via pip (I'm using this tutorial). I'd like to know if there is a way that django can load the app after it's installed. Here are the methods that I used in my views.py def upload(request): if request.method == 'POST': app_file = request.FILES['app'] #gets the builded zip name = request.POST['name'] #gets the name of the app path = _save_file(app_file) #save the file and return the path _install_file(path) #install the tar via pip _add_app(name) #try to load in installed apps return render(request, 'upload.html') return render(request, 'upload.html') def _save_file(file): path = f'/usr/src/mysite/plugins/{file.name}' with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) return path def _install_file(path): code = subprocess.check_call([sys.executable, '-m', "pip", "install", path]) print(code) def _add_app(name): installed = settings.INSTALLED_APPS + [name] # apps.unset_installed_apps() apps.set_installed_apps(installed) management.call_command('migrate', name, interactive=False) When I execute the code and upload the tar.gz file, it outputs: ... web-mysite | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready web-mysite | raise AppRegistryNotReady("Apps aren't loaded yet.") web-mysite | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm using the dev … -
Saving the query object of one Django-Model into another
I am new to Django. I want to save the queried instance of Model-A,'Q' into Model-B. Model-A corresponds to Database D1 and Model-B to D2. In simple terms something like: Q=queryset(A).using('D1') Q.save(database='D2',model='Model-B') How can I do it? -
Ajax request to Django returns 500 Internal Server Error
Im pretty new in Django and Im trying to collect data with Ajax. Additionally, I would like to add Im trying to make and edit quiz app from tutorial(so Im doing it by tutorial, not from the scratch. After clicked button I got an error console.log('hello world quiz') const url = window.location.href console.log(url) $.ajax({ type: 'GET', url: `${url}data`, success:function(response){ console.log(response) }, error: function(error){ console.log(error) } }) I see that path is wrong, it should be: http://127.0.0.1:8000/1/, not http://127.0.0.1:8000/1/data. But changing from: url: `${url}data`, to: url: `${url}`, not collecting information about amount of arrays etc. I have also error from terminal: Traceback (most recent call last): File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ad/Documents/test01/src/quizes/views.py", line 20, in quiz_data_view for q in quiz.get_questions(): File "/home/ad/Documents/test01/src/quizes/models.py", line 22, in get_questions return self.question_set.all[:self.number_of_questions] TypeError: 'method' object is not subscriptable But really no idea what could I change in quizes/models.py: from typing import Text from django.shortcuts import render from .models import Quiz from django.views.generic import ListView from django.http import JsonResponse # Create your views here. class QuizListView(ListView): model = Quiz template_name … -
Django Admin Password Change
Step 1: I logged into the Django Admin Step 2: Clicked in Password Change in Admin Step 3: Entered the Old Password and New Password Step 4: Clicked the Change My password button The password is being successfully changed in the database. But, I'm getting the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/password_change/done/ Django Version: 2.2.24 Python Version: 3.7.10 Installed Applications: ['material.admin', 'material.admin.default', 'nested_inline', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'softdelete', 'reversion', 'actstream', 'rest_framework', 'rest_framework.authtoken', 'valital.api.apps.ApiConfig', 'cacheops', 'corsheaders', 'drf_yasg', 'storages', 'djmoney', 'mail_factory', 'mjml'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'reversion.middleware.RevisionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /usr/local/lib/python3.7/site-packages/material/admin/templates/registration/password_change_done.html, error at line 3 Invalid block tag on line 3: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? 1 : {% extends "admin/base_site.html" %} 2 : {% load i18n %} 3 : {% block userlinks %}{% url 'django-admindocs-docroot' as docsroot %}{% if docsroot %}<a href="{{ docsroot }}"> {% translate 'Documentation' %} </a> / {% endif %}{% translate 'Change password' %} / <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a>{% endblock %} 4 : {% block breadcrumbs %} 5 : <div class="breadcrumbs"> 6 : <a href="{% url 'admin:index' %}">{% translate 'Home' … -
validating uniqueness of many to many model by foreign key model field
I have 3 model: class Citizenship(models.Model): name = models.CharField() class Destination(models.Model): name = models.CharField() class RestrictionGroup(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) citizenship = models.ManyToManyField(Citizenship) I want my citizenship be unique based on related destination. If my destination is England, and if I have 5 restriction groups, each restriction groups related to destination have to unique citizenship. for example, at this image Greece is duplicated, but I need unique countries for destination country. so how can validate this and return back friendly error message? any help appreciated, thanks advance. -
Django-allauth apple login KeyError id_token
I am using django-allauth and django-rest-auth for authentication. I have implemented google login with these too. This is my urls url('rest-auth/apple/$', AppleLogin.as_view(), name='apple_login') and this is my views.py file from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter serializer_class = CustomSocialLoginSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) and this is my serializers.py file from rest_auth.registration.serializers import SocialLoginSerializer class CustomSocialLoginSerializer(SocialLoginSerializer): is_advertiser = serializers.BooleanField(required=False, default=False) def validate(self, attrs): attrs = super().validate(attrs) user = attrs['user'] if attrs.get('is_advertiser'): user.is_advertiser = True user.save() return attrs This is my settings.py file SOCIALACCOUNT_PROVIDERS = { 'apple': { "APP": { "client_id":'KEY GOES THERE', # APP ID "secret": 'APPLE SECRET KEY GOES THERE', "key": 'APPLE KEY GOES THERE', # The certificate you downloaded when generating the key. "certificate_key": """-----BEGIN PRIVATE KEY----- MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg806TKaQPgPJ7jj9e AFDJSKJFOW8495U93453SDVWFEOWI5U3405U34059U3450I304534095I34095I3 Mo4LCUa2GZhKDO2qHehLbAASDFSDFKJLKREKlok6MvuI8riC6xdnPGEcUp4 z5ihhVbY -----END PRIVATE KEY----- """ }, }, } above setup is straightforward But it's firing me this error KeyError at /rest-auth/apple/ 'id_token' Here you go for traceback ile "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation 422. value = self.validate(value) File "/home/py/Desktop/kidgistics/backend/home/api/v1/serializers.py" in validate 116. attrs = super().validate(attrs) File "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/rest_auth/registration/serializers.py" in validate 118. social_token = adapter.parse_token({'access_token': access_token}) File "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/allauth/socialaccount/providers/apple/views.py" in parse_token 92. identity_data = self.get_verified_identity_data(data["id_token"]) Exception Type: KeyError at … -
How to use bulk_create in django
I just learned that I can use bulk_create in django so that the query wont be too long and it will be fast rather than using for loop to add data to the database one by one. The problem is, I don't know how to do it, please help me. views.py: if request.method == "POST": csv_form = UploadCSVFileForm(request.POST or None, request.FILES or None) if csv_form.is_valid(): period = csv_form.cleaned_data.get('period') print(period) period = SchoolPeriod.objects.get(period = period) # save csv file uploaded_file = csv_form.cleaned_data.get('file_name') save_csv = GradeCSVFile.objects.create(file_name= uploaded_file) csv_file = GradeCSVFile.objects.get(grades_uploaded= False) #read csv file with open(csv_file.file_name.path, 'r') as file: reader = csv.reader(file) for i, row in enumerate(reader): if i == 0: pass else: subject = Subject.objects.get(subject_name = row[3]) profile = get_object_or_404(StudentProfile, LRN_or_student_number = row[0]) ######### **THIS IS THE PART WHERE I NEED THE `BULK_CREATE` ** ############ new_grade = StudentGrade.objects.create( student=profile.student.student, period = period, subject = subject, grade = row[4], ) csv_file.grades_uploaded = True csv_file.save() -
How to ensure sending ajax request happen after mouseevents?
I track mouse movement on several elements on an HTML page. I used this [question][1] for the mouse movement function. Then I send how much a user spent over an element using an ajax POST request to a Django view which save it into the db every time there is a new movement. Now I am able to do that, except I noticed that every now and then one of the elements store the time stamp rather than how many seconds. it seems that js is messing up the calculation here: mouseoverTime = currentTime.getTime() - mouseenterTime; it seems that mouseenterTime doesn't get updated with the mouseenter event and remains zero, hence mouseoverTime becomes currentTime.getTime() I am confused because this doesn't happen all the time and I am not getting any errors. could that be because of a problem when the page is loaded? or do I need to put the mouseenterTime variable inside the function? here is my js code: d3.select(window).on('load', function () { let mouseenterTime = 0; $(document).on('mouseenter mouseleave', '#gender_question', function (evt) { let currentTime = new Date(); if (evt.type === 'mouseenter') { mouseenterTime = currentTime.getTime(); } else if (evt.type === 'mouseleave') { mouseoverTime = currentTime.getTime() - mouseenterTime; $.ajax({ … -
How to use axios to post to my Django Rest server?
I am getting a 403 error when trying to post to my Django server from my frontend mobile app. However, it works totally fine when I post with the form on the browser. I managed to register once using my frontend mobile app, but ever since then, I get this 403 error. I've tried both signing up and logging in. Here is the error I get in my Django backend terminal: Bad Request: /rest-auth/registration/ [16/Aug/2021 14:51:37] "POST /rest-auth/registration/ HTTP/1.1" 403 58 Here is my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'users', ] SITE_ID = 1 .... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } ACCOUNT_EMAIL_VERIFICATION = 'none' Here is my front end (register.js): axios .post("http://127.0.0.1:8002/rest-auth/registration/", { username: "tester1234@gmail.com", email: "tester1234@gmail.com", password1: "tester1234@gmail.com", password2: "tester1234@gmail.com", }) What am I doing wrong? I just want users to be able to register, log in, and log out of my app. -
Django AttributeError (object has no attribute...)
I have such a href in my html template: <link><a href="{% url 'delete_all' %}">Delete all texts</a></link> Here's the view, attached to 'delete_all' url: def delete_all_texts(request): Text.objects.all().delete() return HttpResponse('All texts deleted') But when this href is clicekd I get such an error message: AttributeError at /delete_all 'str' object has no attribute 'get' P.S: Here's my Text model: class Text(models.Model): title = models.TextField(null=True) text = models.TextField(null=True) language = models.ForeignKey('Language', null=True, on_delete=models.PROTECT, verbose_name='Язык') class Meta: verbose_name_plural = 'Текст' verbose_name = 'Текст' ordering = ['title', 'text'] def __unicode__(self): return self.title def __str__(self): return str(self.title) + '\n' + str(self.text) + '\n' -
replacing images inside MEDIA_ROOT doesn't change the images in live server
i have avatar.png inside my /media/ folder and after a created some profiles i went and replaced the avatar.png with another with same name and it seems it doesn't change it at all, how to replace it all over django server ?