Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have error when migrating my db in django-python
i change my database django default to postgresql and when i try to migrating ... django.db.utils.OperationalError: FATAL: password authentication failed for user "hamid" my settings is install psycop2 but i dont understad my mistake becuse i can enter to shell database by this password but when i migrating i have error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USRE': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } and my docker-compose.yml version: '3' services: blogpy_postgresql: image: postgres:12 container_name: blogpy_postgresql volumes: - blogpy_postgresql:/var/lib/postgresql/data restart: always env_file:.env ports: - "5432:5432" networks: - blogpy_network volumes: blogpy_postgresql: external: true networks: blogpy_network: external: true and my .env POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=postgres and my traceback File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "hamid" 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 "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/base.py", … -
Android - Access static file on Django server using Glide fails
I have the following Django model : class MyAccount(AbstractBaseUser): ... profile_picture = models.FileField(upload_to='Images/',default='Images/placeholder.jpg') ... When the user creates this account, he gets a default placeholder image. The registration of the user ( creation of the MyAccount instance for a particular user) works as expected. But my Android App can not get the placeholder image when it is requested. On my local Django development server, I get the following error: [17/Nov/2020 12:54:34] "GET /media/Images/placeholder.jpg HTTP/1.1" 404 2569 Not Found: /media/Images/placeholder.jpg Why is this happening? The image placeholder.jpg exists, so how it can be that the file is not found ? In the LogCat output of Android Studio, I get a similar error when I filter for okhttp. You can also see that the registration is done correctly but the file is not found: 2020-11-17 13:54:32.852 5825-5924/com.example.project D/OkHttp: {"response":"successfully authenticated.","id":1,"email":"abdullah@gmail.com","username":"abdullahc","profile_picture":"http://192.***.*.***:8000/media/Images/placeholder.jpg","date_joined":"2020-11-17T12:54:30.702559Z","token":"88b8ea2cf59ba851f7bac1751946213f5ee5afe9"} 2020-11-17 13:54:32.852 5825-5924/com.example.project D/OkHttp: <-- END HTTP (287-byte body) 2020-11-17 13:54:33.854 5825-5825/com.example.project I/Glide: Root cause (1 of 1) java.io.FileNotFoundException: http://192.168.2.104:8000/media/Images/placeholder.jpg at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251) at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:102) at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:56) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:164) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:154) at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:62) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100) at com.bumptech.glide.load.engine.SourceGenerator.startNextLoad(SourceGenerator.java:70) at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63) at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310) at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279) at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) at java.lang.Thread.run(Thread.java:764) at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:393) -
Django OneToOneField & Foreignkey - How to get value from related model?
I've been banging my head against this for an whole workday now and tried various suggestions from stackoverflow and other google results, and consulted the django documentation but all to no avail. In my django project I have the two models listed below. The related values in the models are the rowid which is unique to each "Sag". My goal is that when I query using "Sag.objects.all()" that it would also return the group attached to that specific rowid. Ideally it should be a "OneToOneField" and not a "ForeignKey" since the rowid should only exists once in both tables but my latest try had me change it to a "ForeignKey". I have, however, been unable to get the related field with the different solutions I've tried so far class Sag(models.Model): id = models.IntegerField(blank=True, null=False, primary_key=True) rowid = models.IntegerField(db_column='RowId', blank=True, null=True) posts = models.TextField(db_column='POSTS', blank=True, null=True) date = models.TextField(db_column='Date', blank=True, null=True) art = models.IntegerField(db_column='Art', blank=True, null=True) class Grouping(models.Model): rowid = models.ForeignKey(Sag, on_delete=models.CASCADE, db_column='RowId') group = models.IntegerField(db_column='Group', blank=True, null=True) Any ideas/ressources as to how i would solve this problem? -
filter a query set based on start_time and duration fields
I want to filter a queryset based on a start time and an end time . The table has the fields , "start_time" and "duration" . start_time is a DateTimeField and duration is an IntegerField which holds the duration in minutes. I want to get a queryset between two times. query_filter = Q() if self.start_time is not None: query_filter.add(Q(virtualclassroommodule__end_time__gt=self.start_time), Q.AND) if self.end_time is not None: query_filter.add(Q(virtualclassroommodule__start_time__lt=self.end_time), Q.AND) self.start_time and self.end_time are the time frames i want to filter with .The above is an example of another working filter. In this example, the model has an end_time field, so it can be done. However i want to accomplish the same when I have only a duration field and a start_time. -
Database error while authenticating user from mongodb connected with django app deployed in gcp
I have deployed django app in Google cloud Platform,I am using mongodb atlas to store users data .I can successfully register and login by running it on localhost.But when i try to register/login directly from the app url ,it's giving database error.In settings.py file ,i have given connection string of mongodb database.How would i be able to access data stored in mongodb through app deployed in gcp ? The resources which are used are App Engine alongwith cloud sdk to deploy. The Database connection in settings.py file is as follow: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'name' : 'Haley', 'host':'mongodb+srv://username:password@haley.tdyg9.mongodb.net/Haley?retryWrites=true&w=majority', 'username': 'username', 'password': 'password', 'authMechanism': 'SCRAM-SHA-1', }, } } The error is as following : DatabaseError at /login No exception message supplied Request Method: POST Request URL: https://haley-295802.ew.r.appspot.com/login Django Version: 3.0.5 Exception Type: DatabaseError Exception Location: /env/lib/python3.7/site-packages/djongo/cursor.py in execute, line 59 Python Executable: /env/bin/python3.7 Python Version: 3.7.9 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Tue, 17 Nov 2020 12:48:36 +0000 The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('INSERT INTO "django_session" ("session_key", "session_data", "expire_date") VALUES (%(0)s, %(1)s, %(2)s)',) Params: (('gvtlvlakx6bvztpv816net7zp6e86ot7', 'MGEwYWY5ZTEwOWNjZjliZGZjMWQwMTdjMTlkMDQ4YTA1ZDUxNDUwMjp7InVzZXJfaWQiOiJrYXRpZS5wYXRlbEBnbWFpbC5jb20ifQ==', datetime.datetime(2020, 12, 1, 12, 48, 35, 677384)),) Version: 1.3.3) was … -
Django Model not being updated after calling save() method
Im Using django signals to update a foreign key object of a model . @receiver(sender=PointItem, signal=post_save) def PointItemSaved(instance, sender, **kwargs): try: print(f"before save {user.points}") user = User.objects.get(id=instance.user.id) user.points += 100 user.save() print(f"after save {user.points}") except Exception as e: print(f"there is a problem {e}") according to logs , everything is correct . before & after values are correct . but when i check it on admin page it does not changed ! -
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred:
I have a checkbox list - user check which items to update - <th scope="row"><input type="checkbox" name="document_detail" value="{{ result.id }}" id="result_check"/>{{ result.id }} This is handled in view by: document_request = request.POST['document_detail'] logging.info(document_request) approval_items = [] for document in document_request: logging.info(document) logging.info gives the correct UUID field e.g. 91da274b-208f-4d65-9e5f-d5cbf2860961 after the loop is initiated the value change to simply "9" or the first character of the UUID. e.g. logging.info give "9" hence the correct error of badly formed UUID Is there a correct method of handling this type of item that I'm missing? -
How to write thread modeling in Django?
I am new to the security side, I know my question might be silly but totally new to Thread Modeling. I have a simple Django application and I need to write thread modeling for this application. If any can help me with a simple Thread Modeling Document it will be great help. Thanks & Regards, Mohamed Naveen -
Change URL when link is clicked in iFrame, when the links in question would be created by user input?
From what I can understand, the URLs of site do not change during navigation if the element with the href/src is within an iframe. And there is a way to override this by getting the ID of every single link element that would exist in the iframe and then set the src manually on each, such as in the response to this question Change URL in an iframe using javascript However the links I want to reflect in the URL are to pages created and added to the site by users, and I cannot know in advance what these URLs will be called, so cannot manually link to them in advance. Is there a workaround for this? And if so, is it really worth the effort and possible messiness? The iframe in question is part of a 3rd party library that I have no control over (django-fobi) -
How do you serialize a queryset that has been created by innerjoining different models?
So, I'm trying to serialize a queryset in my ModelsViewSet. This is my code in my viewset. `class StudentReportViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny ] serializer_class = GeneralSerializer def get_queryset(self): if self.request.method == 'GET': queryset = StudentReport.objects.all() teststate_name = self.request.GET.get('testid',None) rawmodalstate_name = (self.request.GET.get('byRaw',None)) percmodaltstate_name = (self.request.GET.get('byPerc',None)) stanmodalstate_name = (self.request.GET.get('byStan',None)) convmodalstate_name = (self.request.GET.get('byConv',None)) print('@@@@@@@@@@@@@@@@') if teststate_name is not None: teststate_name= teststate_name.split(',') teststate_name = list(map(int,teststate_name)) print(teststate_name) print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') queryset= queryset.select_related('test').filter(test_id__in = teststate_name).values('test__subject','student__name','resultsmarked__totalrawscore') queryset= json.dumps(list(queryset), ensure_ascii=False) print('33333333333') print(queryset) return queryset` This is my serializers.py: class StudentReportSerializer(serializers.ModelSerializer): class Meta: model = StudentReport fields= '__all__' These are my models used in my query set: 1)StudentReport class StudentReport(models.Model): idstudent_report = models.AutoField(primary_key=True) student = models.ForeignKey('Students', models.DO_NOTHING, db_column='Student_ID', blank=True, null=True) # Field name made lowercase. test = models.ForeignKey('Test', models.DO_NOTHING, db_column='Test_ID', blank=True, null=True) # Field name made lowercase. resultsmarked = models.ForeignKey(ResultsMarked, models.DO_NOTHING, db_column='ResultsMarked_ID', blank=True, null=True) # Field name made lowercase. standardisedscoretable = models.ForeignKey(Standardizedscoretable, models.DO_NOTHING, db_column='StandardisedScoreTable_ID', blank=True, null=True) # Field name made lowercase. gradetableinternal = models.ForeignKey(Gradetableinternal, models.DO_NOTHING, db_column='GradeTableInternal_ID', blank=True, null=True) # Field name made lowercase. gradetableexternal = models.ForeignKey(Gradetableexternal, models.DO_NOTHING, db_column='GradeTableExternal_ID', blank=True, null=True) # Field name made lowercase. percentiletableid = models.ForeignKey(Percentiletable, models.DO_NOTHING, db_column='PercentileTableID', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'student_report' Test Model class Test(models.Model): idtest … -
Can't change interpreter path in VS Code (working on a Django project, python3)
On the first attempt I was able to change the interpreter, but when I come back to project the path is within suggestions but when I click nothing changes. -
unable to serve django media files with nginx (docker-compose)
I am using docker-compose to run my react-django-nginx application. The application is able to server static assets and the admin page. The problem is however, that I am unable to serve files in the media folder. The files in the media folder are created by me from the admin pannel. They are pdfs. I also have Icons that also do not show up. These are the relevant file: folder structure: backend |---Docker |---core |---settings.py |---etc frontend |---Docker |---conf.d |---etc. ngnix |---Docker |---default.conf docker-compose.yaml docker-compose: version: "3" services: backend: build: context: ./backend dockerfile: Dockerfile ports: - 8000:8000 volumes: - ./backend:/app - ./backend/media:/app/media - ./backend/static:/app/static frontend: build: context: ./frontend dockerfile: Dockerfile-prod ports: - 3000:80 volumes: - ./frontend/src:/app/src nginx: build: context: ./nginx dockerfile: Dockerfile volumes: - ./backend/media:/app/media ports: - 80:80 - 443:443 nginx server { listen 80; client_max_body_size 60M; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /api { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /admin { proxy_pass http://backend:8000/admin; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /media/ { alias /home/vicktree/Documents/EducationPortal/backend/media/; } location /nginx-health-check { access_log … -
Dango admin throws empty exception when calling __str__ method
I'm developping a web app with Django (2.2). I have the following Profile model extending the built-in User model trough an One-to-one relationship. class Profile(models.Model): class Meta: ordering = ['user__last_name'] txt = models.CharField("TXT", max_length=5, null=True, blank=True, unique=True) user = models.OneToOneField(User, on_delete=models.PROTECT) colleague = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) def __str__(self): """ Display of User with its full name""" return "%s %s" % (self.user.last_name.upper(), self.user.first_name.capitalize()) The __str__ method works well in the Admin list display view or in a Django shell. However, an exception is thrown when I try to access to the admin form, pointing to the __str__ method but without any detail. When the __str__ method is removed the form is displayed correctly. Here is the ModelAdmin class ProfileAdmin(admin.ModelAdmin): readonly_fields = ('get_last_name','get_first_name',) fieldsets = [ ('User', {'fields': ['get_last_name', 'get_first_name','txt', 'colleague']}), ] #Sélection des champs à afficher dans la vue liste list_display = ('__str__','get_poste','txt', 'colleague ') #Champ de recherche search_fields = ['user__first_name', 'user__last_name', ] #calculate fields for list_display def get_last_name(self, obj): return obj.user.last_name def get_first_name(self, obj): return obj.user.first_name #Define description of fields for list_display get_last_name.short_description = 'Name' get_first_name.short_description = 'Firstname' #Enable sorting on calculated fields get_last_name.admin_order_field = 'user__last_name' get_first_name.admin_order_field = 'user__first_name' Any advice to solve this issue would be appreciated -
django-storages resize url
I'm using DigitalOcean spaces and try to resize the image that is already there. I have only filename. url = static(filename) # this contains full url to the image image = Image.open(what is here???) if image.size[1] > height: ratio = (height / float(image.size[1])) width = int((float(image.size[0]) * float(ratio))) image = image.resize((width, height), Image.ANTIALIAS) image.save(how to save???) -
Django deployment with Daphne
I want to deploy my Django app (Rest API + React on frontend) on AWS. I use nginx, gunicorn (for http handling) and daphne (for async websockets - Im using django channels for chat application). I was following THIS tutorial. It looks like I configured well nginx and gunicorn (page is normally loading, I can handle sync request to rest API) but I guess there are some problems with daphne and/or asgi. I use systemctl services for server. All 3 (nginx, gunicorn, daphne) statuses show 'active'. Everything works fine on my development server on local. On deployment server when I enter website, I see in console Firefox can’t establish a connection to the server at ws://PATH_TO_WEBSOCKET Is Daphne connected well with Nginx? I use Redis for CHANNEL_LAYERS. I have installed channels-redis and redis-server on Ubuntu server. I think it works fine as I get respond > redis-cli > ping **PONG** project tree . ├── frontend #react files ├── checkers #project dir │ ├── settings.py │ ├── urls.py │ └── asgi.py ├── chat #chat app │ ├── consumers.py │ └── routing.py └── checkers.sock asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'checkers.settings') django.setup() application = get_default_application() settings.py ROOT_URLCONF = … -
How to create a User model in Django which contains a list of friens which are "User" models as well
I have a model named User and it must have a list of friends which are also "User"s.How shall i go about doing this. Should I make another model named Friends which will contain two "ForeignKey"s to the model User.Or is there any other way of doing this?? -
Add +7 before the entered number when saving to the database Django rest
I have a phone number field. I want the user to enter a phone number like 123 456 7889 and server add +7 when saving. I decided that it can be done with serialization and added this serializers.py class AbstractUserSerializer(serializers.ModelSerializer):полей""" class Meta: model = AbstractUser fields = ('id', 'phone_number', 'email', 'password') extra_kwargs = {"phone_number": {"error_messages": {"blank": "Phone number field can not be blank", "invalid": "Phone number field is not correct", "unique": "This phone number is already registered"}}, "email": {"error_messages": {"invalid": "Email field is not correct", "unique": "This email is already registered"}}, "password": {'write_only': True, "error_messages": {"blank": "Password field can not be blank", "invalid": "Password field is not correct"}}, } def create(self, validated_data): abstract = AbstractUser.objects.create_user( phone_number='+7' + validated_data.pop('phone_number'), **validated_data, ) return abstract This works, but this field must be unique and handled by my error, but after adding my functionality, my error message stopped working, instead an error is thrown django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_email_key" DETAIL: Key (email)=() already exists. Where and how best to add +7. I tried in the manager and view, but it didn't work. Can you please help me? My code: views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class … -
annotate a datetime field from another date time and duration in minutes
I want to annotate a datetime field to a queryset using timedelta and F objects Example: Model.objects.annotate(end_time=F('start_time')+timedelta(minutes=F('meeting_duration'))) Here i have a field "start_time" and "meeting_duration" in my table and i want to calculate and annotate an end_time using datetime.timedelta And thereafter filter the queryset using the annotated field. quueryset.filter(end_time__gte=self.end_time) Now its throwing error: TypeError: unsupported type for timedelta minutes component: F -
Django enum compare in template (html)
I am creating an application with Django. (I am new to Django). The application has some statuses, so I tought: let's do it with an ENUM. It kind of works, except the ENUM compare in the template. That gives a false, but it should be true. My models.py: from django.db import models from enum import Enum # Create your models here. class ScannerStatus(Enum): OPERATIONAL = "Operational" ERROR = "Error" class SystemStatus: id: int scannerStatus: ScannerStatus feedStatus: str pentestStatus: str Views.py (partially): from .models import SystemStatus, ScannerStatus status = SystemStatus() status.scannerStatus = ScannerStatus.OPERATIONAL status.feedStatus = "Out dated" status.pentestStatus = "IDLE" return render(request, 'VulnManager/dashboard.html', {'status': status}) dashboard.html (partially): <div class="list-group-item"> <h6 class="list-group-item-heading"> Scanner <a href="#" data-toggle="tooltip" data-placement="bottom" title="Status of the scanner"> <i class="fa fa-question-circle"></i> </a> {% if status.scannerStatus == ScannerStatus.OPERATIONAL %} <!-- This compare doesn't work --> <span class="badge badge-pill badge-success"> {% else %} <span class="badge badge-pill badge-danger"> {% endif %} {{status.scannerStatus.value}}</span> </h6> </div> Anybody some suggestions or alternatives? I've also tried it with class ScannerStatus(models.Model) but that didn't work. Thanks -
images don't appear when i press on phone photos - django
images don't appear when i press on show imgs using collapse method , how to fix problem model.py : class Mobile_Images(models.Model): phone = models.ForeignKey(Mobile, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to = 'images/') admin.py: class Mobile_ImagesAdmin(admin.StackedInline): model = Mobile_Images class MobileAdmin(admin.ModelAdmin): search_fields = ('name', 'name') inlines = [Mobile_ImagesAdmin] class Meta: model = Mobile admin.site.register(Mobile,MobileAdmin) views.py : def mobile_posts(request,slug): mobile_posts = get_object_or_404(Mobile, slug=slug) best_posts = BestArticals.objects.all() phone_images = Mobile_Images.objects.all() context = {'mobile_posts':mobile_posts,'best_posts' : best_posts,'phone_images':phone_images} return render(request,'mobile/mobile_posts_page.html', { 'mobile_posts': mobile_posts,'best_posts' : best_posts,'phone_images':phone_images }) html page : <button type="button" class="btn btn-info" aria-controls="#phone_pic" data-toggle="collapse" data-target="#phone_pic" style="background-color:#7952b3;border-radius:10px"> phone photos </button> <div id="phone_pic" class="collapse"> <br> <img src="{{phone_images.images}}" alt="" height="300px" width="500px" class="rounded mx-auto d-block"> </div> so when i use the code in html src="{{phone_images.images}}" it don't show all photos that i uploaded before , how to fix this problem -
Career matching query does not exist
this is my views.py. its show a error, Career matching query does not exist. rg = request.GET.get rp = request.POST.get response_data = {} print(rp,'rppp') job = Career.objects.get(job_id=rp('career_id')) print("job_idddd", job) -
how to use choices argument inside a class as a value of radio input in Django template
I want to know how to define choices values to a radio button in the Django template. Here is my models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) ... class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) In the template I want to assign values of my RARING_CHOICES to radio in a loop condition. {% for question in questions %} <li>{{ question }}</li> <ul> <input type="radio" value=""> <input type="radio" value=""> <input type="radio" value=""> <input type="radio" value=""> </ul> {% endfor %} Views.py def index(request): context = { "questions": Question.objects.all(), "answers": Answer.objects.all(), "departments": Department.objects.all(), "semesters": Semester.objects.all(), "teachers": Teacher.objects.all(), "subjects": Subject.objects.all(),} return render(request, "evaluation/index.html", context) -
One place to monitor modifications of django model
I have model: class UserAvailableCredit(models.Model): user = models.ForeignKey( "auth_ex.User", related_name="credits", on_delete=models.CASCADE, ) payment = models.ForeignKey( Payment, related_name="credits", on_delete=models.CASCADE, ) project = models.ForeignKey( Project, related_name="credits", on_delete=models.CASCADE, null=True, blank=True, ) and on this model I make various actions like: Bulk creating Deleting Updating etc. is there any way to have one method that on any change of model triggers action? Overwriting save method doesn't solve problem when bulk_create action is triggered. In my solution I have done something like this: class UserAvailableCreditQuerySet(QuerySet): def update(self, **kwargs): notify = kwargs.pop("notify", False) if notify: #custom action def bulk_create(self, objs, batch_size=None): super().bulk_create(objs, batch_size) #custom action class UserAvailableCredit(models.Model): """Model to store available users credits to use with plan limitations.""" objects = UserAvailableCreditQuerySet.as_manager() user = models.ForeignKey( "auth_ex.User", related_name="credits", on_delete=models.CASCADE, ) payment = models.ForeignKey( Payment, related_name="credits", on_delete=models.CASCADE, ) project = models.ForeignKey( Project, related_name="credits", on_delete=models.CASCADE, null=True, blank=True, ) class Meta: ordering = ["id"] def save(self, *args, **kwargs): super().save(*args, **kwargs) #custom action def create(self, *args, **kwargs): super().create(*args, **kwargs) #custom action def delete(self, *args, **kwargs): super().delete(*args, **kwargs) #custom action But I am not sure if it is best way to solve this problem. -
'Order' object is not iterable [Django]
At the very beginning I would note that I'm a beginner as hel :P I have two models in my django models.py and I want them to display on a page. The issue is that I got error about no possible iteration and I don't know why. Also, I'm following the Crash Course from Youtube with changing some thing for my use :) Could You please advice as I haven't found any useful tips on google? Thanks! models.py from django.db import models # Create your models here. class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending Order', 'Pending Order'), ('Pending PR', 'Pending PR'), ('Declined by SME', 'Declined by SME'), ('Declined by Finance', 'Declined by Finance'), ('Ordered', 'Ordered'), ('Canceled', 'Canceled'), ('Delivered', 'Delivered'), ) product = models.CharField(max_length=200, null=True) link = models.CharField(max_length=400, null=True) supplier = models.ForeignKey(Supplier, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, default='Pending Order', choices=STATUS) amount = models.CharField(max_length=40, null=True) comment = models.CharField(max_length=400, null=True, blank=True) requester = models.CharField(max_length=40, null=True) def __str__(self): return self.product views.py from django.shortcuts import render from .models import * # Create your views here. def home(request): return render(request, 'accounts/dashboard.html') … -
How should I test this Custom Permissions
I'm confused about the procedure to test this permissions. Should I run this tests testing the login inheriting just the permissions? Couldn't just test this permissions by itsef? How must be done a test like this? def has_permission(self, request, view): user = request.user if not user: user = get_user(request) # -- Default user from allowed hosts bypasses authentication. if API_DEFAULT_USER == user.username: return True # -- Admin users have permission. if user.is_staff or user.is_superuser: return True # -- suscribed users have permission. if not user.is_anonymous: return True return False class SuscribedUserApiPerm(BasePermission): def has_permission(self, request, view): user = request.user # -- suscribed users only have permission. if not user.is_anonymous and user.username is None: return True return False class SubscriptionApiPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_api() return False class SubscriptionSimulatorPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_simulator() return False