Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding & updating users from django admin to Auth0
I am trying to use Auth0 authentication in my django application. I am able to see the users added from auth0 in my django custom user table. Is it possible to add and update users from django application to Auth0. So far my code is mostly from the auth0 django tutorial. Can we add users from django admin site with Abstract Base User model and show them in Auth0? Below is code for authentcation that I am using. But is it possible to do 2-way? If I update a user in django admin site, it is not reflecting in Auth0 users. I couldn't get a clear picture of the AUth0 management API to update users from django side.. especially from admin site. Any inputs would be of great help. auth0.py class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): """Return current user id.""" return details['user_id'] def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' … -
How to access a dictionary value in a for [django, python, html]
I pass the context to html and I need to display the values in a for - by key. is not displayed. how to refer to the value of a dictionary in a loop? print context context = {'tag': 'fast', 'view': <orders.views.OrderAddView object at 0x0000000005AB30A0>, 1: <class 'clients.forms.RelatedAddForm'>, 2: <class 'clients.forms.RelatedAddForm2'>, 'count_form': range(1, 3)} html <form action="{% url 'order_add' tag %}" method="post"> {% csrf_token %} {% for x in count_form %} {{ x.as_p }} - this does not work {% endfor %} {{ 1.as_p }} - it works <button type="submit" class="btn btn-primary btn-block">Add order</button> </form> that is, how to access the values 1,2, etc. in a loop - 1: <class 'clients.forms.RelatedAddForm'>? perhaps it is necessary to specify {{context [x] .as_p}} in the loop? how to do it? -
save Django2.2 404 request in database using middelware
i write a custom middilware to save all request in my database. this is my code: class TestMiddleware(MiddlewareMixin): def process_response(self, request, response): .... # save my request attr in database HttpRequestLog.objects.create(**params) ... i have a problem. when user call a wrong url apis , Django return 404 status but this code save nothing to my database and i have n't any error!!! HttpRequestLog.objects.create(**params) my code is worked when api returned 200 or 204 or 201 status. -
Django Rest Framework Path working for one link, but not for other with same setup
I am trying to access my mysql database through the django rest backend. My frontend uses Vue with Axios. More specifically, I have a junction table TeacherSubjectJunction, which I want to access through the following path to get all subjects for a teacherid. app/urls.py path('teacherssubjects/<int:teacherid>/', TeacherSubjectJunctionList.as_view()) views.py: class TeacherSubjectJunctionList(generics.ListAPIView): queryset = TeacherSubjectJunction.objects.all() serializer_class = TeacherSubjectJunctionDeepSerializer filterset_class = TeacherSubjectJunctionFilter serializer.py: class TeacherSubjectJunctionDeepSerializer(serializers.ModelSerializer): class Meta: model = TeacherSubjectJunction fields = ['teacherid', 'subjectid'] depth = 3 For Filtering i am using the third party library django-filter filters.py class TeacherSubjectJunctionFilter(filters.FilterSet): class Meta: model = TeacherSubjectJunction fields = ['teacherid', 'subjectid'] models.py class TeacherSubjectJunction(models.Model): pk_teachersubject = models.AutoField(primary_key=True) teacherid = models.ForeignKey(Teachers, models.CASCADE, db_column='TeacherID') subjectid = models.ForeignKey(Subjects, models.CASCADE, db_column='SubjectID') class Meta: db_table = 'teacher_subject_junction' In my Vue file I am trying to access this path with the following code: async getSubjectsforTeacher(teacher){ await getAPI.get('/teacherssubjects/?teacherid='+teacher) .then(response =>{ this.SubjectsforTeacherData[teacher] = response.data console.log(this.SubjectsforTeacherData) }).catch(error =>{ if (error.response){ console.log( error.response ) }else if(error.request){ console.log( error.request ) }else if(error.message){ console.log( error.message ) } }) } The above setup gives me the following error: GET http://127.0.0.1:8000/teacherssubjects/?teacherid=3 404 (Not Found) Since I am only a few months into drf, I figured that something about my url setup was wrong. But here is where it gets interesting. … -
How to calculate total amt of different Models using multiple @property Django
class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return "Ordered by "+str(self.customer) @property #meaning add property see cart.html def get_cart_total(self): #get total value of one Model with their respective quantity orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): #get items total orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total @property #meaning add property see cart.html def get_energy_total(self): #get total value of another Model with their respective quantity orderenergies = self.orderenergie_set.all() total = sum([item.get_total for item in orderenergies]) return total @property def get_energy_items(self): #get items total orderenergies = self.orderenergie_set.all() total = sum([item.quantity for item in orderenergies]) return total @property def get_total_items(self): #get items total #how to get total value of two different model class OrderItem(models.Model): #make more orderitem product = models.ForeignKey(Paidproduct, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True) addtodpage = models.ForeignKey(Downloaddisplay, on_delete=models.CASCADE, blank=True, null=True) category=models.CharField(max_length=20, choices=CATEGORY_CHOICES,null=True) quantity = models.IntegerField(default=0, null=True, blank=True) data_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) @property def get_total(self): #to get total items of a certain product in cart.html total = self.product.price * self.quantity #+self.product1.price * self.quantity return total -
django site Admin shows 500 after login
I am new to Django, current site after login shows the 500 request not found but it login me as credentials are correct Django hosted in IIS and Django is 1.10 -
Django: list User details and Group for every User-Group (Many-To-Many) relationship in template
How to query and show User info and their Group for every User-Group (Many-To-Many) relationship in Django template? The result should look like: | User username | User email | Group name | | ------------- | -------------- | ----------- | | user1 | user1@mail.com | groupA | | user1 | user1@mail.com | groupB | | user2 | user2@mail.com | groupA | | user2 | user2@mail.com | groupC | | user3 | user3@mail.com | groupA | My question is similar to Vanilla Django Query to show 'flattened' User/Group (ManyToMany) Listing, but would like show more user details on the table. I naively thought something like this would have worked, but didn't. {% for group in groups %} {% for user in group.users.all %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{group.name}}</td> </tr> {% endfor %} {% endfor %} Using the raw SQL query has solved my problem: https://stackoverflow.com/a/38780451/991505 , but I am looking for better answers in the Django/Python way. -
Django App - auto creating & printing pdfs
Is there any way to autogenerate pdf and autoprint it? Let's say - i've got a list with 0 orders, server refreshes itself for every 5 minutes, and after that - there is an order in a list. App is creating pdf and print it by itself. Is this possible? -
Django custom login issue
I have created custom authenticate method because instead of username i want logged in through email for that i have written backends.py backends.py from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError UserModel = get_user_model() class EmailBackend(object): def authenticate(username=None,password=None): try: user = UserModel.objects.get(email=username) if user.check_password(password): return user else: return None except UserModel.DoesNotExist: raise ValidationError('Invalid Credentials') def get_user(self,user_id): try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None After authenticating i want user to be logged in.For that i am using login method as below: login(request,user,backend='django.contrib.auth.backends.ModelBackend') views.py from django.shortcuts import render,redirect from users.forms import RegisterForm,LoginForm from users.backends import EmailBackend as em from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import login def register(request): if request.method=='POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() print('Successfully Created') else: form = RegisterForm() return render(request,'users/register.html',{'form':form}) def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) uname = request.POST['username'] pwd = request.POST['password'] user = em.authenticate(username=uname,password=pwd) if user is not None: if user.is_active==True: k=login(request,user,backend='django.contrib.auth.backends.ModelBackend') print(user,k) print('Successfull login') else: print('Unsuccessfull login') else: form = LoginForm() return render(request,'users/login.html',{'form':form}) In my console i am trying to get the value returned by login function but that is returning None . k=login(request,user,backend='django.contrib.auth.backends.ModelBackend') print(user,k) Output in my console: [16/Mar/2021 16:02:34] "POST /register/ HTTP/1.1" 200 881 [16/Mar/2021 16:02:52] "GET … -
Integrate a voip application to a website
I need for a project to integrate to a website ( django & vuejs ) a voice chat page where there could be one to one exchanges, or one to many, following a group logic. For example if people are spread in 4 groups A,B,C,D, there should be one 'push to talk' button where for A people such that only their group hears it, and one global push to talk button such that everyone receives it. I was thinking of implementing it in python using PyAudio and multicast sockets but not sure it is the best idea or if it is even doable... Any idea or remark is welcome ! I saw that WebRTC could have been an option however it implies joining rooms if im not mistaken, which would be a problem. Thank you for reading and have a great day! -
How to display many to many fields in templates?
I have departments and services as Many to Many field. While Department is only for Hospital category and Service is for rest others. While listing all the categories I need to display departments/ services. But while I called it in my views as an object of the model. The data displays all the many to many field data in every category section. I need help to get list of all categories with only their specific many to many fields in HTML template. Views class ProviderList(TemplateView): template_name = "admin_section/provider_list.html" form_class = ProfileCompletionForm form_class1 = CustomUserCreationForm model = ProfileCompletion model1 = CustomUser context = {} def get(self,request,*awrgs,**kwargs): # obj1 = self.model1.objects.all() list1 =[] list3 = [] list4 = [] # for datas in obj1: # print(datas) qs = self.model.objects.all() for data in qs: # print(datas.departments.get()) # query = datas.category,datas.id,datas.services qs1 = self.model.objects.filter(id=data.id) for datas in qs1: dept = datas.departments.filter(id=datas.id) list3 += dept print(list3) ser = datas.services.filter(services=datas.id) # print(dept) list4 += ser # for obj in qs: # query = obj.id,obj.fullname,obj.location,obj.category,obj.departments # list1 += qs print(qs) print(list3) # print(list3,";",list4) self.context['form'] = qs self.context['dept'] = list3 self.context['ser'] = list4 form = SearchForm self.context['search'] = form return render(request,self.template_name,self.context) MODEL class ProfileCompletion(models.Model): fullname = models.CharField(max_length=120,default=None) address … -
how to get all the obj of model class ForeignKey after applying filter?
models.py class XYZ(models.Model): student = models.ForeignKey(to=Student, on_delete=models.SET_NULL, null=True) note = models.ForeignKey(to=Notes, on_delete=models.SET_NULL, null=True) views.py user = User.objects.get(username=request.session['user']) student = Student.objects.get(user=user) xyz_obj = XYZ.objects.filter(student=student) how can i get current login user(student) note_obj from xyz_obj for buy in xyz_obj: print(buy.note) gettig it using loop but how to get this without loop -
csrf fail on restAuth with TokenAuthentication and corsheaders
I am trying to make auth apis for my django+react project. I have used restauth package. When I hit the api with postman, it is successful (200) on get request but fails on post request due to csrf, I looked on internet and disabled sessionauthentication but still in vain .Here is my settings.py minimal settings for restauth INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "whitenoise.runserver_nostatic" ] LOCAL_APPS = [ "users.apps.UsersConfig", "corsheaders", ] THIRD_PARTY_APPS = [ "rest_framework", "rest_framework.authtoken", "rest_auth_custom", "rest_auth_custom.registration", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", ] INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', "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", "whitenoise.middleware.WhiteNoiseMiddleware", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication' ) } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) here is the postman view. let me know if you need anything additional -
django dropdown menu not showing options from MySQL table
i'm trying to display a column in my MySQL table as a dropdown menu (e.g. have all the orderIDs in the database show as options in the dropdown menu), and while my model loads into the HTML page, i have a blank dropdown menu (e.g. only the -- Select Order ID -- shows). this is my code: models.py from django.db import models from django.conf import settings import pymysql pymysql.install_as_MySQLdb() class Distance(models.Model): order = models.ForeignKey(Order, null=True, default=None) start_lat = models.DecimalField(max_length=20, max_digits = 25, decimal_places = 20, blank=True, null=True) start_long = models.DecimalField(max_length=20, max_digits = 25, decimal_places = 20, blank=True, null=True) end_lat = models.DecimalField(max_length=20, max_digits = 25, decimal_places = 20, blank=True, null=True) end_long = models.DecimalField(max_length=20, max_digits = 25, decimal_places = 20, blank=True, null=True) total_distance = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import Member, Driver, Order, Distance def homepage(request): try: members = Member.objects.all().order_by('member_hash') drivers = Driver.objects.all().order_by('driver_hash') orders = Distance.objects.all().order_by("order") except Member.DoesNotExist or Driver.DoesNotExist or Distance.DoesNotExist: raise Http404("Either member, driver, or distance object does not exist") return render(request, 'base.html', { 'members': members, 'drivers': drivers, 'orders': orders, } ) base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- Chart.js CDN --> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <!-- Bootstrap … -
@abstractstaticmethod indentation error Django [closed]
I'm working on a Django REST project and I am asked to refactor some piece of code that is very spaghetti into a Chain of responsibility. This is my code: from abc import ABCMeta, abstractstaticmethod class IHandler(metaclass = ABCMeta): """ Interface for handling requests """ @abstractstaticmethod def set_successor(successor): # Sets the next handler in the chain @abstractstaticmethod def handle(): # Handle the event The error that shows is the following: @abstractstaticmethod ^ IndentationError: expected an indented block I'm using Python 3.6.5 and I can't change to any other. -
Reverse for 'like_majstor' with arguments '('',)' not found. 1 pattern(s) tried: ['likeProfile/(?P<pk>[0-9]+)$'] problem
I am trying to add a like button for my users. I have two types of users in my AbstractUser model. They are different by user_type. What I am trying to do: make a like button where users of type KORISNIK, can like a user by type of MAJSTORI: Here is my model.py: class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) profile_image = models.ImageField(null=True, upload_to="images/", default='korisnici/static/post_user/images/profile_image.png') is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) bio = models.TextField(default=" ") def __str__(self): return self.username + ' | ' +self.last_name + ' | ' + self.first_name + ' | ' + str(self.phone_number) + ' | ' + self.user_type + ' | ' + self.email+ ' | ' + str(self.id) class LikeButton(models.Model): user = models.ForeignKey(CustomKorisnici, on_delete=models.CASCADE) likes = models.ManyToManyField(CustomKorisnici,related_name='profile_like') Up I created LikeButton in my model.py Next view.py def LikeProfile(request,pk): like = get_object_or_404(LikeButton, id=request.POST.get('majstori_id')) like.likes.add(request.user) return HttpResponseRedirect(reverse('majstori_profile', args=[str(pk)])) My URL: path('likeProfile/<int:pk>', LikeProfile, name="like_majstor"), And my HTML page: <form action="{% url 'like_majstor' majstor.pk %}" method="post"> {% csrf_token %} <button type="submit" name="majstor_id" value="{{ majstor.pk }}" class="btn">Like</button> </form> -
Docker on Google Compute Engine can't access port 80 despite setting firewall rules
I have a container running Django, Nginx, and Gunicorn running on Compute Engine I can successfully deploy and SSH into the VM but cannot access the external URL to the container despite creating several firewall rules. It seems to be closed to port 80 even after exposing it from within the VM. how do I fix this? Here's a copy of my: docker-compose file: version: '3' services: web: build: context: ./ dockerfile: Dockerfile.prod image: app-name:prod volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 8000:8000 command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:10-alpine env_file: - ./.env.prod volumes: - pgdata:/var/lib/postgresql/data expose: - 5432 nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: pgdata: static_volume: media_volume: NGINX conf: upstream core { server web:8000; } server { listen 80 default_server; listen [::]:80 ipv6only=on; location / { proxy_pass http://core; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } Here's a similar step I followed in setting up the VM: Why is Google Compute Engine not running my container? Here's the error I get when I try to access port 80: curl: … -
created_by not working with ManyToManyField django
Hello everyone I'm trying top build a task manager web app using django, I need to assign task to one or mutiple users I'm using manytomany relation in models.py and in views.py I'm adding created_by user automatically my problem is that when I do that I see that no users selected in assigned users but if I add created by user from the form it worked well bellow is my code class Task(models.Model): task_id = models.AutoField(primary_key=True) shortcode = models.CharField(max_length=15, unique=True, blank=True, null=True) task_name = models.CharField(max_length=200) task_progress = models.ForeignKey(TaskProgressStatus, on_delete=models.CASCADE, blank=True, null=True) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True) task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE) assigned_to_employee = models.ManyToManyField(User) paid = models.BooleanField(default=False) on_account = models.BooleanField(default=False) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True) net_amount = models.DecimalField(decimal_places=2, max_digits=20, blank=True, null=True) vat = models.IntegerField(default=11) quote_validity = models.CharField(max_length=200, default='1 Month from offer date') delivered = models.BooleanField(default=False) delivered_date = models.DateTimeField(null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) due_date = models.DateTimeField(null=True, blank=True) created_by = models.ForeignKey(User, related_name='created_by_username', on_delete=models.CASCADE, null=True, blank=True) project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE) file_name = models.FileField(upload_to='projects_files', null=True, blank=True) notes = models.TextField() def __str__(self): return str(self.task_name) @login_required def addtask(request): form = taskForm() if request.method == 'POST': form = taskForm(request.POST) if form.is_valid(): newform = form.save(commit=False) newform.created_by = request.user newform.save() return HttpResponseRedirect(request.path_info) else: … -
Failed to find attribute 'application' in 'Django project name'. Heroku app deploy
I deployed my Django project with Heroku successfully but when I view my app I get an error page saying Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail when I put it in terminal I get this message 2021-03-16T08:50:34.762969+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-03-16T08:50:34.763493+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [4] [INFO] Listening at: http://0.0.0.0:55178 (4) 2021-03-16T08:50:34.763587+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [4] [INFO] Using worker: sync 2021-03-16T08:50:34.767113+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [8] [INFO] Booting worker with pid: 8 2021-03-16T08:50:34.770278+00:00 app[web.1]: Failed to find attribute 'application' in 'ourUI'. 2021-03-16T08:50:34.770403+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-03-16T08:50:34.794976+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [9] [INFO] Booting worker with pid: 9 2021-03-16T08:50:34.799785+00:00 app[web.1]: Failed to find attribute 'application' in 'ourUI'. 2021-03-16T08:50:34.799990+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-03-16T08:50:34.904166+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [4] [INFO] Shutting down: Master 2021-03-16T08:50:34.904279+00:00 app[web.1]: [2021-03-16 08:50:34 +0000] [4] [INFO] Reason: App failed to load. 2021-03-16T08:50:37.000000+00:00 app[api]: Build succeeded 2021-03-16T08:50:39.982849+00:00 heroku[web.1]: Starting process with command `gunicorn ourUI` 2021-03-16T08:50:42.245442+00:00 … -
React Monaco Editor with python language server - Django Backend
all. I'm working on the project that uses Monaco editor (for python language) on React. But we want to implement IntelliSense to code editor, so it should suggest, autocomplete and so on. For that, I know I should use python language server with web-socket in my back-end, in order to, connect my code editor with python language server. But I cannot get any docs or examples how to use Django web-sockets (i think channels) to connect language server and front end code editor each-other. I know we should use monaco-languageclient, but its docs are not enough and noting for django -
Charts.js with time labels xAxes
i'm having trouble with initialize my chart with charts.js on my Django project, What i want to do: my labels should be time in day, something like that : ['06:00','07:00','08:00',...,'05:00'], my data items are dict (as described in charts.js doc) : {t: '24-05-2020 07:34:44', x: 6} (many like this), and what i want is that on my line chart, the data i provide will be present as a dot between the hours 07:00 and 08:00. important - the chart only shows data for one day. So how can i achieve that? thanks. -
Django whit api React js: ConnectionAbortedError: [WinError 10053] An established connection was aborted --> BUT this error will be only login request
Exception happened during processing of request from ('192.168.0.102', 51737) Traceback (most recent call last): File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Mandaa\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
How to save the image in the ImageField field from the link given by the parser, optimize it, and rename it according to needs?
I faced such a problem because of my inability, lack of understanding. In general, I made myself a parser for certain sites with saving the image and optimization and using extra_felds so as not to save choose to the database. In general, I need the picture to be saved in ImageField, to be optimized, and if its temp file is saved to be deleted. from io import BytesIO from django.core.files.base import File from urllib import request from django import forms from .models import Mods from .utils import get_link_data, slugify """Форма для Файлов""" class AdminFileForm(forms.ModelForm): """Выбор площадки парсинга""" PARSER_CHOOSE = [ (None, 'Не выбрано'), ('2', 'Steam'), ('3', 'Nexus') ] """Моё поле, недобавленное в модель""" parser = forms.ChoiceField(choices=PARSER_CHOOSE) """Добавляем русское название""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parser'].label = 'Площадка для парсинга' """Все поля из модели""" class Meta: model = Mods fields = '__all__' def clean(self): data = self.cleaned_data parser = data.get('parser', None) source = data['source'] if parser == self.PARSER_CHOOSE[1][0]: # Steam if source: # Source link to Steam mod title, version, author, link = get_link_data(source) data['title'] = title data['slug'] = slugify(title) data['author_file'] = author if not data['preview']: # ImageField from PIL import Image #parser img request_link = request.Request(link, headers={'User-Agent': 'Mozilla/5.0'}) input_file … -
Django get_FOO_display on template wont display
Good day SO. I am trying to use the get_FOO_display on template but my data is not displaying. Also, I have read other SO answers and I believe that I followed them to a T but not working. Please try to correct me what I do wrong. How I declared: Models: GENDER_CHOICES = ( (1, '男性'), (2, '女性'), ) gender = models.PositiveSmallIntegerField(choices=GENDER_CHOICES, default=0, null=False) forms: ... self.fields['gender'].widget.attrs.update({'class': 'form-control'}) view: account = AccountViewForm(initial = {"gender" : account.gender}) template: {{account.get_gender_display}} If I only use {{account.gender}}, it becomes a select tag with the correct data -
Django: How to return an attribute inside an HttpResponse with meta tags?
I have this return render(...) for the simple_upload view: def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'simple_upload.html') I would like to return something similar in the view complex_upload and be able to get the attribute 'uploaded_file_url' from complex_upload.html in the same way as I do with simple_upload.html but I don't know how to do it. Complex upload view: def complex_upload(request, filename): import os from mimetypes import MimeTypes content_type, encoding = MimeTypes().guess_type( os.path.basename(filename) ) if content_type is None or len(content_type) == 0: print(f'No content-type found for file: {filename}') content_type = 'text/plain' try: url = os.path.join( settings.MEDIA_ROOT, str(filename) ) with open(url.encode('utf-8'), 'rb') as f: uploaded_file_url = f.url(filename) resp = HttpResponse(f.read(), content_type=content_type) resp['X-Robots-Tag'] = 'noindex, nofollow' return resp except IOError as ex: data = {'ERROR': str(ex)} print(data) return JsonResponse(data) Is it possible to combine in a return a render with an attribute and a HttpResponse? What would be the proper way to do it? This question partially solves my doubts but it is not clear to me how to do something like that having meta tags.