Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Docker container without database container - best practise?
I am a little bit confused about the database Docker container. I read everywhere that is not good practise to dockerize a database, for example here. But if I search for Django Docker container then I see almost in every Docker Compose file that a Postgres database container is included. For example I have this docker-compose.yml file: version: '3.9' services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - .:/app command: > sh -c "python manage.py migrate && python app/manage.py runserver 192.168.1.65:8000" env_file: - variables.env depends_on: - db db: image: postgres:13-alpine container_name: postgres volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=dzijn - POSTGRES_USER=zijn - POSTGRES_PASSWORD=password volumes: dev-db-data: dev-static-data: It has also a Docker database. Is it better to omit the database container in the Docker Compose file and for example to store the database in a cloud service? Because I am using Microsoft Azure for the hosting. -
General way of iterating over a dictionary containing multiple mpld3 graph images in Django?
I am working on a personal project. One part of this is to display multiple histograms on a webpage. So far, I have been able to get this to work using the following code: views.py: import pandas as pd import matplotlib.pyplot as plt,mpld3 import scipy.stats as stats import numpy as np for column in df.columns: fig=plt.figure() plt.hist(df[column]) histogram=mpld3.fig_to_html(fig) context[f"{column}Histogram"]=[histogram] HTML Code: {% for elem in PregnanciesHistogram %} {{elem|safe}} {% endfor %} {% for elem in GlucoseHistogram %} {{elem|safe}} {% endfor %} {% for elem in BloodPressureHistogram %} {{elem|safe}} {% endfor %} {% for elem in SkinThicknessHistogram %} {{elem|safe}} {% endfor %} {% for elem in InsulinHistogram %} {{elem|safe}} {% endfor %} {% for elem in BMIHistogram %} {{elem|safe}} {% endfor %} {% for elem in DiabetesPedigreeFunctionHistogram %} {{elem|safe}} {% endfor %} {% for elem in AgeHistogram %} {{elem|safe}} {% endfor %} I do see all the histograms on my webpage, but the problem is that all of the HTML code uses hardcoded keys in the dictionary. Is there a general way of writing what I wrote in this HTML code, using a for loop, without hardcoding the keys from the dictionary? I would appreciate it if someone could tell me … -
How to (conditionally) remove SCRIPT_NAME from MEDIA_URL in urls.py
Situation: working in Debug=True mode in Django. I want to serve files from the media root, so I follow the documentation hint: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And it works perfectly (remember to read the note: MEDIA_URL should be local i.e. media/. Don't put a / in front of it. Important!). I have a media resource called 123456.txt, in the admin interface I get the link: /media/123456.txt. Now I move to Apache (still in debug), but I run this Django site in a subfolder of the server, and everything works fine, thanks to the WSGI variable SCRIPT_NAME which gets prepended to all URIs. So just to be clear, I have https://example.com/subfolder as the root for the Django site and the previous media resource called 123456.txt, in the admin interface I get the link: /subfolder/media/123456.txt. So the link is correct. When I request the resource https://example.com/subfolder/media/123456.txt, Apache recognizes the subfolder and sends to Django a request for media/123456.txt, as expected. The problem is that the url pattern created by the static() helper function now includes the SCRIPT_NAME prefix, so when I click on the resource, I get an exception … -
Django SELECT Query
Hi Iam try to select from mysql using Django my models.py from django.db import models from django.db.models import Q class Series(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) des = models.CharField(max_length=255) img = models.CharField(max_length=255) isseries = models.IntegerField() istrend = models.CharField(max_length=255) background_img = models.CharField(max_length=255) trial_url = models.CharField(max_length=255) imdb_id = models.CharField(max_length=255) rate = models.CharField(max_length=255) date = models.CharField(max_length=255) status = models.IntegerField() isdel = models.IntegerField() section_id = models.IntegerField() poster_img = models.CharField(max_length=255) genres = models.CharField(max_length=255) class Meta: db_table = 'series' my sample Script series = series_db.objects.filter(istrend=1,status=1,isdel=0).order_by('id').values() i want to SELECT all columnt without isdel so i remove isdel from models.py, but when i remove it i cant use isdel to make WHERE isdel = 0 in mysql so i got This Error django.core.exceptions.FieldError: Cannot resolve keyword 'isdel' into field. so how i can use isdel to make a condition without select it LIKE this Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` = '1' AND `series`.`status` = 1) ORDER BY `series`.`id` ASC real Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`isdel`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` … -
I am trying to install django-jazzmin but I am getting an error
When I try to install django-jazzmin using command pip install django-jazzmin I am getting the error. ERROR: Could not find a version that satisfies the requirement django>=2 (from django-jazzmin) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, 1.11.28, 1.11.29) ERROR: No matching distribution found … -
chatterbot: how to utter a default welcome message?
My Chatterbot instance is ready and trained. But it only replies when the user initialize the conversation. I want my chatterbot instance to utter a default message. How can I do that? My chatterbot instance is installed in a "django project". -
Celery Task Signals, Headers not accessible in signals.task_prerun
I am trying to change the behaviour of celery tasks by defining before_task_publish and task_prerun handler, requirement is, i need pass certain data between the tasks. I am trying to modify the headers of before_task_publish and trying to access the same in task_prerun using task.request.headers, but headers are blank. My approach is: from celery_setup import celery_app from celery import Celery, signals @signals.before_task_publish.connect def before_task_publish_handler(sender=None, body=None, headers=None, **kwargs): headers['shared_data'] = "Data to share" @celery_app.task def my_task(arg): print("Task running:", arg) @signals.task_prerun.connect def task_prerun_handler(task_id=None, task=None, **kwargs): shared_data = task.request.headers.get('shared_data') if shared_data: print("Shared data in task_prerun:", shared_data) # Calling the task my_task.apply_async(args=("Hello, Celery!",), headers={}) i am using celery 4.4.4 with Python3.7 I have try this approach, i am expecting to share the data among signals. -
Django: multiple return from one class of models.py, but problems using it in another class
I would like to use the same class to pull two teams and display them in a django admin combobox when inserting records. When I extracted only one teams it worked fine, all ok, but now that I added two returns it doesn't work. How can I use the same Teams class to return the team_home and team_away that I will use in the New_Match class? (team_home and team_away will be two comboboxes). I tried writing Teams.team_home and Teams.team_away, but I got the error: TypeError: 'DeferredAttribute' object is not callable. I don't even know if this was a good idea models.py class Teams(models.Model): team_home = models.CharField(max_length=40) team_away = models.CharField(max_length=40) def __str__(self): return self.team_home, self.team_away class New_Match(models.Model): team_home = ChainedForeignKey( Teams, related_name='team_home', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) team_away = ChainedForeignKey( Teams, related_name='team_away', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) P.S: I'm using smart_selects -
NotImplementedError: This backend doesn't support absolute paths.(Django)
I am trying to upload my media files to AWS Bucket and I am completely able to upload them there on bucket using this code. model.py class Evidence(models.Model): """ Stores an individual evidence file, related to :model:`reporting.ReportFindingLink` and :model:`users.User`. """ def set_upload_destination(self, filename): """ Sets the `upload_to` destination to the evidence folder for the associated report ID. """ return os.path.join("evidence", str(self.finding.report.id), filename) document = models.FileField( upload_to=set_upload_destination, validators=[validate_evidence_extension], blank=True, ) finding = models.ForeignKey("ReportFindingLink", on_delete=models.CASCADE) views.py def form_valid(self, form, **kwargs): self.object = form.save(commit=False) self.object.uploaded_by = self.request.user self.object.finding = self.finding_instance try: self.object.save() messages.success(self.request,"Evidence uploaded successfully", extra_tags="alert-success") except: messages.error(self.request, "Evidence file failed to upload", extra_tags="alert-danger") return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): if "modal" in self.kwargs: return reverse("reporting:upload_evidence_modal_success") return reverse("reporting:report_detail", args=(self.object.finding.report.pk,)) All of this is working fine. But trouble occurs when I am trying to delete the file. Huh? Here is my code for deleting the file. I must tell you guys that there is relationship established between Evidence and ReportingLink table. class ReportFindingLinkDelete(LoginRequiredMixin, SingleObjectMixin, View): """ Delete an individual :model:`reporting.ReportFindingLink`. """ model = ReportFindingLink def post(self, *args, **kwargs): finding = self.get_object() finding.delete() data = { "result": "success", "message": "Successfully deleted {finding} and cleaned up evidence".format(finding=finding), } logger.info( "Deleted %s %s by request of %s", finding.__class__.__name__, finding.id, … -
How merge different table record and show on timeline with django?
I have different table for different medias (like video, audio, ebooks) extending one abstract mode. I want to show them by merging in some order. This is my abstract model: class Media(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(default='', max_length=128) thumbs = GenericRelation(Image) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(to=User, null=True, on_delete=models.SET_NULL) class Meta: abstract = True And this is my extended Audio model: class Audio(Series): duration = models.IntegerField(default=0) metadata = GenericRelation(Metadata, related_query_name='audio_metadata', null=True) # some other fields How do I create a ranking system on the basis of some values in my media tables? And my second question is should the data with rankings be stored in Relation database? (If I store the ranks in some relation database, I would have to create django Generic model I guess and then I can keep data in cache and show on timeline). Please suggest here. -
has anyone used milvus vector database with Django
I am planning on using Django to front end an application that uses one of the ML/AI platforms, and the milvus vector database looks like a good choice. The question is how to use milvus as the database for Django? I have found the python libraries but none that reference how to do it with Django. I am hoping to get some advice on how to hook up milvus vector database to Django. -
What is apps.py in django?
I read about this,And i cunfused The application server takes the INSTALLED_APPS and loads or generates an AppConfig object for each app. This collection of AppConfig objects are then stored in an instance of theApps class. Please someone explain with simple example. Thanks -
Large File Uploads with Amazon S3 + Django 400 Bad Request
i was following this course, i think i did everything right but it gives me POST https://fakebucket.s3-eu-north-1.amazonaws.com/ 400 (Bad Request) views.py class FilePolicyAPI(APIView): """ This view is to get the AWS Upload Policy for our s3 bucket. What we do here is first create a FileItem object instance in our Django backend. This is to include the FileItem instance in the path we will use within our bucket as you'll see below. """ permission_classes = [permissions.IsAuthenticated] authentication_classes = [authentication.SessionAuthentication] def post(self, request, *args, **kwargs): """ The initial post request includes the filename and auth credientails. In our case, we'll use Session Authentication but any auth should work. """ filename_req = request.data.get('filename') if not filename_req: return Response({"message": "A filename is required"}, status=status.HTTP_400_BAD_REQUEST) policy_expires = int(time.time()+5000) user = request.user username_str = str(request.user.username) """ Below we create the Django object. We'll use this in our upload path to AWS. Example: To-be-uploaded file's name: Some Random File.mp4 Eventual Path on S3: <bucket>/username/2312/2312.mp4 """ file_obj = Post.objects.create( author = request.user, title=filename_req ) file_obj_id = file_obj.id upload_start_path = "{username}/".format( username = username_str, file_obj_id=file_obj_id ) _, file_extension = os.path.splitext(filename_req) filename_final = "{file_obj_id}{file_extension}".format( file_obj_id= file_obj_id, file_extension=file_extension ) """ Eventual file_upload_path includes the renamed file to the Django-stored FileItem … -
Error while running python3 manage.py migrate_schemas --shared in Django multi-tenant application
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Meta: swappable = 'AUTH_USER_MODEL' # Add related_name arguments to avoid clash with auth.User groups = models.ManyToManyField( 'auth.Group', related_name='user_custom_set', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user_custom', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='user_custom_set', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', related_query_name='user_custom', ) `your text` SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'django.contrib.contenttypes', "student", "teacher", "tenant", "account", ) INSTALLED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', "student", "teacher", "account", ) python3 manage.py migrate_schemas --shared \[standard:public\] === Running migrate for schema public \[standard:public\] Operations to perform: \[standard:public\] Apply all migrations: account, admin, auth, contenttypes, sessions, sites, student, teacher, tenant \[standard:public\] Running migrations: \[standard:public\] Applying contenttypes.0001_initial... \[standard:public\] OK \[standard:public\] Applying contenttypes.0002_remove_content_type_name... \[standard:public\] OK \[standard:public\] Applying auth.0001_initial... \[standard:public\] OK \[standard:public\] Applying auth.0002_alter_permission_name_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0003_alter_user_email_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0004_alter_user_username_opts... \[standard:public\] OK \[standard:public\] Applying auth.0005_alter_user_last_login_null... \[standard:public\] OK … -
Django form and Inline form with crispy forms layout
I have a form with a custom layout from "crispy forms" and an inline form manually in HTML. If I don't use custom layouts, I can save both with no problem, however I'll need to make a button to submit the forms together using layouts. This is my HTML: <form id="registro-form" class="main-form" action="?" method="POST"> <!-- Main Form --> {% csrf_token %} {% crispy form %} <hr> <!-- Inline Formset --> {{ itens_formset.management_form }} {% for formset_form in itens_formset %} <div class="inline-formset-item"> <!-- Render inline formset fields manually --> <div class="row no-gutters"> <!-- Render formset fields here --> </div> </div> {% endfor %} <!-- Submit Button --> <button class="btn btn-success mt-2 mb-5" type="submit" style="width: 110px;">Salvar</button> </form> This is my html code at the moment, but when I click the submit button, nothing happens. This is my views.py: class RegistrarCreate(GroupRequiredMixin, CreateView): # GroupRequiredMixin and other attributes def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ItemFormSet = inlineformset_factory(Registro, Item, form=ItemForm, extra=1, can_delete=False) if self.request.POST: context['itens_formset'] = ItemFormSet(self.request.POST, instance=self.object) else: context['itens_formset'] = ItemFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() itens_formset = context['itens_formset'] if itens_formset.is_valid(): self.object = form.save() itens_formset.instance = self.object itens_formset.save() return super().form_valid(form) else: print("Formset is invalid") print(itens_formset.errors) return self.render_to_response(self.get_context_data(form=form)) def get(self, request, *args, … -
The difference between prefetch_related and model_set in Djnago
I wonder what is the best flow when I need to retrieve foreign key model objects. is it to use prefetch_related in views.py like: queryset = queryset.prefetch_related('book_set') context={objects:queryset} or to use directly in the template by model_set: {% for attach in objects.book_set.all %} what is better and which one is good for performance? -
Cannot render custom form field in templates
So I've built this some kind of spam detection field that I want to use in our templates. As you can render other other form fields in the template with form.X, I cannot render this one: {{ forms.tour_form.form.spam_field }} <web.utils.forms.HoneypotField object at 0x7f3c0fd98820> But I can't seem to find what's the issue here? I'm using SpamDetectFormMixin in my forms. class HoneypotField(forms.BooleanField): default_widget = forms.CheckboxInput( attrs={"class": "hidden", "tabindex": "-1", "autocomplete": "off"} ) def __init__(self, *args, **kwargs): kwargs.setdefault("widget", self.default_widget) kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if cleaned_value := super().clean(value): raise ValidationError("") return cleaned_value class SpamDetectFormMixin(forms.Form): spam_field_keys = ["adf", "adg", "adh"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.random_key = random.choice(self.spam_field_keys) self.fields[self.random_key] = HoneypotField() @property def spam_field(self): return self.fields[self.random_key] -
How to make generate Custom ID for employee in django using different String
I have model's like this : class Karyawan(models.Model): id_karyawan = models.CharField(max_length=10, blank=True,null=True) nama_karyawan = models.CharField(max_length=50) jabatan = models.CharField(max_length=15) branch_id = models.ForeignKey(Branch, on_delete = models.CASCADE,null=True) agen_id = models.ForeignKey(Agen, on_delete = models.CASCADE,null=True) salary = models.IntegerField() alamat_karyawan = models.TextField() tanggal_masuk = models.DateField(null=True) kota_karyawan = models.CharField(max_length=30, null=True) ttl_karyawan = models.DateField(null=True) tanggal_resign = models.DateField(null=True,blank=True) no_hp_karyawan = models.CharField(max_length=15) slug_karyawan = AutoSlugField(populate_from='id_karyawan') I want id_karyawan filled using branch_id at first then following id using unique id like 'BDO001','BDO002', 'JKT001' etc. -
How do I connect my React frontend with my Django backend?
I've been trying to connect my React frontend with Django backend server to complete development of a sign up page. I'm trying to test a simple GET HTTP request to my server which I know is functioning correctly. However every time the code compiles I get these errors in the console instead of a response. For reference here are some photos. My Signup page JSX Errors in the console I looked into the errors and found they were Axios Errors. Axios is the HTTP calls library I am using but I am unsure why these errors are being thrown. I have attempted to configure CORS headers in multiple ways as well but with no success. I think I am either declaring it incorrectly. Ways I've tried to Configure my CORS headers: Using the axios properties e.g. Method 1 I found this next fix on this site Here is how I implemented it in my index.js file Method 2 -
Edit multiple tables in database in django
I have a page with the user can edit the information in database, and this page have more than one table (InformacaoFamilia, Imagens). The images i can delete and insert. But when click in confirm the fields with a legend dont save in database. In this page have a form with all fields in InformacaoFamilia models, have a image and a textarea with respectivily legend, have all images and the user can select what goes to delete, and for a add news images. but the legend dont saving in database. update_facthseets.html <article> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <p class="form-group"> {% if field.errors %} <div class="">{{ field.errors.as_text }}</div> {% endif %} <label class="" for="{{ field.id_for_label }}"> {{ field.label }}: </label> {{ field }} </p> {% endfor %} <hr> Editar Legenda {% for image in images %} <div class="imagem"> <p> <label for="edit-legend-{{ image.id }}"> <img src="{{ image.imagens.url }}" alt="{{ image.legenda }}"> Legenda: <textarea type="text" name="imagens-{{ image.id }}-legenda" id="edit-legend-{{ image.id }}" value="{{ image.legenda }}">{{ image.legenda }}</textarea> </label> </p> </div> {% endfor %} Excluir Imagens {% for image in images %} <div class="imagem"> <!-- <p class="paragrafo-{{ image.id }}"> --> <input type="checkbox" name="delete_image" value="{{ image.id }}" id="delete-image-{{ image.id … -
How to reference/mess with a model in a JS file (Django)
So I have a model Profile with a field level (IntegerField) upon completion I would like to add a number to that field but I'm not sure how to reference it in the JS file. Can I edit a models field in a JS file? I'm new to Django and couldn't find anything in the ''documentation''. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) rpg_class = models.CharField(max_length=100, default='Warrior') level = models.IntegerField(default=1) def __str__(self): return str(self.user) Views.py: profile = self.get_object() context['level'] = profile.level return context for now I just want to know if I can do something like this in hte JS file model_name += 1; but I cant figure out how to reference it -
Custom permission class not returning custom permission denied message - DRF
I have a custom permission class where I want a custom permission message to be returned. But it is returning the default permission denied message. Below is the custom permission class that I have written: class IsAuthenticatedAndIsLr(BasePermission): def has_permission(self, request, view): message = "user is not LR" return request.user.is_authenticated and request.user.regd_as == "LR" and here is how I am using it on the api: @api_view(['POST']) @permission_classes([IsAuthenticatedAndIsLr]) def create_profile(request): ''' this api creates profile for users based on their choosen category. ''' data = request.data model_dict = { 'IND' } try: ... return Response({'message': f'{request.user} isLR'}, status= status.HTTP_201_CREATED) except Exception as e: return Response({"message": str(e)}, status= status.HTTP_500_INTERNAL_SERVER_ERROR) I have followed the docs method to raise a custom message but for some reason it is not working. Please suggest to me what is the cause of this problem. -
Gitlab CI/CD and Azure deploying Django
Am trying to deploy Django code to Webapp using gitlab CI, here's the .gitlab-ci.yml ; image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - deploy deploy-azure-stag: stage: deploy image: mcr.microsoft.com/azure-cli script: - echo "Logging into Azure" - az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET --tenant $AZURE_TENANT_ID - echo "Deploying to Azure App Service" - az webapp up --name $AZURE_APP_NAME However am getting this error, how best can I continuously deploy my Django code . Error am getting. Deploying to Azure App Service $ az webapp up --name $AZURE_APP_NAME WARNING: Webapp 'app_name' already exists. The command will deploy contents to the existing app. ERROR: Unable to retrieve details of the existing app 'app_name'. Please check that the app is a part of the current subscription if updating an existing app. If creating a new app, app names must be globally unique. Please try a more unique name or leave unspecified to receive a randomly generated name. Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 -
How can i shuffle my questions in Django views?
I have got a project with quiz and it needed to make random questions. I try like this: @login_required def test(request, test_id): test_set = get_object_or_404(TestSet, id=test_id) questions = test_set.question_set.all().order_by('?') But when i take an a next question it may be repeated. How can i fix it? Also i have a button like "repeat" -
Save() method does not save my form to database
Coding a simple form to add articles to website. Failed to add any information from form to database. My models.py from django.db import models class Articles(models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('announcement', max_length=250) full_text = models.TextField('Article') def __str__(self): return self.title class Meta(): verbose_name = 'news' my forms.py from .models import Articles from django.forms import ModelForm, TextInput, Textarea class ArticlesForm(ModelForm): class Meta: model = Articles fields = ['title', 'anons', 'full_text'] widgets = { 'title': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Header' }), 'anons': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Announcement' }), 'full_text': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Text' }), } my views.py from django.shortcuts import render, redirect from .models import Articles from .forms import ArticlesForm def news(request): news = Articles.objects.all() #[:2] - срез записей return render(request, 'news_templates/news.html', {'news': news}) def create(request): error = '' if request.method == 'POST': form = ArticlesForm(request.POST) if form.is_valid(): form.save return redirect('./') else: error = "Wrong format" form = ArticlesForm() data = { 'form': form, 'error': error } return render(request, 'news_templates/create.html', data) template for page {% extends 'main/layout.html' %} {% block title %}Create article {% endblock %} {% block content %} <main class="features"> <h1>Add an article</h1> <form method='post'> {% csrf_token %} {{ form.title }}<br> {{ form.anons }}<br> {{ form.full_text }}<br> <button …