Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python unsupported operand type(s) for -: 'list' and 'list'
I have the following functions: def one(): a={'Income_one': list(100 for m in range(12))} context={'a':a,} return context def two(): b={'Income_two': list(50for m in range(12))} context={'b':b,} return context Now I want to create a third function to get the different between a and b I have tried to get this one: def diff(): data_one=one['a'] data_two=two['b'] diff=dict() diff['Diff']=list(a)-list(b) But python give me the following errors: unsupported operand type(s) for -: 'list' and 'list' Where is the issue? -
i cant do anything brow, i just want to connecting my Django peoject with mysql
i just add pip install mysqlclient at (Env) F:\MyDjango> and then i got this : ERROR: Command errored out with exit status 1: command: 'f:\mydjango\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Administrator\AppData\Local\Temp\pip-install-01m1bk9e\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Administrator\AppData\Local\Temp\pip-install-01m1bk9e\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Administrator\AppData\Local\Temp\pip-record-hd_d1okv\install-record.txt' --single-version-externally-managed --compile --install-headers error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.26.28801\\bin\\HostX86\\x86\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'f:\mydjango\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Administrator\AppData\Local\Temp\pip-install-01m1bk9e\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Administrator\AppData\Local\Temp\pip-install-01m1bk9e\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' but i have install ms visual studio include visual c++ v 14 -
how should i implement celery for the external module response in django?
My django project includes 3 external tasks Camera integration(Alliedvision camera) Movie making module using frames which is took from camera Emotion detection for camera frames My get function in class based view for camera integration part is, def get(self, request, *args, **kwargs): status = request.GET.get('status') team_name = request.session['current_team_name'] user_name = request.session['current_inputUserName'] media_path = settings.MEDIA_ROOT print(media_path,'mediapath') print(team_name,'teamname') print(user_name,'user') try: if status == 'ON': os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib/Libraries" global proc proc = subprocess.Popen( ["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoContinuousFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path], shell=True, preexec_fn=os.setsid) elif status == 'GROUP': os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib/Libraries" proc = subprocess.Popen( ["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoGroupFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path],shell=True) elif status == 'SINGLE': os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib/Libraries" proc = subprocess.Popen( ["/home/dev/integrated_module/front-face-camera/rest_project/CameraApplication/MakoSingleFrameGrabberConsoleApplication" + ' ' + team_name + ' ' + user_name + ' ' + media_path], shell=True) else: import signal from pynput.keyboard import Key, Controller keyboard = Controller() keyboard.press('~') except: import signal os.killpg(os.getpgid(proc.pid), signal.SIGTERM) return JsonResponse({'message': 'successfully saved your profile'}, status=200) For rest of the both modules iam calling the function whenever server need the response Can anyone suggest me how can i implement celery task for each module. -
Ajax and HTML select options with Django
I have a form registration that include some select option fields, which has a country-specific field and a city-specific field. Each country has several cities of course, I want to make the city choices depend on the selected country. Meaning, after selecting a country, only the cities for that country appear in the next field. I know it is done with ajax, but I don't know ajax. I spent hours and hours to search for an example or method of work and did not find anything clear to help me If you have an example that you did before please put it here and help me. -
how can I build mongo db based django application on azure
there, I build a mongodb based django app, but I do not know how to migrate the application to azure. In addition, I will also want to use the cosmos db as the database on azure. Can somebody tell me the overflow? -
Django manytomany feild access single item, 'ManyRelatedManager' object has no attribute 'price'
class Cart(models.Model): user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2) quantity = models.IntegerField(default=0, null=True, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) @property def get_total_item(self): total = self.products.price * self.quantity return total class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path,null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ProductManager() @property def get_total_item(self): total = self.products.price * self.quantity return total (error in products,price how to access it ) In this self.products.price I cannot accesss the price from products i am trying to get a single value from product model but i dont know how to acsess in many to many realtionship -
Reverse to specific Bootstrap-Tab with Django CBV get_success_url()
I'm using Bootstrap Tabs https://getbootstrap.com/docs/4.0/components/navs/#tabs Is there a way to reverse to a specific Tab with get_success_url() ? Someting like (but this does not work): class UpdateModelView(UpdateView): model = Model def get_success_url(self): return '{}#secondTab'.format(reverse('myApp')) -
Using unique user identifier in Django logs
In my website I'd like to add logging of user actions (eg. user added/modified/deleted something, user visited some page, user logged-in/out). Just to be clear I'd need this identifier be unique but allow me to follow user and not change on every site (everything happens within my website). I have already logger in place, but I'm not sure how I can get unique user identifier. Currently it looks like this: logger.info('User %s entered website X', self.request.user) I know I could use request.user for logged-in users, but what with the rest? Right now everyone are AnonymousUser, but instead I'd like to have some unique identifier. I assume Django is already providing that, but question is - how I could access it. -
count how many items exist that have an age equal to or greater than 50
In the Python file, write a program to perform a GET request on the route https://coderbyte.com/api/challenges/json/age-counting which contains a data key and the value is a string which contains items in the format: key=STRING, age=INTEGER. here need to count how many items exist that have an age equal to or greater than 50, and print this final value. Example Input {"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"} Example Output 2 -
how to set session value as quarry set object
here is my code b = student_details.objects.all() request.session["b"]=b its giving me error TypeError at /logs Object of type QuerySet is not JSON serializable i want to fetch all data form student_details table and show it on display.html page def login(request): if request.session.has_key("b"): b= request.session['b'] return render(request,'display.html',{"b":b}) its showing me above error :( -
Django DictField with child param
class SomeSerializer(serializers.Serializer): some_field = serializers.DictField(child=SomeOtherSerializer()) some_other_field = serializers.BooleanField(default=False, required=False) class SomeOtherSerializer(serializers.Serializer): boolean_field = serializers.BooleanField(default=False, required=False) dict_field = serializers.DictField(required=False) And here is what the data looks like: {'some_other_field': True, 'some_field': {'boolean_field': True, 'dict_field': {}}} However, when I do serializer.is_valid() and serializer.errors I get the following: {'some_field': {'boolean_field': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got bool.', code='invalid')]} What am I doing wrong? If someone can explain this behaviour it would be greatly appreciated -
Pycharm debugger, does not go deep enough : Django project. [ fairly new to python/Django ]
I'm currently debugging my Django project [kind of first project in Django/python]. The debug 'Step Over' button in Pycharm seems to be going properly. However at a particular point, it does not go deep enough. Below is the code with the debug point (commented that particular line). Please note, it's a properly working project, although I have trimmed down the codes (like skipping import statements, class definitions etc) here to make it as simple as possible to represent my question. File: create_report_view.py Here is where I have set the debug point. from project.project_core.forms import BrandModelForm def post(self, request): brand_form = BrandModelForm(request.POST, request.FILES) if brand_form.is_valid(): # Debug point file_name_errors, csv_name_errors, file_name_alphanumeric_error = self._validate_data(brand_form) print(" And debug step goes on... ") So, the debugger skips what happens inside the .is_valid() call, where my validation runs, and jumps to next line in the above code. How do I force it to debug the .is_valid() method as well ? Dependent code blocks. Below is the definition of my model, where i mention the validators in it. File : models.py from django.db.models import Model from project.project_core.validators import ReportTypeValidator class BrandModel(Model): report_model = models.ForeignKey(ReportModel, models.CASCADE) name = models.CharField(max_length=256, db_index=True) review_file = models.FileField(upload_to='reviews/', validators=[ReportReviewValidator]) number_of_reviews = models.IntegerField(blank=True, … -
Django shell not printing QuerySet
In the commande prompt I have entering the same text as the book 'python crash course' on page 393. But my terminal is not giving the query set as it does in the book. I enter: >>> t.entry_set.all() I get back: <QuerySet [<Entry: Entry object (1)>, <Entry: Entry object (2)>]> -
Django server not responding
When I run the command django-admin startproject newsite in my root directory it works But afterwards when i give the command "python manage.py runserver" in my cmd it doesnot give any results and opens the the new commandline interface as itis ' C:\Users\Shiv Chandra Sraswat\Desktop\newsite>python manage.py runserver 0:8000 and there is no result the answer that comes is C:\Users\Shiv Chandra Sraswat\Desktop\newsite> ' Can anyone tell what is the error ? thank you -
how to replace pk with slug in detailview
how to make slug place pk? views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Category,Subcategory, Product, Characteristic class CategoryView(ListView): """list of categories""" model = Category class CategoryDetailView(DetailView): """Full description of categories""" model = Category models.py class Category(models.Model): name_category = models.CharField(verbose_name = 'name category', max_length = 100, null=True) image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic') def __str__(self): return self.name_category class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='category', related_name='sub') name_subcategory = models.CharField(verbose_name = 'name subcategory', max_length = 100, null=True) image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic') url = models.SlugField(max_length=160, unique=True, null=True) def __str__(self): return self.name_subcategory urls.py urlpatterns = [ path("", views.CategoryView.as_view()), path('<int:pk>/', views.CategoryDetailView.as_view(), name='category_detail'), ] in the link template I form like this {% for category in category_list %} <a href="{% url 'category_detail' pk=category.pk %}">{{category.name_category}}</a> <img src="{{category.image.url}}" width="100px" height="100px"> {% for img in category.sub.all %} {{ img.name_subcategory }} {% endfor %} {% endfor %} Now my links are formed like this http://127.0.0.1:8000/1/ how to make the place pk in the link substituted slug from the Subcategory model -
Not able to use Django treebeard or django-mptt with Djongo
Not able to use django treebeard or django-mptt with djongo. I am trying to build tree structure but i am using djongo to connect with mongoDB and django. Kindly help me with the alternate solution for the same. Getting the SQLDecodeError for both plugins while creating data from django-Admin -
How can I send an data to chart.js in python django?
I'm making a project about pull a user github API like this one https://octoprofile.now.sh/user?id=nathannewyen I don't know how to pass an data to another function in django Here is my views.py: def user(req, username): username = str.lower(username) # Get User Info with urlopen(f'https://api.github.com/users/{username}') as response: source = response.read() data = json.loads(source) # Get Limit Call API with urlopen(f'https://api.github.com/rate_limit') as response: source = response.read() limit_data = json.loads(source) # Get User Repo Info with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() sorted_by_stars = json.loads(source) sorted_by_forks = json.loads(source) sorted_by_size = json.loads(source) # Sorted by stars def sort_user_repo_by_stars(sorted_by_stars): return sorted_by_stars['stargazers_count'] sorted_by_stars.sort(key=sort_user_repo_by_stars, reverse=True) # Sorted by forks def sort_user_repo_by_forks(sorted_by_forks): return sorted_by_forks['forks'] sorted_by_forks.sort(key=sort_user_repo_by_forks, reverse=True) # Sorted by size def sort_user_repo_by_size(sorted_by_size): return sorted_by_size['size'] sorted_by_size.sort(key=sort_user_repo_by_size, reverse=True) created_at = data['created_at'] created_at = datetime.datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") created_at = created_at.strftime("%B %d, %Y") context = { 'username': username, 'data': data, 'created_at': created_at, 'limit_data': limit_data, 'sorted_by_stars': sorted_by_stars[:8], 'sorted_by_forks': sorted_by_forks[:8], 'sorted_by_size': sorted_by_size[:8], } return render(req, 'user.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = ["Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [23, 2, 3, 12, 2] data = { "labels": labels, "default": default_items, } return Response(data) and here is my urls.py: from django.urls import path from . import views … -
Django fails adding foreign key column to table on PostgreSQL (constraint does not exists)
I have 2 models ContainerType and EventType: class ContainerType(models.Model): code = models.CharField(max_length=3, db_column='ct_code') description = models.CharField(max_length=20, db_column='ct_description', blank=True, null=True) father_type = models.ForeignKey('self', on_delete=models.PROTECT, db_column='ct_id_container_father', blank=True, null=True) class Meta: db_table = '"clinical"."cd_container_type"' verbose_name = 'Container type' verbose_name_plural = 'Container types' def __str__(self): return self.code +' - '+ self.description class EventType(models.Model): code = models.CharField(max_length=3, db_column='et_code') description = models.CharField(max_length=20, db_column='et_description', blank=True, null=True) class Meta: db_table = '"clinical"."cd_event_type"' verbose_name = 'Event type' verbose_name_plural = 'Event types' def __str__(self): return self.code +' - '+ self.description And I'm trying to add a ForeignKey "father_type" relating EventType to ContainerType: class EventType(models.Model): code = models.CharField(max_length=3, db_column='et_code') description = models.CharField(max_length=20, db_column='et_description', blank=True, null=True) father_type = models.ForeignKey(ContainerType, on_delete=models.PROTECT, db_column='et_id_container_father', blank=True, null=True) class Meta: db_table = '"clinical"."cd_event_type"' verbose_name = 'Event type' verbose_name_plural = 'Event types' def __str__(self): return self.code +' - '+ self.description But when I apply the migration I get the following error: Running migrations: Applying clinical_data.0011_eventtype_father_type...Traceback (most recent call last): File "/pyprojects/venv/ehr/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedObject: constraint "cd_event_type_et_id_container_fath_fcbe1653_fk_cd_contai" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/pyprojects/venv/ehr/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, … -
Djnago Apps One Statoc for all templates
What is the best way to use Static files (css, js ...) for all apps templates? For example, I have a css file for all templates in different apps, should I place it to each templates folder? -
Django template variables not working in django-social-widget
In following line while sharing the content to twitter, the template variable is not interpreted. {% social_widget_render "twitter/share_button.html" href="{{ request.build_absolute_uri }}" %} instead of showing the actual url, it shows: -
Django : crypt password with SHA1
I want to reuse an old database for a project. All the passwords in this database are crypted with sha1. That's why I'm trying to crypt password with sha1 in django. I tried something with the hashlib library but it doesn't work. This is my code : serializer.py : from rest_framework import serializers import hashlib from .models import memberArea, category, product, byProduct, order, orderDetail class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input-type' : 'password'}, write_only=True) #The field will be hidden from the user class Meta: model = memberArea fields = ['name', 'email', 'phone', 'password', 'password2', 'deliveryAddress', 'postalCode', 'city'] extra_kwargs = { 'password': {'write_only':True}, #For security to hide the password (we can't read it) } def save(self): account = memberArea( name = self.validated_data['name'], email = self.validated_data['email'], phone = self.validated_data['phone'], deliveryAddress = self.validated_data['deliveryAddress'], postalCode = self.validated_data['postalCode'], city = self.validated_data['city'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match !'}) password = hashlib.sha1(password) account.password = password account.save() return account views.py : ... from .serializers import RegistrationSerializer ... @api_view(['POST', ]) def register(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): #Then we have access to the validated data in the file serializer.py account = serializer.save() #Call … -
URL dispatcher: cateogories and drafts
Django 3.0.7 urls.py urlpatterns = [ path('<slug:categories>/', include(('categories.urls', "categories"), namespace="categories")), ] categories/urls.py urlpatterns = [ path('', CategoryView.as_view(), name='list'), re_path(r'.+', include(('posts.urls.post', "posts"), namespace="posts")), ] This is my faulty attempt to write a regex to catch not less than one arbitrary symbol. posts/urls/post.py urlpatterns = [ path('draft/<slug:slug>/', PostDetailView.as_view(), name="draft_detail"), path('<slug:slug>/', PostDetailView.as_view(), name="detail"), ] First pboblem When I load http://localhost:8000/linux/install-os-ubuntu/, I get this: Page not found (404) Request Method: GET Request URL: http://localhost:8000/linux/install-os-ubuntu/ Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order: [name='home'] ^admin/ polls/ applications/ draft/authors/ authors/ email/ facts/ <slug:categories>/ [name='list'] <slug:categories>/ .+ draft/<slug:slug>/ [name='draft_detail'] <slug:categories>/ .+ <slug:slug>/ [name='detail'] tags/ [name='tags'] __debug__/ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, linux/install-os-ubuntu/, didn't match any of these. Another problem >>> p = Post.objects.first() >>> p.get_absolute_url() '/news/.efremov/' That is a dot appeared in the url. Could you help me understand what is going on here and how to organize: 1) http://localhost:8000/linux/ routes to CategoryView. 2) Anything else goes to PostDetailView with urls like: a) http://localhost:8000/linux/draft/install-os-ubuntu/ b) http://localhost:8000/linux/install-os-ubuntu/ -
Setting the value of a dropdown in django viewa
I have a HTML dropdown,When I select some value,it navigates to a different HTML page containing another dropdown.I want to set the dropdown in new page with the previous dropdown value.How can I accomplish this in views.py? -
how to find the other side of an Foreignkey field and auto-fill the next field with it
I'm new to Django, so sorry for Negligence: I have a model named score and the fields of that are exam, student, user and score. Also, my Student model is an abstract user and has an user OneToOne field in itself. What i want to do here is to auto-fill the user field in my Score model; So that means I want to get the user from the student field which the admin fills and the user field get filled by the user which is connected to the student field via ForeignKey. Here is the model: class Score(models.Model): exam = models.ForeignKey(Exam,on_delete=models.CASCADE,null=True) student = models.ForeignKey(Student,on_delete=models.CASCADE,null=True) user = models.ForeignKey(User,on_delete= models.CASCADE,null=True) score = models.FloatField(null=True) def __str__(self): return str(self.score) How should i do it ? from the beginning(getting the student's user) to the end(auto filling the user with it) I have tried a lot of thing(using default, save() method and none of them worked(at least, I didn't figured them out)) and I couldn't find out how should find the student's user. -
Wagtail - how to setup multiple paths with different templates to the same model instaces?
Imagine a Page model: class ItemPage(Page): featured = models.BooleanField(default=False) priority = models.IntegerField(default=0) This is model is served by Wagtail, on the url given by structure or the website (all instances are on the same place), for example: /items/1 /items/2 ... I would like to create a different path template, that would lead to the different template (same model, same data, different HTML/JS/CSS): /items-different-view/1 /items-different-view/2 ... I can use the Django mechanism for this - create a regex pattern in urls.py that triggers a custom function that returns HTTP response (the other template filled with data of the particular instance). But is there some more Wagtail way how to do it directly in the model without creation outlaying URLs and view function?