Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels AsyncComsumer cannot catch the custome Exception
I'm building a chat app with Django-channels. I use AsyncConsumer. In my consumer, I have method chatroom() that tries to call another method _can_access_room(). In _can_access_room() there's a case it raises a custom Exception (inherit from Exception). But I cannot catch the custom Exception in chatroom(). The log shows that it raised, but WebSocket disconnects. I set a breakpoint on the line that catches the exception but it doesn't stop there. But if I catch the base Exception, it works. Please help, thanks ^^ Here's my code: async def chatroom(self, data: dict): # check room in group or not? if group_from_room_id(data.get('room_id')) in self.groups: await self.chatroom_send(data) else: try: a = await self._can_access_room(data) except CustomException as e: print('ahihi') @database_sync_to_async def _can_access_room(self, room_data: dict): room_id = room_data.get('room_id') chat_room: ChatRoom = ChatRoom.objects.filter(id=room_id).first() if not chat_room: raise custom_exceptions.RoomDoesNotExist Here's log: ... , line 455, in thread_handler return func(*args, **kwargs) File "***********/consumers/chat_room_consumer.py", line 153, in _can_access_room raise custom_exceptions.RoomDoesNotExist common.custom_exceptions.RoomDoesNotExist WebSocket DISCONNECT /ws/chat/winners [127.0.0.1:49452] -
How to build a Django QuerySet to check conditions on two manyToMany fields
I have the following models (simplified): class Resource(models.Model): name = models.CharField(max_length=64, unique=True) class ResourceFlow(models.Model): resource = models.ForeignKey(Resource, related_name="flow") amount = models.IntegerField() class Workflow(models.Model): inputs = models.ManyToManyField(ResourceFlow, related_name="workflow") class Stock(models): resource = models.ForeignKey(Resource, related_name="stock") amount = models.IntegerField() class Producer(models.Model): workflow = models.ForeignKey(Workflow, related_name="location") stocks = models.ManyToManyField(Stock, related_name="location") I would like to test with computation done by the the DB engine if I can start a production. A production can start if I have enough stock: for my Producer's workflow, all inputs ResourcesFlow amount have to be present in the Producer'stocks So the queryset might be one those result: for a given producer return all stocked resources that do not fulfill Workflow inputs amounts conditions for a given producer return inputs resources needed for the workflow that are not in sufficient quantity in its stocks It is possible to do that in Django? -
django server log is full of "NoneType: None" messages
The log of my REST Server app is full of messages saying NoneType: None Is there a way to know where these messages are generated?. I have added this line to the settings.py in order to set the file/line of the errors, but no lunk. logging.basicConfig(format = '%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt = '%Y-%m-%d:%H:%M:%S', level = logging.DEBUG) Example of the REST API logs: v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:10] "GET /api HTTP/1.1" 200 22 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:10] "GET /api/person/me HTTP/1.1" 200 1981 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/people HTTP/1.1" 200 514227 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-add-travel HTTP/1.1" 200 84 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-update-travel HTTP/1.1" 200 87 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-delete-travel HTTP/1.1" 200 87 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-undelete-travel HTTP/1.1" 200 89 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/countries HTTP/1.1" 200 32773 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/reasons HTTP/1.1" 200 1997 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/states HTTP/1.1" 200 5270 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 … -
Would this make my code faster? Should I not follow Django's structure best practices and would that affect my website's security?
I don't know what makes my code fast or slow... is it the quantity of lines? How separated between different files it is? What I am trying to do? On a Django website could my website security be compromised because of me not following Django's project structure best practices? (if that would give my code more speed) How could I make my Django website as fast as possible without compromising security? -
How to implement new log_action for LogEntry in admin views
I'm trying to display every actions performed on my models on an admin page, using LogEntry. So far I see actions done through the admin (which is the way LogEntry works by default if I understood well), but I would like to catch actions performed through my VueJS frontend as well. Not sure how to do this properly ! This is my code in admin.py (django 4.0) from django.contrib import admin from .models import * from django.contrib.admin.models import LogEntry, ADDITION, CHANGE class MoniterLog(admin.ModelAdmin): list_display = ('action_time','user','content_type','object_repr','change_message','action_flag') list_filter = ['action_time','user','content_type'] ordering = ('-action_time',) admin.site.register(LogEntry,MoniterLog) -
How to exclude search queries when selecting values in Django?
There is a product filter in which you need to exclude other attributes when choosing a brand. For example, we have color, size, weight, brand. When choosing a brand, we only have certain colors, sizes and weights. How to disable their checkboxes when they are not assigned to the selected brand. My code: [http://jsfiddle.net/Wihomie/vju41bqe/3/][1] -
Issue Installing ODBC Driver 17 for SQL Server for Linux
My end goal is to use Azure SQL Edge (ASQLE) instead of Microsoft SQL Server in a Docker container for a local development instance of an application (since MSSQL doesn't run on ARM). The container running ASQLE seems to be fine, but when I try to start my application I get the following error from the container running the API (which is powered by Django): django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") I have seen this issue a few other times on the web (1, 2) and they all seem to start with ensuring the driver installation, which is what I am having problems with. Following the guide provided by Microsoft, I run the following four commands (on a fresh ASQLE image) and get these outputs: root@7c38f5ceb89c:/$ curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)). 100 983 100 983 0 0 4529 0 --:--:-- --:--:-- --:--:-- 4529 OK root@7c38f5ceb89c:/$ … -
Cloudinary upload image from Django admin panel from two or more databases
everyone. I decide to use Cloudinary for storing images. This is my model field with image: avatar = models.ImageField(upload_to='avatar/', default='avatar/default.png', blank=True) All works fine for me, but I have one little issue. When I uploaded the image from admin panel, cloudinary upload it to my cloudinary folder 'avatar' with some modified name, for example: 'july2022_kda4th' or 'july2022_aidkdk' But when I uploaded this image from admin panel of another database (production), cloudinary upload the image with another name. So, I have two similar images in cloudinary. It's not convenient. How can I fix it? -
Indexing first n characters of Charfield in Django
How to index a specific number of Characters on Django Charfield? -
How to enable basic http auth through Django?
How do you enable basic http auth in Django? According to the Django docs, basic http auth can be enabled directly in Django, requiring no server support. I've added django.contrib.auth.middleware.RemoteUserMiddleware to my MIDDLEWARE list and added django.contrib.auth.backends.RemoteUserBackend to my AUTHENTICATION_BACKENDS list. so I created a simple view: import logging from django.http.response import JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def test_auth(request): print('Request.user: %s' % request.user) print('META:', request.META) print('REMOTE_USER:', request.META.get('REMOTE_USER')) if request.user.is_anonymous: return JsonResponse({"success": False}, safe=False) return JsonResponse({"success": True}, safe=False) and registered it in my urls.py as /test_auth. And then to test, I call it using curl: curl -u "myuser:mysupersecretpassword" -0 -v -X GET http://127.0.0.1:8000/test_auth However, it shows that Request.user: AnonymousUser, implying the RemoteUserBackend is not being called. I've tested my myuser:mysupersecretpassword credentials, and confirmed I can login as that user via the normal Django admin login. I'm using Django 3.2. Why isn't basic auth working with RemoteUserBackend? Is there another step that I'm missing? -
Django: permission required based on roles, but using a single User model
I have a custom user model that looks like this: class SpotUser(AbstractBaseUser): BASIC = 1 ADMIN = 2 QA = 3 RESEARCH = 4 uid = models.IntegerField(primary_key=True) name = models.TextField(blank=True, null=True) email = models.EmailField(unique=True) password = models.TextField(blank=True, null=True) USER_TYPE_CHOICES = ( (BASIC, 'Basic'), (QA, 'Qa'), (RESEARCH, 'Research'), (ADMIN, 'Admin') ) user_type = models.TextField(choices=USER_TYPE_CHOICES, default=BASIC) last_login = models.DateField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'users' I would like to add permissions based on the role. For example: Admin and research can update users via backend API, but QA and Basic cannot. Is it possible to implement this feature without using multiple User models? -
Url Error in Multiple Application Django site
My site has 3 application [alpha , store , management] alpha for landing page , login , about , contact and similar pages store e-com like page , management for system admin and management I have urls.py in all my applications And everything runs well first but when try request to in app urls it didn't worked.. Main urls urlpatterns = [ path('admin/', admin.site.urls), path('services',include('store.urls')), path('management',include('management.urls')), path('',include('alpha.urls')) ] First application url for store urlpatterns = [ path('',views.main,name = "main"), path('track',views.track,name="tracker") ] Second application url for management urlpatterns = [ path('',views.main ,name=''), path('staffs',views.staffs ,name='staffs'), path('costumers',views.costumers ,name='costumers'), path('services',views.services ,name='services'), path('delete',views.delete ,name='delete'), path('add',views.add ,name='add'), path('crm',views.crm ,name='crm'), path('ratings',views.ratings ,name='ratings'), path('complainBox',views.complainBox,name = 'complainBox'), path('registrationApproval',views.registrationApproval ,name='registrationApproval'), path('feedbacks',views.feedbacks,name = "feedbacks"), path('contact',views.contact,name = "Contact"), path('datasets',views.datasets,name = "Dataset page"), path('tools',views.tools,name ="Tools page" ), path('services',views.services,name ="services page" ), path('reports',views.reports,name ="reports page" ), path('login',views.login,name="Login page") , path('forgetPassword',views.forgetPassword,name = "Forget password") ] 3rd application url for alpha urlpatterns = [ path('',views.main,name='Main page'), path('about',views.about , name="About page"), path('contact',views.contact,name='contact page'), path('register',views.register,name='Staff registration'), path('patners',views.patners ,name="patner page"), path('alumuni',views.alumuni,name="Alumini page"), path('help',views.help , name = "help page"), path('complain',views.complain,name="Complain page"), path('feedback',views.feedback,name = "feedback page"), path('plans',views.plans,name = "plans and visions"), path('team',views.team,name = "team page") ] management page image When i click to tools or other link it is showing me … -
Django pass form data into another function
So I have a function that I want to use here in the forms or if I can in another python file but call it from this file. I want to access the file or at least the file path to be uploaded with the AssignmentSubmission class then pass it along with some other data into another python function to be processed and saved back to the sqlite database but I have no idea how to do it. My python forms file is below. from django import forms from .models import Course, Assignment, Exam, AssignmentSubmission, ExamSubmission # FORM FOR CREATE A COURSE class CourseCreateForm(forms.ModelForm): class Meta: model = Course fields = ['course_ID', 'course_name', 'course_image', 'teacher_name', 'teacher_details', 'course_description', 'end_date'] def __init__(self, *args, **kwargs): super(CourseCreateForm, self).__init__(*args, **kwargs) self.fields['course_ID'].label = "Course ID" self.fields['course_name'].label = "Course Name" self.fields['course_image'].label = "Image" self.fields['teacher_name'].label = "Teacher Name" self.fields['teacher_details'].label = "Teacher Details" self.fields['course_description'].label = "Description" self.fields['end_date'].label = "End Date" self.fields['course_name'].widget.attrs.update( { 'placeholder': 'Enter Course Name', } ) self.fields['course_ID'].widget.attrs.update( { 'placeholder': 'Enter Course ID', } ) self.fields['course_image'].widget.attrs.update( { 'placeholder': 'Image', } ) self.fields['teacher_name'].widget.attrs.update( { 'placeholder': 'Teacher Name', } ) self.fields['teacher_details'].widget.attrs.update( { 'placeholder': 'Teacher Details', } ) self.fields['course_description'].widget.attrs.update( { 'placeholder': 'Description', } ) def is_valid(self): valid = super(CourseCreateForm, self).is_valid() # … -
why I can't get total number of pages on output after using 'num_pages' property of pagination in django
where i made mistake... why I can't able to get total number of pages on output code which giving error -
How to convert that js function into django views
if (isset($_GET['pricechart'])) { $priceSliderOptions = array( 'minPrice' => '1', //minimal possible price for range slider 'maxPrice' => '350', //maximal possible price for range slider 'sliderPriceFrom' => '12', //default min value for range slider 'sliderPriceTo' => '189', //default max value for range slider 'sliderIncrement' => '1', //increment for range slider 'chartBars' => generateChartBarsExample() //@json (see README.md) ); header('Content-Type: application/json; charset=utf-8'); echo(json_encode($priceSliderOptions)); die(); } //price chart demo functions function generateChartBarsExample() { $maxPrice = 350; //maximal price of product in dataset $increment = 5; //how much euro in one bar of chart $priceTo = $increment; //default value $priceFrom = 1; //default value (should be the same as minPrice for range slider) $numberOfBars = $maxPrice / $increment; //how much bars we show on chart (linear calculation) $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $increment, 'frequency' => randomFloat()]; //first line without iteraction for ($i=1; $i < $numberOfBars; $i++) { $frequency = mt_rand() / mt_getrandmax(); $priceFrom = $priceFrom + $increment; $priceTo = $priceFrom + $increment - 1; if ($i < $numberOfBars) { $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $priceTo, 'frequency' => randomFloat()]; } else { $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $priceFrom, 'frequency' => randomFloat()]; //for last element we just set priceFrom = priceTo … -
add user input value to exported excel in Django import-export library
I am struggling with getting the value that user inserts in the form IN field called number_of_units. How can I pass the user value and add it to the total_price column in exported Excel file? views.py class ProductDetailView(LoginRequiredMixin, FormMixin, DetailView): login_url = 'login' redirect_field_name = 'login' template_name = 'ProductDetailView.html' model = Product form_class = CalculatorForm date_field = "publish" month_format = "%m" def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['form'] = form return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): number_of_units = form.cleaned_data['number_of_units'] filter_qs = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) dataset = CostCalculatorResource().export(filter_qs, number_of_units) form.save() response = HttpResponse(dataset.xlsx, content_type="xlsx") response['Content-Disposition'] = 'attachment; filename=cost_calculator.xlsx' return response def get_success_url(self): return reverse('product', kwargs={'slug': self.kwargs['slug']}) models.py class CostCalculator(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='related_product') title_component = models.ForeignKey(CalculatorServiceComponent, on_delete=models.CASCADE, default=1) number_of_units = models.IntegerField(default=0) cost = models.IntegerField(default=0) margin = models.FloatField(default=0.0) rate = models.IntegerField(default=0) @property def total_price(self): return self.cost * self.number_of_units * self.margin resources.py class CostCalculatorResource(resources.ModelResource): related_product__title = Field(attribute='related_product__title', column_name='Product') total_price = Field(attribute="total_price") class Meta: model = CostCalculator fields = ('id', 'related_product__title', 'total_price' ) forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) class Meta: model = CostCalculator fields = ('number_of_units',) -
How to solve this error "connection to local host failled " while deploying my django project on heroku
I am making a Facebook app using Django and want to deploy my project on Heroku. While deploying my project I am putting my important data in a .env file using decouple module. My settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD' : config('DB_PASSWORD'), 'HOST' : config('DB_HOST'), 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] USE_I18N = True USE_TZ = True STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type and my .env file looks like this SECRET_KEY=##### DB_NAME=####### DB_USER=######## DB_PASSWORD=####### DB_HOST=######### and I am facing this error: OperationalError at /login connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Request Method: POST Request URL: https://facebook-django-akhil.herokuapp.com/login Django Version: 4.0.6 Exception Type: OperationalError Exception Value: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py, line 122, in connect Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: … -
Axios taking long time to fetch response
I am using Axios instance in a React app to fetch data from GET requests. Backend server is deployed on Heroku(Professional Dyno) and written in Django REST framework. Database is deployed on AWS. On postman, APIs are giving response in around 2-3 seconds: Postman Screenshot But in the react app, response time is around 25-30 seconds. React app response time Screenshot Please note that I am calling around 10 different APIs in a single page. Is this affecting the response times? -
datetime ISO-8601 format
I have Django project and I want to use parse_datetime() to get (IOS-8601) formatted not in templates I have this datetime (2022-06-04 15:23:08.367007+00:00) I want it to be like this format (2022-06-04T15:30:00Z) I have tried this like this datetime_test = '2022-06-04 15:23:08.367007+00:00' datetime_test_1 = dateparse.parse_datetime(str(datetime_test)) print(datetime_test_1) I got 2022-06-04 15:23:08.367007+00:00 Is there any way I can get IOS-8601 format like this format 2022-06-04T15:30:00Z -
Django accessing a session outside of a view
I need to access a session outside of my view in a custom template filter, however don't know how to access the specific item in the list of current sessions, my Views.py looks like this: def handle_rebase(request): total_increase = 1 request.session["global_rebase"] = total_increase return HttpResponse(total_increase) The Django docs show the following snippet: >>> from django.contrib.sessions.models import Session >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') >>> s.expire_date However how do I determine the 'pk' of request.session["global_rebase"] ? -
mocking attribute of class that is used in tested class
I'm trying to write unit tests for my django app but failing to correctly use mock.patch my code : apps\MyApp\DataAccessLayer\CctDAO.py : from ..models import CCT from ..serializers import CctSerializer """ get a list of all CCTs @return a list of all the CCTs """ def getAll() -> list[dict]: entities = CCT.objects.all() serializer = CctSerializer(entities, many=True) return serializer.data apps\Myapp\serializers.py : from rest_framework_mongoengine.serializers import DocumentSerializer from .models import CCT """ serializer to encode and decode Yadbar CCT to JSON """ class CctSerializer(DocumentSerializer): class Meta: model = CCT exclude = ('id', ) #using custom id field instead of the default my test case : from unittest import TestCase, mock from .DataAccessLayer import CctDAO class Test_CCT_DAO(TestCase) : # @mock.patch('apps.MyApp.DataAccessLayer.CctDAO.CCT.objects.all', return_value=['mocked-data1']) @mock.patch.object(CctDAO.CctSerializer, 'data', new_callable=mock.PropertyMock, return_value = ['mocked-data1']) def test_getall_empty(self, mock1=None, mock2=None): print(CctDAO.getAll()) self.assertEqual(['mocked-data2'], CctDAO.getAll()) in this test case CctDAO.getAll() returns [], abd not my mocked data I also tried @mock.patch.object(CctDAO, 'CctSerializer.data', new_callable=mock.PropertyMock, return_value = ['mocked-data1']) but this results in an error that the CctDAO module does not have the attribute 'CctSerializer.data' I also tried @mock.patch('apps.MyApp.DataAccessLayer.CctDAO.CctSerializer.data', new_callable=mock.PropertyMock, return_value=['mocked-data1']) which returns [] as well, and not the mocked data how am I supose to patch CCT.objects.all() and serializer.data correctly? thanks -
Any one used "django-sqlcipher" for encrypting SQLITE ? I want to encrypt SQLITE database in Django
I am working on Windows OS. I want to encrypt my SQLite3 database in Django. I have installed "django-sqlcipher" and add "sqlcipher" in my InstalledAPPS. After that, I added "sqlcipher.backend" in my database Engine. when I run my project I get this error django.core.exceptions.ImproperlyConfigured: 'sqlcipher.backend' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in back ends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' If anyone of you faced this issue already please do let me know. -
Django : retrieve data from models
I have a serious problem, I need to retrieve a query set from an unrelated model my model: # problem/models.py User = get_user_model() class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey(User,models.CASCADE) score = models.PositiveIntegerField(default=100) # my perfer is PositiveSmallIntegerField class Submission(models.Model): submitted_time = models.DateTimeField(auto_now_add=True) participant = models.ForeignKey(User,related_name="submissions",on_delete=models.CASCADE) problem = models.ForeignKey(Problem,related_name="submissions",on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) # contest/models.py class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants') I trying to retrieve a query set of Submission like this : <QuerySet [<Submission: Submission object (12)>, <Submission: Submission object (6)>, <Submission: Submission object (16)>, <Submission: Submission object (5)>, <Submission: Submission object (11)>, <Submission: Submission object (15)>, <Submission: Submission object (14)>, <Submission: Submission object (4)>, <Submission: Submission object (10)>, <Submission: Submission object (9)>, <Submission: Submission object (3)>, <Submission: Submission object (8)>, <Submission: Submission object (2)>, <Submission: Submission object (13)>, <Submission: Submission object (1)>, <Submission: Submission object (7)>]> with the id of the Contest model , but I don't know how it is possible -
Many To Many display field Django
I have 4 models Account (a Custom User model) TeacherProfile (that have a foreign key to the Account) Section (that have a foreign key to the TeacherProfile) Subject (Many to Many to Student and Teacher) Now I want my Django-Admin to show whenever I'm going to Subject, this instance <Subject 1> under <Teacher 1> <Subject 1> under <Teacher 7> How could I do this? -
i see an error during making a virtual Environment
im making a ew project and start like this: (enviro) PS C:\Users\MadYar\Desktop\code.py\learning_log> django-admin.py startproject learning_log . and Error: The term 'django-admin.py' is not recognized as the name of a cmdlet, function, script file, or operable pr ogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try a gain. At line:1 char:16 django-admin.py <<<< startproject learning_log . CategoryInfo : ObjectNotFound: (django-admin.py:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException