Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing django model attribute passed as a parameter
I'm using django with a legacy database where I can not change the original table columns. I have similar models which have slightly varying field names. The following model is an example. class EURegister(models.Model): record_id = models.AutoField(primary_key=True) reg_no = models.CharField(max_length=45, blank=True, null=True) company_name = models.CharField(max_length=300, blank=True, null=True) In some models, reg_no is a different name such as registration_id. Hence, I have to access the model attribute passed as an argument. But I can not use it since the model doesn't allow to use attributes as they were dict keys. It gives the following error. TypeError: 'EURegister' object is not subscriptable -
Django Dynamic initial values for current user
I want the current user to be able to upload a file in my html page. I try a method but it didn't work. I have an error message :"File.userFile" must be a "Customer" instance Thanks in advance! Here's my code models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.user.username class File(models.Model): userFile = models.ForeignKey(Customer, on_delete=models.CASCADE) document = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.document forms.py class FichierUpload(ModelForm): class Meta: model = File fields = '__all__' exclude = ['userFile'] views.py def my_view(request, **kwargs): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' # Handle file upload current_user= request.user.username #fileuser = Customer.objects.get(user=current_user) form = FichierUpload(request.POST or None, request.FILES) if request.method == 'POST': # if form.is_valid(): file = form.save(commit=False) file.userFile = request.user file.save() # Redirect to the document list after POST return redirect('my-view') # else: # message = 'The form is not valid. Fix the following error:' else: form = FichierUpload() # An empty, unbound form # Load documents for the list page documents = File.objects.filter(userFile__name=current_user).order_by('-uploaded_at') # Render … -
Django dynamic form subclass list
I'm trying to understand how can I define model as a class containing 2 integers and 1 charfield and then make it a part of another model. Example of data I need I guess in object oriented programming I should define model class like this: class Component(models.Model): pipe_type = models.CharField(max_length=200) length = models.IntegerField() amount = models.IntegerField() And then I don't know how can I use it with django models, it should be something like this: class Item(models.Model): name = models.CharField() components_needed = ? LIST OF Component class ? Also, since components needed size will wary for objects, it should be possible to extend it's size with button on a page, for example there could be 3 input fields and next to them would be "+" and "-" button to add/remove another set of 3 input fields I spent entire day looking for solution, but at this point I'm not sure if django can handle this. I'm new to python and django, so there are many things I do not understand. I will be grateful for any kind of help -
How can I nest one Django form within another?
I want to nest one of my forms - AddressForm, in a few different forms, without having to re-add all the fields to each form. I want to do this without relying on models, which is what Djangos inline form seems to do. I tried adding the address form as a field in the parent form, which renders correctly, but doesnt get returned when the form is cleaned. -
Building a Fantasy Football App. If player name is not in JSON data file, set score to zero. Sounds simple, but how do I get it to work?
I'm building a very simple fantasy football web-app using django for a course. One bug I discovered recently was that if a player isn't present in the JSON data that I'm pulling from an api, then it throws an error stating that the local variable for that player's score is being referenced before being assigned. Makes sense given that there is no actual data for that player. So, to fix this, I figured all I needed to do is add an elif (or else) statement to my logic to set that player's score to zero. Here's my code for this so far. for score in scores: if score['player_name'] in QBname: QBscore = float(score['points']) totalpoints.append(QBscore) I'm looping through a list called "scores" where I have the player scores coming in from an api call, then I'm comparing the player's name, which is stored in a variable called "QBname", to score['player_name]. Obviously, if score['player_name'] is a match and is in "QBname", I'm then appending that player's score to the variable "totalpoints." Now, to "fix" the problem, and assign a score of 0 to an absent player, I thought I would need something like this... if score['player_name'] in QBname: QBscore = float(score['points']) totalpoints.append(QBscore) … -
Error in passing filtered data to template. Reverse not found. 1 pattern(s) tried. What query should be used to avoid this error?
I am trying to create a dynamic url that displays all the sub-courses in course. To do this I am passing the course name through the url and filtering the sub-courses to only send the ones for this course. However I cannot seem to find the correct query to filter and pass the data. I attempted to follow the official Django documentation and search stack to find an answer but found nothing. My experimentation has also gotten me no results. the view is def subcourse(request, course): if request.method == 'GET': course = Course.objects.get(slug=course) subcourses = Subcourse.objects.all().filter(course=course) context = {'subcourses': subcourses} return render(request, 'subcourse.html', context) and my models are: class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) thumbnail = models.ImageField( upload_to='images/courses', null=True, blank=True ) position = models.IntegerField() def __str__(self): return self.title class Subcourse(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) thumbnail = models.ImageField( upload_to='images/subcourses', null=True, blank=True) position = models.IntegerField() def __str__(self): return self.title and the current error message is Reverse for 'subcourse' with arguments '('',)' not found. 1 pattern(s) tried: ['training/(?P<course>[-a-zA-Z0-9_]+)$'] I have read through the documentation regarding queries and filters but cannot seem to find my error. -
Django avatar images broken
I'm trying to learn django and was following this tutorial: https://django-avatar2.readthedocs.io/en/latest/ I can upload an image and it shows up in myproject/avatars/admin/ as it should, but when I go to the html page, the image appears broken. in u.html I have: {% load avatar_tags %} {% avatar user 150 %} In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'avatar', 'boards', In urls.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^admin/', admin.site.urls), url(r'^u/(?P<username>[\w.@+-]+)/$', views.u, name='u'), url('avatar/', include('avatar.urls')), ] When I upload the avatar or go to my profile page the image is broken. Change page Direct address to image -
Django RestFrameWork Security
How can I protect my endpoints? Currently, I'm working on a project but I don't know how to secure the API URLs. How can I prevent the user from login through the rest framework (backend using the API URL)? I'm currently using IsAuthenticated but still, it gives a prompt to enter username and password which I want to prevent. -
How to get querysets which "has" value on the lists?
I'm not sure my title is precise question I wanna ask if i have list like [2, 3, 4] Then i wanna get querysets which has list of value!! 'in' is simillar with my question but kinda different. (https://docs.djangoproject.com/en/dev/topics/db/queries/#the-pk-lookup-shortcut) For example, Blog.objects.filter(pk__in=[1,4,7]) then it will return queryset which has 1 and 4 and 7. I wanna get queryset has 1 or 4 or 7 !! Somebody help me :( class UniversityViewSet(generics.ListAPIView): """ View Set of University Model """ queryset = University.objects.all() serializer_class = UniversitySerializer filter_class = UniversityFilter def get_queryset(self): queryset = University.objects.all() topiks = self.request.query_params.get("topiks", None) if topiks is not None: topik_coverage = topiks.split(",") for topik in topik_coverage: queryset = queryset.filter( tuitions__requirement_topik__in=topik_coverage <=== HERE!!!!! ) return queryset else: return queryset -
Django admin - Allow deletion only for users in a specific group for all models
I want to allow hard deletion in the Django administration site only for members of a specific group. To achieve this, I could create a mixin where I override has_delete_permission and get_actions to check if the user is a member of the group. Then, I could use it in all admin classes. However, I have a lot of admin classes and I don't want to update all of them and to always think about adding this mixin every time I create a new one. Is there a better way to achieve the same? -
What is the best text to Html formatter to use for my Django project
I am currently using markdown but I don't like the way my code's are being formatted. Is there a better text formatter that can give my code snippets a nice look..?? -
sockjs.js?9be2:689 Uncaught Error: SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS
I am deploying Vue + Django app in Heroku but Django is working well coming to the vuejs it is displaying the above error. What I need to change in the place of "http://127.0.0.1:8080". Actually, Django templates are working well but coming to the Vue js files it is not displaying and I got the following error Uncaught Error: SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS at new SockJS (sockjs.js?9be2:689) at new SockJSClient (SockJSClient.js?0a33:43) at initSocket (socket.js?e29c:20) at Object.eval (client?7017:176) at eval (index.js?http://127.0.0.1:8080&sockPath=/sockjs-node:177) at Object../node_modules/webpack-dev-server/client/index.js?http://127.0.0.1:8080&sockPath=/sockjs-node (bundle.js:9374) at __webpack_require__ (bundle.js:790) at fn (bundle.js:101) at Object.1 (bundle.js:9967) at __webpack_require__ (bundle.js:790) vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" transpileDependencies: ["vuetify"], publicPath: "http://127.0.0.1:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, //uncomment before executing 'npm run build' css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, } }; -
How should i create, save and open user specific checklist data in django?
I need to develop this app using Django. I have given checklist of 25 checks. This checklist is related to PCB designing. The checklist will get updated as PCB passes through different stages. Before sending PCB for manufacturing user has to complete all the checks. To avoid the error in later stages and the cost this checklist has been created. Requirement is, User need to login to the application. After login if he wants to create new project, he should be able to create new project and after creating a new project the checklist should open when he should be able to check and uncheck those 25 checks. Suppose user is working on 5 different PCB designs then he should be able to save those 5 projects individually. After login if he wants to open old project then also, he should be able to open the old project and see how many checks he has completed and how many are remaining? I am new to Django. Before 2 weeks I started learning Django. I already have created user registration and login page and stored user data in postgresql. Now my question is, how should I create or open a new … -
Local python module overrides module installed with pip
I am having issues with importing, my own, pip package named the same as a module inside a django-app. Lets say my own pip module is called: fancymodule. I then have a module-folder inside a django-app named the same: * django-project * payments * models.py * fancymodule/ * __init__.py The problem I am having, is that inside payments/models.py, I import: from fancymodule import ApiClient This is suppose to reference the fancymodule installed through pip. But is instead referencing the module inside the payments-django-app instead. If I wanted to reference the module inside the payments-django-app, in my head, this should be: from payments.fancymodule import whatever I get that from the view of payments/models.py, the import fancymodule .. will reference the module inside the folder it self of the specified name.. but can i change/fix this? FYI: Working on an old legacy project. Home someone can help. -
Is FILE_UPLOAD_DIRECTORY_PERMISSIONS required after upgrade to Django 3.1?
There was a web app on Django 2.x with no FILE_UPLOAD_DIRECTORY_PERMISSIONS and FILE_UPLOAD_PERMISSIONS. After upgrade to Django 3.1 (through 3.0) (new) user media files saved to new directories are inaccessible to users via nginx static files serving. They become accesible if I manually fix permissions with chmod -R 755 . in media directory. And I guess it will be fixed for all new files when I set FILE_UPLOAD_DIRECTORY_PERMISSIONS. The question is why it was not needed in django 2.x and how do I not miss something similar next time? Apparently, FILE_UPLOAD_DIRECTORY_PERMISSIONS is not mentioned in https://docs.djangoproject.com/en/3.1/releases/3.0/ and https://docs.djangoproject.com/en/3.1/releases/3.1/ -
how can i save an inline form to the current parent i am working
to be more specific i have a questionaire model and a question with many to many relationship. class poll(models.Model): name=models.CharField(max_length=100) class question(models.Model): text = models.CharField(max_length=200) polls = models.ManyToManyField(poll) in the admin.py i have admin.site.register(question) class questionsinline(admin.TabularInline): model = question.polls.through extra = 1 class polladmin(admin.ModelAdmin): inlines = [questionsinline,] # admin.site.register(question,questionsinline) admin.site.register(poll,polladmin) when i open the admin form to add a new questionnaire it shows as well the option to add a new question. the problem is tha adding a new question needs a questionanaire that don't exists because i am currently makin it -
Django error: Process finished with exit code 134 (interrupted by signal 6: SIGABRT) python2.7 django project
Im facing a very strange error from few days now. I have a python2.7 project that was running smoothly but since few days its been throwing an error: Process finished with exit code 134 (interrupted by signal 6: SIGABRT) Im using virtual environment for my project. What happened was that few days ago I tried installing nginx using brew command and what I believe is brew updated some dependencies that were being used for python2.7 project (this is what i think might be the case). Now since that day , Im facing this issue and I have googled it everywhere but couldn't resolve. Below is some information you might need to figure out. I urgently need to resolve this issue since alot depends on it. Thanks in advance. my requirements.txt file asn1crypto==0.24.0 beautifulsoup4==4.3.2 boto==2.49.0 boto3==1.8.7 botocore==1.11.9 cachetools==3.1.0 certifi==2018.11.29 cffi==1.12.2 chardet==3.0.4 cryptography==2.6.1 Django==1.6.5 django-appconf==0.6 django-autoslug==1.7.2 django-blog-zinnia==0.14.1 django-ckeditor-updated==4.4.4 django-common-helpers==0.6.1 django-compressor==1.4 django-cors-headers==1.1.0 django-crispy-forms==1.4.0 django-cron==0.3.3 django-filter==0.15.3 django-hosts==0.6 django-htmlmin==0.11.0 django-imagekit==3.2.5 django-mobi==0.1.7 django-mobile==0.3.0 django-mptt==0.6.1 django-redis==4.4.0 django-sass-processor==0.2.6 django-simple-captcha==0.4.2 django-storages==1.1.8 django-tagging==0.3.2 django-xadmin==0.5.0 django-xmlrpc==0.1.5 djangorestframework==2.4.8 docutils==0.14 enum34==1.1.6 futures==3.2.0 google-api-core==1.7.0 google-auth==1.6.2 google-auth-oauthlib==0.2.0 google-cloud-bigquery==1.9.0 google-cloud-core==0.29.1 google-resumable-media==0.3.2 googleapis-common-protos==1.5.6 html5lib==1.0b8 httplib2==0.9 idna==2.8 ipaddress==1.0.22 jmespath==0.9.3 libsass==0.18.0 lxml==3.3.5 Markdown==2.6.7 MySQL-python==1.2.5 nginxparser==1.0.1 numpy==1.16.1 oauth2==1.5.211 oauthlib==3.0.1 pandas==0.24.1 pandas-gbq==0.9.0 pilkit==2.0 Pillow==5.3.0 protobuf==3.6.1 pyasn1==0.4.5 pyasn1-modules==0.2.4 pycparser==2.19 pycrypto==2.6.1 pydata-google-auth==0.1.2 pyOpenSSL==19.0.0 … -
Exit server terminal while after celery execution
I have successfully created a periodic task which updates each minute, in a django app. I everything is running as expected, using celery -A proj worker -B. I am aware that using celery -A proj worker -B to execute the task is not advised, however, it seems to be the only way for the task to be run periodically. I am logging on to the server using GitBash, after execution, I would like to exit GitBash with the celery tasks still being executed periodically. When I press ctrl+fn+shift it is a cold worker exit, which stops execution completely (which is not desirable). Any help? -
Django can't multiply sequence by non-int of type 'str'
I have this logic in my views and models, in my views i get the data of what the user inputted, and in my models, i have an automatic computation of discount_price_formula, and other_discount_price_formula why i am having this error? can't multiply sequence by non-int of type 'str' this is my views.py otherdiscountpercentage = request.POST.get("otherdiscountpercentage") S_price = request.POST.get("price") otherdiscountprice = request.POST.get("otherdiscountprice") discountpercentage = request.POST.get("discountpercentage") discountprice = request.POST.get("discountprice") insert_data = Product( price=S_price, discount_percentage=discountpercentage, discount_price=discountprice, Other_discount_percentage=otherdiscountpercentage, Other_discount_price=otherdiscountprice, ) this is my models.py class Product(models.Model): price = models.FloatField(null=True, blank=True, verbose_name="Unit Price") discount_percentage = models.FloatField(max_length=500, null=True, blank=True) discount_price = models.FloatField(null=True, blank=True) Other_discount_percentage = models.FloatField(null=True, blank=True) Other_discount_price = models.FloatField(null=True, blank=True, default=0.0) discount_price_formula = models.FloatField(null=True, blank=True) other_discount_price_formula = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): self.discount_price_formula = self.price - (self.price * self.discount_percentage) self.other_discount_price_formula = (self.price - (self.price * self.discount_percentage)) - ((self.price - (self.price * self.discount_percentage)) * self.Other_discount_percentage) return super(Product, self).save(*args, **kwargs) def __str__(self): suser = '{0.product}' return suser.format(self) this is my traceback Traceback: File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\onlinestoreapp\customAdmin\views.py" in InsertProduct 293. insert_data.save() File "C:\Users\Desktop\onlinestoreapp\customAdmin\models.py" in save 209. self.discount_price_formula = self.price - (self.price * … -
How to get domain url in Django?
I want to get domain url to use in view of Django and I use Nginx in my server but I got a problem: I have tried request.META['HTTP_HOST'] or request.build_absolute_uri but it only return 127.0.0.1:8000 (proxy pass in nginx config to Django project). So are there any solution for this? Thanks in advance. -
Django CBV (ListView) paginate_by not allowed with queryset
I'm trying to paginate my tasks but I can't views.py: class DashboardTaskAppView(LoginRequiredMixin, ListView): model = Task template_name = "task_app/task_dashboard.html" context_object_name = 'tasks' today = datetime.date.today() paginate_by = 5 def queryset(self): ordering = ['-due_date'] usr = self.request.user return Task.objects.filter(Q(responsable=usr)) Without paginate_by = 5: WITH paginate_by = 5: TypeError at /task/ object of type 'method' has no len() Request Method: GET Request URL: http://localhost:8000/task/ Django Version: 3.1.2 Exception Type: TypeError Exception Value: object of type 'method' has no len() Exception Location: C:\Users\caior\Desktop\Python\simple_task\venv\lib\site-packages\django\core\paginator.py, line 95, in count Python Executable: C:\Users\caior\Desktop\Python\simple_task\venv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\caior\\Desktop\\Python\\simple_task', 'C:\\Users\\caior\\Desktop\\Python\\simple_task\\venv\\Scripts\\python38.zip', 'c:\\users\\caior\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\caior\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\caior\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\caior\\Desktop\\Python\\simple_task\\venv', 'C:\\Users\\caior\\Desktop\\Python\\simple_task\\venv\\lib\\site-packages'] Server time: Mon, 09 Nov 2020 09:48:07 +0100 Console: File "C:\Users\caior\Desktop\Python\simple_task\venv\lib\site-packages\django\core\paginator.py", line 95, in count return len(self.object_list) TypeError: object of type 'method' has no len() [09/Nov/2020 09:48:07] "GET /task/ HTTP/1.1" 500 112987 Any help is appreciated, thanks a lot in advance, Kind regards -
how to fix header in datatable with sidebars?
I have used DataTable and tried to fix the header, it is fine until I close the sidebar, when I close the sidebar then header remain constant while scrolling, -
How to break “for loop” in Django template
My code is: {% for key, value in section.items %} {% for key_t, value_t in title.items %} {% if value_t.section_id == key|add:"0" %} <li class="nav-item-header"><div class="text-uppercase font-size-xs line-height-xs"> {{value.title}}</div> <i class="icon-menu" title="Tables"></i></li> {% endif %} {% endfor %} {% endfor %} I want to break the for loop when if the condition is true. like as {% for key, value in section.items %} {% for key_t, value_t in title.items %} {% if value_t.section_id == key|add:"0" %} <li class="nav-item-header"><div class="text-uppercase font-size-xs line-height-xs"> {{value.title}}</div> <i class="icon-menu" title="Tables"></i></li> {% endif %} {{break}} {% endfor %} {% endfor %} How is it possible? please help me... -
How to send Session ID in Cookies using Django Rest Framework
I'm trying to make an cart system using Django. I want to use session id to store products in cart for anonymous users. I am also using Django Rest Framework to create the API which will also be used in an Android Application. Whenever I call the API on 127.0.0.1:8000, it shows me this field on the Response Headers: Set-Cookie: sessionid=nypgq3o486r2qk4ei1excduthrfjuy83; expires=Mon, 23 Nov 2020 08:07:20 GMT; Max-Age=1209600; Path=/ But on calling the API using axios on localhost:3000 this field is missing and no session id is stored on the cookies. I am aware its a cors issue and I have tried few solutions but nothing worked. settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = False What can I do to send the cookies automatically like it is working 127.0.0.1:8000? -
Not authenticated error while using stripe
i am creating an ecommerce website where i have included stripe payment method but when i submit the data there occur not authenticated error. i have no idea what is going wrong, i have followed as same as the video and tried many thing to solved this but still that error was occuring here is my VIEWS.py from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, DetailView, View from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.contrib.auth.mixins import LoginRequiredMixin from django.conf import settings from django.utils import timezone from django.contrib import messages from .forms import RegistrationForm from .models import * from .forms import * import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered = False) context = {'order': order} return render(self.request, "payment.html", context) def post(self, *args, **kwargs): order = Order.objects.get(user= self.request.user, ordered = False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: # Use Stripe's library to make requests... charge = stripe.Charge.create( amount= amount , currency="usd", source= token ) # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True …