Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
how can I make an internal API design where only react app can listen to `internal_api`?
I want to perform (get, post) operations to internal API without exposing the API to the world since it's just for creating new subscribers, managing the landing page, sending emails and mostly create, update, delete operations for administrators that I don't want to be publicly available /api/v1/? version: '3.7' services: internal_api: build: context: ./backend/services/internal_api dockerfile: Dockerfile container_name: internal_api command: gunicorn internal_api.wsgi:application --bind 0.0.0.0:8000 -w 2 volumes: - static_app:/home/app/app/static ports: - 8000:8000 env_file: - ./devops/.env.internal_api.prod depends_on: - database_01 landing: build: context: ./frontend/landing container_name: landing volumes: - ./frontend/landing:/usr/src/app networks: external_network: internal_network: internal: true``` -
django - Over time, Status value is how to update automatically
class Matching(SoftDeleteObject, models.Model): class MatchingStatus(models.TextChoices): REQUEST_REQUIRED = "RR" MATCHING_PROCEEDING = "MP" MATCHING_DONE = "MD" PAST_SCHEDULE = "PM" MATCHING_FAIL = "MF" matc_dt = models.DateField(validators=[validate_date], null=True) matc_time = models.TimeField(null=True) matc_stat = models.CharField(choices=MatchingStatus.choices, max_length=2, default="RR" ) After "matc_dt" and "matc_time" are over the current time, we would like to automatically update the status value to "PAST_SCHEDULE = PM". What should I do? -
Slug id not displaying (found) : http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order: admin/ postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail'] The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=50) slug = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post # Register your models here. class AdminPost(admin.ModelAdmin): list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status'] prepopulated_fields = {'slug':('title',)} list_editable = ('status',) admin.site.register(Post, AdminPost) views.py from django.shortcuts import render from .models import Post # Create your views here. def post_List(request): posts = Post.objects.all() return render(request, 'postscommentapp/post_list.html', {'posts':posts}) def post_detail(request, id, slug): post = Post.objects.get(id=id) return render(request, 'postscommentapp/post_detail.html', {'post':post}) url.py - postscommentapp from django.urls … -
How add guild user Discord
I try add member on guild documentation My code: views.py def login(request): template = loader.get_template('login.html') code = request.GET.get('code') at = Oauth.get_access_token(code) user_json = Oauth.get_user_json(at) id_user = user_json.get('id') invite = Oauth.join_server(id_user).get('message') context = { 'code': code, 'access_token': at, 'id_user': id_user, 'invite': invite, } return HttpResponse(template.render(context, request)) Oauth.py @staticmethod def join_server(user_id): guild_id = 'guild_id' url = f'{Oauth.discord_api_url}/guilds/{guild_id}/members/{user_id}' bot = 'token_bot' headers = {"Authorization": f"Bot {bot}", "Content-Type": "application/json", } link = requests.get(url=url, headers=headers).json() return link I get error: {'message': '405: Method Not Allowed', 'code': 0} {'message': 'Unknown Member', 'code': 10007} how fix it? -
Please correct the error below i can not add the data in the model
enter image description here Can someone suggest what I am doing wrong? I always get the erro model.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField Create your models here. class Youtuber(models.Model): crew_choices = ( ('solo','solo'), ('small','small'), ('large','large'), ) camera_choices = ( ('canon','canon'), ('nikon','nikon'), ('sony','sony'), ('red','red'), ('fuji','fuji'), ) category_choices = ( ('code','code'), ('mobile_review','mobile_review'), ('vlogs','vlogs'), ('comedy','comedy'), ('gaming','gaming'), ) name=models.CharField(max_length=254) price = models.IntegerField() photo = models.ImageField(upload_to='media/ytubers/%Y/%m') video_url = models.CharField(max_length=255) description = RichTextField() city =models.CharField(max_length=255) age =models.IntegerField() height = models.IntegerField() crew =models.CharField(choices=crew_choices, max_length=255) camera_type =models.CharField(choices=camera_choices, max_length=255) subs_count =models.CharField(max_length=255) category =models.BooleanField(choices=category_choices, default=False) is_featured =models.BooleanField(default=False) created_date =models.DateTimeField(default = datetime.now, blank=True ) admin.py from django.contrib import admin from .models import Youtuber from django.utils.html import format_html Register your models here. class YtAdmin(admin.ModelAdmin): # def myphoto(self,object): # return format_html('<img src="{}" width="40" />.format(object.photo.url)') list_display = ('id','name','subs_count','is_featured') search_fields = ('name','camera_type') list_filter = ('city','camera_type') list_dispaly_link = ('id','name') list_editable = ('is_featured',) admin.site.register(Youtuber,YtAdmin) -
Choices Field link to an attribute.Django
Is there a way to link a specific Choices field to an attribute? I've done some research and did not see anything posted. Models.py SIZES_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large') ( class Item(models.Model): name = models.CharField(max_length=50) sizes = models.CharField(choices=SIZES_CHOICES, max_length=50, null=True, blank=True, default="Small") small_item = models.FloatField(null=True, blank=True, (code that will associate it to Small Size)) medium_item = models.FloatField(null=True, blank=True, (code that will associate it to Medium Size)) large_item = models.FloatField(null=True, blank=True, (code that will associate it to Large Size)) -
Is there any good Ebook for Django?
I am in search of a good ebook for Django python. The book shall be for beginners with step to step guide and introduction of models, urls, etc. If anyone knows such a book then please provide me with a link to download that book. Thanks -
How can i get value which i have entered in sweetify input field?
sweetify.success(request,"Enter Otp",content = 'input',button='Confirm',persistent = True) How can i get this value entered by user ? -
self.request.user does not work in Django REST framework
I want to give only the information of the user who requested with self.request.user, but for some reason, this way I get the information of all users. How can I improve this so that we can retrieve only the information of the user who requested it? Please let me know if you know anything about this. View class StatisticsViewSet(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = EntrySerializer def get(self, request): queryset = self.request.user.entries.all() serializer = StatisticsSerializer(queryset) return Response(serializer.data) Serializer class StatisticsSerializer(serializers.Serializer): daily_report = serializers.SerializerMethodField() daily_report_week = serializers.SerializerMethodField() def get_daily_report(self, obj): data = Entry.objects.all().values( 'created_at__year', 'created_at__month', 'created_at__day').annotate(Sum('time')).order_by( 'created_at__year', 'created_at__month', 'created_at__day') ........ ... ... -
How to add X-BULK-OPERATION with HTTP_AUTHORIZATION in session credentials (headers). Pytest, Django
I'm writing test for Django Rest Framework with PyTest. There was a problem with headers X-BULK-OPERATION because I can't add X-BULK-OPERATION with HTTP_AUTHORIZATION on header. my code session.credentials(HTTP_AUTHORIZATION=response.data.get("token", None), **{"HTTP_X-BULK-OPERATION": True}) error {'detail': "Header 'X-BULK-OPERATION' should be provided for bulk operation."} print request, as you can see I have Bulk-Operation in header 'HTTP_AUTHORIZATION': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjcm1fdXNlciI6MSwiY3JtX2lkIjoxLCJncm91cF9pZCI6MSwiZGVhbF9wZXJtIjp7ImNyZWF0ZSI6MSwiZGlzcGxheSI6MSwiZWRpdCI6MSwiZGVsZXRlIjoxLCJleHBvcnQiOjF9LCJjb250YWN0X3Blcm0iOnsiY3JlYXRlIjoxLCJkaXNwbGF5IjoxLCJlZGl0IjoxLCJkZWxldGUiOjEsImV4cG9ydCI6MX0sImxlYWRfcGVybSI6eyJjcmVhdGUiOjEsImRpc3BsYXkiOjEsImVkaXQiOjEsImRlbGV0ZSI6MSwiZXhwb3J0IjoxfSwidGFza19wZXJtIjp7ImNyZWF0ZSI6MSwiZGlzcGxheSI6MSwiZWRpdCI6MSwiZGVsZXRlIjoxLCJleHBvcnQiOjF9fQ.Wrd89a8jpRnNu1XhNsOKFAkNQR6v_Y_X0nKySocMtLM', 'HTTP_X-BULK-OPERATION': True}