Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join with OneToOneField relathionship django
I have two models with OneToOneField relationship and I want to somehow join them and be able to access the attribute of the one model from the other. My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My views.py is as follows: @api_view(['GET']) def result(request): results_list = Result.objects.all() num_results_list = Result.objects.all().count() if num_results_list < RES_LIMIT: serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) else: results_list = Result.objects.order_by('-created_at')[:RES_LIMIT] serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) Right now the query is as follows: [OrderedDict([('id', 1), ('HVAC_flex', [49.0, 27.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), ('DHW_flex', [4.0, 0.0, 45.0, 4.0, 20.0, 33.0, 42.0, 13.0]), ('lights_flex', [6.0, 8.0, 0.0, 0.0, 0.0, 18.0, 28.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', 2), ('HVAC_flex', [0.0, 0.0, 15.0, 0.0, 23.0, 6.0, 0.0, 0.0]), ('DHW_flex', [1.0, 2.0, 7.0, 47.0, 1.0, 19.0, 37.0, 9.0]), ('lights_flex', [40.0, 28.0, 34.0, 6.0, 8.0, 43.0, 6.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', … -
Django admin - admin inheritance
When registering django admin, I inherited another admin, but I don't know why the model of list_display is changed. Let me explain the situation in detail with code. @admin.register(User) class UserAdmin(models.Model): list_display = [a.name for a in User._meta.concrete_fields] @admin.register(Sales) class SalesAdmin(UserAdmin): pass According to the code above, SalesAdmin Admin appears to inherit from UserAdmin. In this case, shouldn't list_display of User model appear in list_display? I don't understand why the list_display of Sales Model comes out. If I want to display the list_display of the Sales model while inheriting UserAdmin, shouldn't I have to redeclare the list_display as shown below? @admin.register(User) class UserAdmin(models.Model): list_display = [a.name for a in User._meta.concrete_fields] @admin.register(Sales) class SalesAdmin(UserAdmin): list_display = [a.name for a in Sales._meta.concrete_fields] I did not redeclare list_display, but I do not understand whether it is automatically output as the list_display of the changed model. If anyone knows, please explain. -
How to get POST and create message on Django using DetailView
I have Post model and Message model. I want to get POST, create message on one post and preview it. I have ValueError Cannot assign "<bound method PostDetailView.post of <blog.views.PostDetailView object at 0x7fa9a370b8>>": "Message.post" must be a "Post" instance. at body = request.POST.get('body') How can I do this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message( user = request.user, post = self.post, body = request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
UnboundLocalError local variable 'context' referenced before assignment Django
I get the error below immediately after i add a new root url inside the root urls.py. When i remove the dashboard view, url and i try to load index view, it renders successfully. What am i doing wrong or what can i do to resolve the issue. Error message UnboundLocalError at /blogapp/ local variable 'context' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/blogapp/ Django Version: 4.0.2 Exception Type: UnboundLocalError Exception Value: local variable 'context' referenced before assignment My views from multiprocessing import context import re from django.shortcuts import render from django.http import HttpResponse from .odd_finder_func import * def index(request): if request.method == 'POST': odd1 = float(request.POST.get('odd1')) odd2 = float(request.POST.get('odd2')) odd3 = float(request.POST.get('odd3')) func_def = odd_finder_true(odd1, odd2, odd3) context = { 'Juice': func_def['Juice'], 'TotalImpliedProbability': func_def['TotalImpliedProbability'], 'HomeOdd': func_def['HomeOdd'], 'DrawOdd': func_def['DrawOdd'], 'AwayOdd': func_def['AwayOdd'], 'Home_True_Odd': func_def['Home_True_Odd'], 'Draw_True_Odd': func_def['Draw_True_Odd'], 'Away_True_Odd': func_def['Away_True_Odd'], 'True_Probability': func_def['True_Probability'] } context = context return render(request, 'index.html', context) def dashboard(request): return render(request, 'dashboard.html') blogapp urls.py from django.urls import path from .views import * from . import views urlpatterns = [ path('', views.index, name='index'), ] myblog urls.py the root file. from django.contrib import admin from django.urls import path, include from blogapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.dashboard, name='dashboard'), … -
Querying within a list of dicts within a Django model JSONField
I'm trying to query an element within a list of dicts in a Django JSONField. I can find similar questions to mine but not one that covers what I'm trying to do. It seems like it should be simple and fairly common so I suspect I'm missing something simple. So. to expand slightly on the example in the Django docs Let's say I have a Dog model with a JSONField named data and it has some data like so: Dog.objects.create(name='Rufus', data = {"other_pets": [{"name", "Fishy"}, {"name": "Rover"}, {"name": "Dave"}]} ) There's a key named "other_pets" which is a list of dicts. I would like to write a query which returns any models which includes a dict with the key name=="Dave" I am able to directly do this if I refer to the element by the index, eg: Dog.objects.filter(data__other_pets__2="Dave") Would return me the row, but I need to reference the index of the list element, and both the position of the item I'm looking up, and the size of the list vary among models. I thought that maybe: Dog.objects.filter(data__other_pets__contains={"name":"Dave"}) Would work but this returns no elements. Is what I'm trying to do possible? As an aside, is it possible to add … -
Django project requirements missing after Ubuntu Jellyfish update
After updating Ubuntu to the latest update, Pycharm tells me required packages are missing but the virtual environment is activated and the packages are all there. Trying to runserver results in ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Trying to install packages again results in Invalid Python SDK Anyone having this problem after the update? Thanks in advance. -
Django - Protect/Redirect a page after session required to see that page is deleted
I use an external API for authentification. In the view i put a request.session to display, after correct login, user information that im getting from that API.Everything work (log in/ log out/ info displays). I the template i show user info only if is a session active/valid after correct login. But after logout (delete that session in the view logout) if i try to access that info page the info is not show but get an error "KeyError at..." | and name of the session. Is good that now show info but i want to redirect from that page if is not a session active/valid and i don't know how. I tried to use @login_required but in my case i don't user is not ok because i use authentification with an API. Any suggestion how to redirect from the template/page (view def dashboard) if the session is not prezent/was deleted ? Thank you. Below my settings view.py def loginPL(request): if request.method == 'POST': client = Client(wsdl='http://.....Http?wsdl') marca = request.POST['marca'] parola = request.POST['parola'] try: login = (client.service.Login(marca, parola)) except: messages.error(request, "") if login > 0: # print(login) request.session['loginOk'] = login return redirect('login:dashboard') else: messages.error(request, "utilizatorul sau parola nu sunt corecte / … -
Django Dependent/Chained Dropdown List in a filter
I am using Django to implement my web page; in this page I have a classic item list that I manage with a for loop. I also implement a filter as a form (with search button) to filter the items. I know how can I implement a dropdown List (first code) and I know how can I implement a form filter (second code). DROPDOWN LIST (JQUERY CODE) <script> $( document ).ready(function() { var $provvar = $("#provddl"); $uffvar = $("#uffddl"); $options = $uffvar.find('option'); $provvar.on('change',function() { $uffvar.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> FORM FILTER <form> <div> <label>C: </label> {{ myFilter.form.C }} </div> <div> <label>D: </label> {{ myFilter.form.D }} </div> <button type="submit">Search</button> </form> My problema is that I don't know how can I implement a the Dependent Dropdown List in my filter. -
I need a detailed explanation of the DJANGO get_context_data() function below
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context Please i need a detailed explanation of the function above especially on line: context['now'] = timezone.now() -
Django make search side widget conncet html
Sorry my english not good please forgive me Hi I want make post search side widget i make search widget is can work but i can't connect html side search widget and work how can i connet it enter image description here my search widget of html <div class="card mb-4"> <div class="card-header">Search</div> <div class="card-body"> <div class="input-group"> <input class="form-control" id="search-input" type="text" placeholder="Enter search term..." aria-label="Enter search term..." aria-describedby="button-search"/> <button class="btn btn-primary" id="button-search" type="button" onclick="searchPost();">Go!</button> </div> </div> </div> and i want connet html search widget about this! <h1>Blog Search</h1> {% if search_info %}<small class="text-muted">{{ search_info }}</small>{% endif %} <br> <form action="." method="post"> {% csrf_token %} {{ form.as_table }} <input type="submit" value="Submit" class="btn btn-primary btn-sm"> </form> <br/><br/> {% if object_list %} {% for post in object_list %} <h2><a href='{{ post.get_absolute_url }}'>{{ post.title }}</a></h2> {{ post.modify_date|date:"N d, Y" }} <p>{{ post.description }}</p> {% endfor %} {% elif search_term %} <b><i>Search Word({{ search_term }}) Not Found</i></b> {% endif %} -
KeyError: 'created_at' in django rest serializer
I am getting the following error, while I am trying to save some data coming from a POST request to a database: KeyError: 'created_at' My views.py is as follows: @api_view(['GET', 'POST']) def event(request): if request.method == 'POST': serializer = EventSerializer(data=request.data) if serializer.is_valid(): DR_notice = serializer.data['dr_notice_period'] DR_duration = serializer.data['dr_duration'] DR_trigger = serializer.data['created_at'] DR_start, DR_finish, timesteps = DR_event_timesteps(DR_notice, DR_duration, DR_trigger) serializer.save(user_id_event=request.user, dr_start=DR_start, dr_finish=DR_finish, timesteps=timesteps) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) dr_start = models.DateTimeField(blank=True, null=True) dr_finish = models.DateTimeField(blank=True, null=True) timesteps = models.IntegerField(blank=True, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): created_at = serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S", read_only=True) class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): HVAC_flex = serializers.ListField(child=serializers.FloatField()) DHW_flex = serializers.ListField(child=serializers.FloatField()) lights_flex = serializers.ListField(child=serializers.FloatField()) class Meta: model = Result fields = ('__all__') As I can understand created_at takes its value when … -
Rich text editor for Django with comments/annotation (open source)
Is there anyone succeeded integrating any rich text editor through Django along with inline comments option? I refer inline comment as highlighting a word or sentence in the text editor and adding comments (annotation). When and who commented to be displayed on the side like a thread. I have tried ckeditor, tinymce, summernote etc and nothing seems to have this functionality without premium licensing. Any leads? -
Pass user access token from Django app to ELasticsearch
Im developing a django app that requires users to authenticate via azure ad (Oauth2). The app also interacts with an elasticsearch service that requires the same oauth2 authentication. during development I have used a static username and password to login like this: user_name = "elastic" host_ip = "127.0.0.1" host_ports = 9200 elk_url = f'https://{user_name}:{ESPASSWORD}@{host_ip}:{host_ports}' ELASTICSEARCH_DSL = { 'default': { 'hosts': elk_url, 'ca_certs': False, 'verify_certs': False, } } How can I pass the users token to the elasticsearch service? -
How can I sort instances by a fk related field in a serializer in Django?
According to a prior answer to one of my questions I am trying to re-arrange the queryset qs_payments of objects by field month utilising their fk relationship. The statement in my prior enquiry was you can just serialize the Payments on each Month directly But how would I basically achieve this? As far as I understand I have to use the serializer for the months model then and tell it to sort the qs by month? # models.py class Period(models.Model): period = models.DateField() class Payment(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) amount = models.PositiveIntegerField() # serializers.py class PaymentSerializer(serializers.ModelSerializer): class Meta: model = Payment fields = '__all__' class PeriodSerializer(serializers.ModelSerializer): class Meta: model = Period fields = '__all__' class PayrollRun(APIView): def get(self, request): # Get the related company according to the logged in user company = Company.objects.get(userprofile__user=request.user) # Get a queryset of payments that relate to the company and are not older than XX days qs_payments = Payment.objects.filter(offer__company=company) print(qs_payments) serializer = PaymentSerializer(qs_payments, many=True) return Response(serializer.data) The desired output is that I want to map each month to a React component containing all line items of that particular month. So I need (at least imho) a dictionary of months each having … -
django nested inline formsets with adding fields dynamically
I need a form for grand-parent parent and children form which will go like this grand-parent-- parent-- children in which I can add n number of parent for grand parent and n number for children for each parent , I have implemented this function in django's admin page using django-super-inlines thispip package but I need it for front end. Any help? and Thanks in advance -
JWT Cookie sent as Set-Cookie causing "Invalid Signature" in DRF jwt
I've been trying to solve this problem a week ago, from now on after looking for a solution in almost every forum, blog and lib's github issues I realized that it gonna be easier asking here. I have a django app using JWT for authentication (Web and Mobile), when I change the user email the mobile app (react native) keeps sending the old jwt in cookies to server which leads to an "Invalid Signature" response (in any endpoint including login) Here is my djangorestframework-jwt conf: JWT_AUTH = { 'JWT_VERIFY_EXPIRATION': True, 'JWT_AUTH_COOKIE': "JWT", 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_ALLOW_REFRESH': True, } Setting this line 'JWT_AUTH_COOKIE': "JWT", To 'JWT_AUTH_COOKIE': None, The server won't look for jwt cookies in request however the next api calls don't find token in Authorization Header which leads to Authentication credentials were not provided Even sending the token in Header. At web app there is no problem with that, so I'd like to know how can I fix it, looking for a way to stop sending JWT cookie from mobile app. -
Django silently removes constraints when removing columns, then arbitrarily choses to include them in migrations
I’ve encountered an odd bug(?) in Django in our production code. Dropping a column manually in migrations without removing its constraints leads to Django being unaware those constraints have been removed, and auto-generating incorrect migrations. A short example: Creating the migrations for this schema: class M(): a = models.IntegerField(default=1) b = models.IntegerField(default=2) class Meta: constraints = [ UniqueConstraint( name="uniq_ab_1”, fields=[“a”, “b”] ) ] Create the constraint uniq_ab_1 is Postgres as expected (when using the \d+ command on the table to visualise) However, this manual migration will remove the constraint, due to one of it’s member columns being deleted, this is just standard Postgres behavior: migrations.RemoveField( model_name=“m”, name=“a”, ), migrations.AddField( model_name=“m”, name=“a”, field=models.IntegerField(default=6), ), This migration runs just fine. I can even modify the field of M again and run a further migration. However, using \d+ reveals that the uniq_ab_1 constraint` is gone from the database. The only way I found out about this behaviour was renaming the constraint to uniq_ab_2, then auto-generating migrations and getting the error: django.db.utils.ProgrammingError: constraint "uniq_ab_1" of relation … does not exist. In other words, on a rename, Django become aware a rename was happening and tried to remove the constraint from the database, in spite … -
Error during template rendering / __str__ returned non-string (type NoneType)
I was trying to edit from Django admin panel then this error occure Error: Error during template rendering In template D:\Django\new\venv\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 str returned non-string (type NoneType) enter image description here models.py looks like: class hotel(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) hotel_name = models.CharField(max_length=500, null=True) registration_no = models.CharField(max_length=500, null=True) company_PAN_number = models.CharField(max_length=500, null=True) registered_owner_name = models.CharField(max_length=500, null=True) gender = models.CharField(max_length=100, blank=True, null=True, choices=gender_choice) email = models.EmailField(max_length=500, null=True) phone_no = models.CharField(max_length=500, null=True) website = models.URLField(max_length=500, null=True) registration_certificate = models.ImageField(null=True, upload_to='documents/%y/%m/%d/') PAN_certificate = models.ImageField(null=True, upload_to='documents/%y/%m/%d/') citizen_id_front = models.ImageField(null=True, upload_to='citizen_id/%y/%m/%d/') citizen_id_back = models.ImageField(null=True, upload_to='citizen_id/%y/%m/%d/') verified_hotel = models.BooleanField(default=False, null=True) def __str__(self): return self.hotel_name class hotel_application_status(models.Model): hotel = models.ForeignKey(hotel, null=True, on_delete=models.CASCADE) resubmitted = models.BooleanField(default=False, null=True) comment = models.CharField(max_length=500, null=True) def __str__(self): return self.hotel.hotel_name -
AWS ElasticBeanstalk Django display images
i uploaded my Media directory which contains my Images but i cant access it to display my images. My images are correctly being uploaded when i send them, but i cant view them in the page Im utilizing ElasticBeanstalk and RDS - Mysql I only configured my RDS everything else like EC2, S3 are automattically configured by ElasticBeanstalk static-files.config: option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static /media: media django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: store.wsgi:application 01_packages.config: packages: yum: python3-devel: [] mariadb-devel: [] models.py: class Product(models.Model): image = models.ImageField(upload_to='product_images/%Y/%m/%d') settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' my html: <a href="{{product.get_absolute_url}}"> <img class="default-img" src="{{product.image.url}}}" alt="550x750"> </a> -
Django timezone issue?
I'm not sure what causes this issue but this has been a headache for me. Sometimes in the morning there will be a runtime error (see below log). And after that, almost all the views will trigger the same error, until I restart the httpd service. (Something related to the cache?) I'm not sure if there is something wrong with my timezone setting? I'm using Python 3.10 and Django 4.0.2. Any suggestions will be helpful. File "/var/www/venv310/lib/python3.10/site-packages/django/db/models/lookups.py", line 96, in process_lhs sql, params = compiler.compile(lhs) File "/var/www/venv310/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 463, in compile sql, params = node.as_sql(self, self.connection) File "/var/www/venv310/lib/python3.10/site-packages/django/db/models/functions/datetime.py", line 47, in as_sql tzname = self.get_tzname() File "/var/www/venv310/lib/python3.10/site-packages/django/db/models/functions/datetime.py", line 25, in get_tzname tzname = timezone.get_current_timezone_name() File "/var/www/venv310/lib/python3.10/site-packages/django/utils/timezone.py", line 79, in get_current_timezone_name return _get_timezone_name(get_current_timezone()) File "/var/www/venv310/lib/python3.10/site-packages/django/utils/timezone.py", line 74, in get_current_timezone return getattr(_active, "value", get_default_timezone()) File "/var/www/venv310/lib/python3.10/site-packages/django/utils/timezone.py", line 60, in get_default_timezone return zoneinfo.ZoneInfo(settings.TIME_ZONE) File "/usr/local/python-3.10/lib/python3.10/weakref.py", line 285, in setdefault self.data[key] = KeyedRef(default, self._remove, key) File "/usr/local/python-3.10/lib/python3.10/weakref.py", line 354, in __init__ super().__init__(ob, callback) RuntimeError: super(): __class__ cell not found -
Django Sessions - Pass data between views
I am trying to use Django sessions to pass data between separate views when completing a booking submission. The booking form uses two HTML templates, the first to capture the date and time information (view -booking) about the booking and then when the user clicks Next, it takes the user to the second page (view -booking_details) to collect the booking details about the person booking. From reading online I have the below code, but I don't seem to get any data from the first page. Thanks in advance for any help, appreciate it. Views class Booking(CreateView): form_class = BookingsForm model = Bookings template_name = 'advancement/booking.html' def post_booking_details(request): if request.method == 'POST': form = BookingsForm(request.POST) if form.is_valid(): request.session['form_data_page_1'] = form.cleaned_data return HttpResponseRedirect(reverse('advancement/form.html')) return render(request, 'advancement/booking.html') class Booking_Details(CreateView): form_class = BookingsForm model = Bookings template_name = 'advancement/booking_details.html' def get_booking_details(request): first_page_data = request.session['form_data_page_1'] print(first_page_data) return render(request, 'advancement/booking_details.html') html (First Page) <!DOCTYPE html> {% load static %} <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <style type="text/css"> .card-header{ background: #0a233e url(https://www.vis.org.au/theme/vis/img/header.png) center center no-repeat; background-size: cover; color: white; } b{ color: #f8981d; } .card-title{ color: #0a233e; } .badge{ font-size: inherit; font-weight: inherit; } </style> <title></title> </head> <body onload="method_time()"> <form action="http://127.0.0.1:8000/details/" method="post"> … -
I can't run django test via pycharm
When I run test via terminal 'RUN_TEST=1 REUSE_DB=1 python manage.py test blahblah -v 2 --nologcapture --noinpu -s -x' then it works But when I run test via pycharm, then it fails with these message myvenv_path/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_manage.py test my_test Testing started at 11:10 AM ... nosetests blahblah_my_test --verbosity=1 ====================================================================== ERROR: Failure: ImportError (No module named my_test) ---------------------------------------------------------------------- blahblah ====================================================================== ERROR: Failure: TypeError (issubclass() arg 1 must be a class) ---------------------------------------------------------------------- Traceback (most recent call last): File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 495, in makeTest return self._makeTest(obj, parent) File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 548, in _makeTest if issubclass(parent, unittest.TestCase): Error Traceback (most recent call last): File "myvenv_path/lib/python2.7/unittest/case.py", line 329, in run testMethod() File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 495, in makeTest return self._makeTest(obj, parent) File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 548, in _makeTest if issubclass(parent, unittest.TestCase): TypeError: issubclass() arg 1 must be a class TypeError: issubclass() arg 1 must be a class ====================================================================== ERROR: Failure: TypeError (issubclass() arg 1 must be a class) ---------------------------------------------------------------------- Traceback (most recent call last): File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 495, in makeTest return self._makeTest(obj, parent) File "myvenv_path/lib/python2.7/site-packages/nose/loader.py", line 548, in _makeTest if issubclass(parent, unittest.TestCase): TypeError: issubclass() arg 1 must be a class ====================================================================== ERROR: Failure: TypeError (issubclass() arg 1 must be a class) ---------------------------------------------------------------------- Traceback (most recent call last): File … -
How does companies make staff users?
Apologies since this might not be the best way to word the question nor is this a coding question per say. I get the general process of creating a staff user within Django. What I would like to know is if companies send email links that allow their workers to sign up a form to be a staff user or if the employer provides their details and someone on the backend creates this account for them, or some other process I am unaware of? -
Django Authorization Checking in URL having wild card pattern
I am trying to implement permission checking mechanism in URLs for a request using wildcard techniques, rather than implement permission checking on each views. Currently What I have is. urlpatterns = [ path('admin/', include('admin_urls.py')), ... ] and my admin_urls.py is as follows urlpatterns = [ path('', ViewSpaceIndex.as_view(), name="admin_index"), path('', EmployeeView.as_view(), name="employee"), ... ] and views are as follows @method_decorator(admin_required, name='dispatch') class EmployeeView(TemplateView): template_name = 'secret.html' @method_decorator(admin_required, name='dispatch') class EmployeeView(TemplateView): template_name = 'secret.html' What I want to achieve is without using the repeated @method_decorator(admin_required, name='dispatch') decorator in every view I want to apply the permission to a wild card URLs '/admin/**' with admin_required permission like in Spring boot as follows. http.authorizeRequests() .antMatchers("/admin/**").has_permission("is_admin") -
Django: how to sum up numbers in django
i want to calculate the total sales and display the total price, i dont know how to write the function to do this. I have tried writing a little function to do it in models.py but it working as expected. This is what i want, i have a model named UserCourse which stored all the purchased courses, now i want to calculate and sum up all the price of a single course that was sold. models.py class Course(models.Model): course_title = models.CharField(max_length=10000) slug = models.SlugField(unique=True) price = models.IntegerField(default=0) class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) and also how do i filter this models in views.py so i can display the total price of courses a particular creator have sold.