Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic ModelChoiceField on template
I would like to have a ModelChoiceField that is dynamically changed by the user directly on the form. Basically I'm building a CMS and User has several templates at its disposal, however I'd like to display in my dropdown only the relevant templates to the kind of content it's producing. For example, we would have a first dropdown to select the content_type. We assume we pick article. Selecting this would update in a second dropdown list both including side_image_article.html and default_article.html. Here is a MRE : models.py class MyTemplate(models.Model): template_name = models.Charfield(max_length=80) content_choices = [("article", "article"), ("project", "project"), ("press_release", "press_release"), ("newsletter", "newsletter"), ("newsletter_web", "newsletter_web"), ("petition", "petition"), ("mailing_list_signup", "mailing_list_signup"), ] content_type = models.CharField(max_length=100, choices=content_choices, default="article") Each template is assigned a content type that is appropriate to the sort of content it's designed for. still models.py class MyBlogitem(models.Model) template = models.ForeignKey(MyTemplate, on_delete=models.PROTECT) body_text = models.TextField() content_choices = [("article", "article"), ("project", "project"), ("press_release", "press_release"), ("newsletter", "newsletter"), ("newsletter_web", "newsletter_web"), ("petition", "petition"), ("mailing_list_signup", "mailing_list_signup"), ] item_type = models.CharField(max_length=100, choices=content_choices, default="article") And the forms.py class MyBlogItemForm(ModelForm): template = ModelChoiceField( queryset=TopicBlogTemplate.objects.filter( content_type=???), empty_label=None) So here the goal would be to filter the template field using the content_type field, both being in dropdown lists. There are being loaded … -
Django FileNotFound image url
The idea is I want my form to upload an image with ImageField and then save a base64 of that image with post_save. Model : class Feed(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length = 200) content = models.TextField() thumbnail = models.ImageField(upload_to='feeds/', blank=True) img_b64 = models.BinaryField(blank=True, null=True) author = models.ForeignKey(Account, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) view = models.IntegerField(default=0) kategori = models.CharField(max_length=100, default="None") post_save : @receiver(post_save, sender=Feed) def save_base64(sender, instance, **kwargs): if instance.thumbnail: img_file = open(instance.thumbnail.url, "rb") instance.image_b64 = base64.b64encode(img_file.read()) instance.save() but I get a FileNotFound error: Traceback (most recent call last): File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\Lapor Hoax\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Project\Lapor Hoax\laporhoax\account\views.py", line 123, in isi_berita_view form.save() File "D:\Project\Lapor Hoax\env\lib\site-packages\django\forms\models.py", line 468, in save self.instance.save() File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "D:\Project\Lapor Hoax\laporhoax\feed\models.py", line 43, in save_base64 img_file = open(instance.thumbnail.url, "rb") Exception Type: FileNotFoundError at /berita/add/ Exception Value: [Errno 2] No such file or directory: … -
Sentry SDK Django set tag for event and raise
This is the current implementation I have: from sentry_sdk import push_scope def run(): with push_scope() as scope: message = "Failed" scope.set_tag("custom", "tag") raise Exception(message) But according to the docs the with-scope context manager will swallow the exception raised inside. The problem is I need this method run to actually raise an Exception so is doesn't send a response to the user. If I handle the flow and capture the sentry event in the with-scope context manager and raise later outside of the context manager, I will end up with duplicate events in Sentry ? from sentry_sdk import push_scope, capture_exception def run(): with push_scope() as scope: message = "Failed" scope.set_tag("custom", "tag") capture_exception(message) raise Exception(message) Is this really sending two events to Sentry and/or is there a better way to deal with this issue, maybe forcing sentry to ignore the raise at this point ? -
CreateView redirect with parameter created from the same view
I have this CreateView that creates an object for me and after creating it I would like it to render me inside that object through its 'nome_scheda' which is a text field. views.py class SchedaCreateView(CreateView): model = Schede fields = ['nome_scheda','data_inizio','data_fine'] template_name = 'crea/passo1.html' def form_valid(self, form): form.instance.utente = self.request.user return super().form_valid(form) urls.py path('crea/<nome>/', creazione, name="creazione_passo1"), -
Publish and "Save Drafts" feature in Django
I am working on a Django Rest Framework B2B application with a React Frontend. The data is fed from a csv and then Analytics dashboards are rendered in React. Each Account ("User") is a company - and within a company, the app is used by the entire marketing team (say). Each company account has data unique to that co. and dashboard preferences unique to that company. An administrator is a human user who is some Manager / employee of a company (let's say, for example, Boeing, Nike etc) who has edit / administrator rights on behalf of the company. That "admin" makes some changes to the dashboard preferences and wants to "Publish" the changes so that rest of the employees (the rest of the Marketing team) of the company Account can view the updated dashboard. But maybe not yet, hence a "Save Drafts" feature. I'm not sure how to get these two features in the most industry-standard way in Django (DRF) - When I hit "Publish", the entire marketing team should be able to see the changes. (It's a B2B app). But when I save drafts, I should be able to view the changes (as admin) but not the rest … -
Django 3.2.3 - 3.2.6 broken pipe error on dev server
I tried beget and digital ocean, different Django-projects (my own and examples) and every time i am getting [05/Oct/2021 12:26:24,844] - Broken pipe from ('94.72.62.225', 53959) I do same things every time: python3 -m venv env . env/bin/activate pip install -r requirements.txt python3 manage.py makemigrations python3 manage.py migrate set ALLOWED_HOSTS=['*'] python3 manage.py rusnerver 0.0.0.0:8000 -
how to use model attribute in views for another model
so basically i have a Product model which has a price attribute as below. class Product(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() image = models.ImageField(upload_to = 'photos/products') stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name then i have this Main model which i make for payments, as you can see there is an amount attribute also there: class Main(models.Model): user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) order_id = models.TextField() payment_id = models.TextField() amount = models.IntegerField() date = models.TextField(default='-') card_number = models.TextField(default="****") idpay_track_id = models.IntegerField(default=0000) bank_track_id = models.TextField(default=0000) status = models.IntegerField(default=0) def __str__(self): return str(self.name) now i want to know how to set amount = price ? currently user enter the amount manually from a form. but i want to pass the price to this function and then set it to amount and then delete the amount input from the html def payment_start(request): if request.method == 'POST': order_id = uuid.uuid1() amount = request.POST.get('amount') name = request.POST.get('name') email = request.POST.get('mail') phone = request.POST.get('phone') payer = { 'name': request.POST.get('name'), 'phone': request.POST.get('phone'), 'mail': request.POST.get('mail'), 'desc': request.POST.get('desc'), } record = Main(order_id=order_id, amount=int(amount), … -
Is it possible to return a GET request after saving the post request to the database?
I have been trying to return the GET response after the post request has been made and the data has been saved to the DB. Instead of the serialized validated data being returned to the api caller. It would save another GET request handling on the frontend Here are the serializers: class PollVoteSerializer(serializers.ModelSerializer): class Meta: model = PollVote fields = '__all__' class PollAnswerSerializer(serializers.ModelSerializer): is_correct_answer = serializers.SerializerMethodField() answer_votes = serializers.SerializerMethodField(read_only=True) class Meta: model = PollAnswer fields = ('id', 'answer', 'is_correct_answer', 'answer_votes', ) def get_is_correct_answer(self, object): if object.question.is_finished: return object.is_correct return False def get_answer_votes(self, object): return object.answer_vote.count() class PollQuestionSerializer(serializers.ModelSerializer): choices = PollAnswerSerializer(many=True, read_only=True) total_votes = serializers.SerializerMethodField(read_only=True) user_voted = serializers.SerializerMethodField(read_only = True) class Meta: model = PollQuestion fields = ['id', 'question_name', 'created_by', 'is_finished', 'total_votes','user_voted', 'choices', ] def get_total_votes(self, question_vote): c = PollVote.objects.filter(question=question_vote).count() return question_vote.question_vote.all().count() def get_user_voted(self, object): user_id = self.context['request'].user.id return PollVote.objects.filter(question__id = object.id, voted_by = user_id).exists() Here is the view. class GetPoll(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == 'create': return PollVoteSerializer else: return PollQuestionSerializer queryset = PollQuestion.objects.all().order_by('-id') authentication_classes = (authentication.TokenAuthentication,) permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination Apologies for the massively unneat formatting. I am fairly new to Stack Overflow. -
TypeError at/xx 'method' object is not subscriptable Django
when i try to update i get TypeError,I'm having trouble updating even though I have successfully added and deleted. I'm getting an error even though it just worked, where could I have made a stupid mistake models.py; class problemduyuru(models.Model): olusturulmatarihi = models.DateTimeField(auto_now_add=True, null=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py; def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST.get['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') HTML; <form class="form-horizontal" action="problemduyurusuupdate/{{ problemmembers.id }}" method="POST"> {% csrf_token %} <div class="bd-callout bd-callout-danger"> <div class="bd-calloutic bd-callout-dangeric "> <div class="dangericon"></div> <h4 id="asynchronous-methods-and-transitions" style="color: #e70800;"><b>Technology Announcements</b></h4> <h7 id="asynchronous-methods-and-transitions" style="color:red; font-weight: 400; ">Problem Duyurusu</h7></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Duyuru Tipi:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.duyurutipi }}" name="duyurutipi" id="duyurutipi" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Incident No:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.incidentno }}" name="incidentno" id="incidentno" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Başlangıç Zamanı:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.baslangiczamani }}" name="baslangiczamani" id="baslangiczamani" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3" > <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;" … -
Making Django Function Work On HTML On Button Click
I'm trying to call a view so that it displays within a div on the page I already have existing rather than linking to a new page to post a comment. So far I've been able to bring up the div which shows after a button click and hides when pressed again. Ideally, when it shows the form for a comment should show yet at the moment it is only the submit button. I'm wondering how I could get this form to show up in this div as it does on the other HTML page. If there is any more required info let me know, just didn't want to give too much to look at. Views.py: class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'storysharing/comment.html' def form_valid(self, form): form.instance.story_id = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return reverse('storysharing:story_details', kwargs={'story_id':self.kwargs['pk']}) urls.py: app_name = 'storysharing' urlpatterns = [ path('', views.index, name = 'index'), path('<int:story_id>/', views.story_details, name = 'story_details'), path('add_story/', views.add_story, name = 'add_story'), path('thanks/', views.story_added, name = 'story_added'), path('final_post/<int:pk>', UpdateStoryView.as_view(), name = 'final_post'), path('review/', views.review, name = 'review'), path('get_location/', views.get_location, name = 'get_location'), path('<int:pk>/comment', AddCommentView.as_view(), name = 'comment'), ] page.html, the tag is where the link usually links to the other … -
Django. Как в шаблоне узнать наличие значения в QuerySet
Всем привет! Есть две связанные модели, вопрос и ответ от пользователя: models.py class TasksModel(models.Model): title = models.CharField('Заголовок задания', max_length=100) description = models.TextField('Описание') class UserAnswerTasks(models.Model): task_id = models.ForeignKey(TasksModel, verbose_name='id задания', on_delete=models.CASCADE) user_id = models.ForeignKey(ProjectUsers, verbose_name='id пользователя', on_delete=models.CASCADE) answer = models.TextField('Ответ на задание') Представление: views.py def index(request): user = request.user # берём пользователя tasks = TasksModel.objects.all() # Берём все вопросы all_answers = UserAnswerTasks.objects.filter(user_id=user) # Берём все ответы от этого пользователя content = { "tasks": tasks, "all_answers": all_answers } return render(request, 'tasksapp/index.html', content) Далее мне нужно в index.html вывести все вопросы из "tasks", и к ним же создать кнопку что если вопрос уже решён пользователем то "Кнопка 1" если пользователь ещё не решил этот вопрос то "Кнопка 2" index.html {% for i in tasks %} <h2"> <a href="{% url 'tasks:task' i.pk %}">{{ i.title }}</a> </h2> ???И ВОТ ТУТ КАК СДЕЛАТЬ ВЫДАЧУ??? {% if i.id in all_answer %} <a href="" class="btn">Посмотреть свой ответ</a> {% else %} <a href="" class="btn">Приступить к заданию</a> {% endif %} {% endfor %} Проходить снова циклом не хочется по all_answer, знаю что тип данных разный для оператора in, я знаю как решить задачу ещё одним циклом по all_answer. Но может есть способ сделать это при помощи if in, или какого … -
Django custom decorator for redirections
I'm deploying a multi-domain platform in Django, with some model logic for performing redirections between websites. As the redirection mapping is going to get slightly bulky I'd rather decorate each view as opposed to replicate the code for redirections in every view (I'm sticking to function-based views for this project). As the logic could possibly be changed too, I need to have it all in one place and I'd really like to use a custom decorator for that. I've been trying different syntaxes in order to define a decorator and I'm getting all sorts of problems. https://pythonbasics.org/decorators/ I'm using the syntax I see here but I couldn't apply it to Django views at first. I'm using Django 3.2. This is the thread that most resambles my situation and which helped me get closer to the result I want Django custom decorator redirect problem however my decorator view still returns None instead of an HttpResponse object and I don't understand. Decorator 1 def inner(request, *args, **kwargs): print("DEBUGGING") if settings.DEBUG == False or request.user.is_superuser == False: return render(request, 'myapp/manutenzione.html') func(request, *args, **kwargs) return inner Decorator 2 for my redirection def reindirizzamenti_necessari(func): def inner(request, *args, **kwargs): print("REINDIRIZZAMENTI") sito = get_current_site(request) dominio = sito.domain … -
Error: Request failed with code 403 in axios post api
I am struggling with this problem for a while. I have a new django-vue project, just created it. When I press a button that makes a api request I get the 403 error and recieve "Forbidden (CSRF cookie not set.):" through console. I made some other little newbie projects and I never pass the CSRF token before in a api post. I think that must be another error but I don't know which one The code is the following: views.py from django.shortcuts import render from django.http import HttpRequest, HttpResponse, JsonResponse, HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required import requests def discord_login(request): print('Hola, cómo estas') return redirect(auth_url_discord) settings.py from pathlib import Path ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'key', 'discordlogin', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'leviathan_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'leviathan_django.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
How to use regex in django query to get the shortest match?
I have some bunch of entries in a column of a Postgres database that looks like below Abcd/* Abcd/dir1/* Abcd/dir1/dir2/* Abcd/dir1/dir2/dir3/* I am using django ORM to access this information like below given_path = "/some/path" access_obj = Access.objects.get(dir_id=given_path) #dir_id is the column name Now given a path, I need to find the earliest match (any path after * is allowed, hence don't search further) and give the result back. What I mean is say a path is given Abcd/dir1/dir2, since my first entry itself is Abcd/* so I don't need to look any further and return the first row object itself. Currently I try to fetch using __icontains check like below access_obj = Access.objects.get(dir_id__icontains=given_path) But it would return all the matches and then I am unable to figure out how to target the first match (in this case) and query the object. I am aware django supports regex on queries but I am not sure what to apply here. Any help will be appreciated. -
How do delete an object using axios and Django?
I've got a react Frontend, and a Django backend. I am basically trying send some data to the backend in order to filter out the desired object to delete it. However, I am only able to delete an object when both the django method and the axios method are PUT, not DELETE. (authentication disabled) Here is the error I get when I use DELETE instead of PUT: Error (authentication enabled) Here is the error I get when I use DELETE instead of PUT: Error Codes to delete an object here is my backend code: class deleteTrack(APIView): permission_classes = [IsAuthenticated] def delete(self, request): #ONLY WORKS WHEN THIS METHOD IS PUT, AND WHEN THE AXIOS METHOD IS ALSO PUT user = request.user data = request.data track = Track.objects.get(user=user) trackitem = TrackItem.objects.get(track=track,_id=data['trackitem_id']) trackitem.delete() message = {'detail':'Tracked Item successfully deleted'} return Response(message,status=status.HTTP_200_OK) Here is my frontend code: export const deleteTracks = (track) => async(dispatch,getState) => { try{ dispatch({ type:TRACK_DELETE_REQUEST, }) const { userLogin: {userInfo}, } = getState() const config = { headers:{ 'Content-type':'application/json', Authorization:`Bearer ${userInfo.token}` } } const { data } = await axios.delete(`/api/deletetrackitem/`,track,config) dispatch({ type:TRACK_DELETE_SUCCESS, payload:data, }) } catch(error){ dispatch({type:TRACK_DELETE_FAIL, payload:error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } Example data that … -
django-multiupload | render() got an unexpected keyword argument 'renderer'
I have the error "render() got an unexpected keyword argument 'renderer'" after starting using the django-multiupload. Hope someone can help me, please. Some info about my project: Django Version: | 3.1.7 Python Version: | 3.7.11 My models.py: class Intervention(models.Model): tower = models.ForeignKey('Tower', on_delete=models.DO_NOTHING) .... //got many other attributes class InterventionData(models.Model): interv = models.ForeignKey(Intervention, on_delete=models.CASCADE) files = models.FileField(upload_to="attachments") My forms.py: class InterventionForm(ModelForm): files = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5) class Meta: model = Intervention fields = ('tower',...) //got many other attributes def __init__(self, *args, **kwargs): super(InterventionForm, self).__init__(*args, **kwargs) self.fields['tower'].label = "Tower" .... //got many other attributes def save(self, commit=True): instance = super(InterventionForm, self).save(commit) for each in self.cleaned_data['files']: InterventionData.objects.create(files=each, interv=instance) return instance My views.py: def view_intervention(request, interv_id): try: interv = Intervention.objects.get(pk=interv_id) except Intervention.DoesNotExist: return HttpResponseRedirect(reverse("list_interventions")) if request.method == 'GET': form = InterventionForm(instance=interv) .... elif request.method == 'POST': form = InterventionForm(request.POST, request.FILES, instance=interv) if form.is_valid(): interv = form.save(commit=False) ... form.save() return render(request, 'view_intervention.html', {'form': form, 'interv_id': interv_id, 'interv': interv}) My HTML: <form action="{% url "view_intervention" interv_id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} .... <div class="form-group"> {{ form.files.errors }} {{ form.files.label_tag }}{% if form.files.field.required %} *{% endif %} {{ form.files }} </div> <input type="submit" value="Send" /> </form> -
Django multi stage form saves all fields except for selection fields
I have a multistage form. All fields save successfully but not select fields. My code related to the select field: Forms.py YEAR = [(r, r) for r in range(datetime.now().year, 1940, -1)] = forms.ChoiceField( label="Year", choices=YEAR, ) view.py @require_http_methods(["POST"]) def step5(request): form = forms.StepFive(request.POST) if form.is_valid(): status = 200 else: status = 400 return render( request, "step5.html", context={ "form": form, }, status=status, ) The html product on the browser <select class="form-control " name="year" id="id_year" aria-describedby="id_year-help" cursorshover="true"> <option value="2021">2021</option> <option value="2020">2020</option> ... etc ... </select> All the fields from the same step get saved except for the select value. I can see the form in the from.cleaned data but it gets reset when I click next. -
Is it safe to add EC2 public IP to ALLOWED_HOSTS in Django + Elastic Beanstalk?
I have deployed a Django app as a single instance Elastic Beanstalk environment without Elastic Load Balancer. The setup is Nginx + Gunicorn + Django. SSL is enabled for Nginx server. I have added the host assigned by elastic beanstalk (....elasticbeanstalk.com) to ALLOWED_HOSTS in the settings file, and the app is accessible. But some operations are failing and there are a lot of Invalid HTTP_HOST_HEADER errors in the log file. The header in majority of these errors are the Public IP of the EC2 instance. Is it safe to add the EC2 Public IP to the allowed hosts ? -
DJANGO | Redirect/Disable URLs based on environment variables
Usecase: I have some features that I don't want to release as of yet so I want to disable certain URLs or redirect them to 404/505s in production environment. Is there a way to accomplish that using just the environment settings instead of popping out routes in urls. -
Changing dropdown selection in django admin
I have a model as: class ProductSubcategory(models.Model): category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.SET_NULL) sub_category = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.sub_category class ProductCategorization(models.Model): product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.SET_NULL) subcategory = models.ForeignKey(ProductSubcategory, null=True, blank=True, on_delete=models.SET_NULL) Whenever one selects a category like Bath & Body in the subcategory section one should only see the subcategories of Bath & Body.But now all the subcategories are listed. my admin.py class CategorizationInline(admin.TabularInline): model = ProductCategorization fields = ('category', 'subcategory', 'id') readonly_fields = ('id',) extra = 1 class ProductAdmin(admin.ModelAdmin): inlines = [ CategorizationInline, ] #..some code -
how to copy one table colums to another tables column in Django?
Please tell me ? how to copy data from one table to another table in django? '''f request.method =="POST": agent_ids = request.POST.getlist('id[]') for id in agent_ids: user_del = User.objects.get(id=id) agent_del= AgentDetail.objects.get(u_id=id) # user_del.delete() # agent_del.delete() print("deleted agent Detail") messages.success(request,"Agent Deleted SuccesFully ")''' i want to know to copy these models(User and AgentDetail) data to new model please help me as soon as possible? -
Can I (safely) override Django settings in a server side wsgi.py?
I want to deploy two Django web-apps (individual domains) that share the same source code/repository and, hence, the same settings file. (Hosted on pythonanywhere by the way). The only difference between the two is that they should access different data bases (which I would usually define in settings.py or .env). As I see it, the only file that is unique to each web-app is their individual ...wsgi.py file (the one on the server not the one in the Django project folder). Thus, my idea is to use that file to specify each app's data base settings. Is it possible to (safely) override settings in a wsgi file? How would I do it? The current wsgi.py file looks like this: # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/.../mysite/mysite/settings.py' ## and your manage.py is is at '/home/.../mysite/manage.py' path = '/home/.../...' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Many thanks for your help! -
Django getting value from database using ajax in tab system
I have a tab pane system Monday to Sunday.And the user select any day,then activate_day attribute of User updated.Then I want to get updated request.user.activate_day value from database without refreshing page.I guess ı have to use ajax but I don't know how to handled that.Can anyone help me ? <li class="nav-item" value="Pazartesi"> <a class="nav-link active" onclick="saveDay('Pazartesi');" data-toggle="tab" href="#slot_monday">Pazartesi</a> </li> <li class="nav-item" value="Salı"> <a class="nav-link" onclick="saveDay('Salı');" data-toggle="tab" href="#slot_tuesday">Salı</a> </li> <li class="nav-item" value="Çarşamba"> <a class="nav-link" data-toggle="tab" onclick="saveDay('Çarşamba');" href="#slot_wednesday">Çarşamba</a> </li> <li class="nav-item" value="Perşembe"> <a class="nav-link" onclick="saveDay('Perşembe');" data-toggle="tab" href="#slot_thursday">Perşembe</a> </li> <li class="nav-item" value="Cuma"> <a class="nav-link" onclick="saveDay('Cuma');" data-toggle="tab" href="#slot_friday">Cuma</a> </li> <li class="nav-item" value="Cumartesi"> <a class="nav-link" onclick="saveDay('Cumartesi');" data-toggle="tab" href="#slot_saturday">Cumartesi</a> </li> <li class="nav-item" value="Pazar"> <a class="nav-link" onclick="saveDay('Pazar');" data-toggle="tab" href="#slot_sunday">Pazar</a> </li> </ul> </div> <!-- /Schedule Nav --> saveDay() function(it is working but I don't know how to use returning day) <script> function saveDay(day) { $.get("change_active_day/" + day); } </script> my views.py def change_active_day(request,day): user=get_object_or_404(CustomUserModel,email=request.user.email) user.active_day=day user.save() load_active_day_of(request) data = json.loads(day) return JsonResponse(data=data,safe=False) urls.py path('change_active_day/<str:day>',change_active_day,name="change_active_day"), -
Getting error related to django model arrayfield
When trying to access serialized.data, throws error for type models.ArrayField, but is successfully stored in mongodb. models.py class testStep(models.Model): number = models.PositiveSmallIntegerField(max_length=100) payload = models.JSONField(blank=True) header = models.JSONField(blank=False) assertors = models.EmbeddedField(model_container=assertStep, blank=True) class Meta: abstract = True class test(models.Model): _id = models.ObjectIdField(primary_key=True) appId = models.ForeignKey(application, on_delete=models.PROTECT) name = models.TextField(blank=False, unique=True) step = models.ArrayField(model_container=step, blank=True, default=list) serializers.py class testStepSerializer(serializers.ModelSerializer): class Meta: model = models.testCase fields = '__all__' read_only_fields = ['dateCreated', 'dateUpdated', ] def update(self, instance, validated_data): instance.testStep = validated_data.get('testStep', instance.testStep) instance.save() return instance views.py def put(self, request, testCaseId, format=None): tcDetails = self.getTcDetails(testCaseId) reqData = request.data.copy() if serialized.is_valid(): serialized.save() return Response(json.loads(json_util.dumps(serialized.data)), status=status.HTTP_200_OK) -
Generate shareable link feature in Django?
I have a Django Rest Framework application that is fed in data from a csv. I then use React to create dashboards and Widgets from that data. I want to be able to generate a link to share a read-only version of any dashboard, much like in Google docs etc. I'm not sure how to go about doing that. Any help / pointers would be appreciated. Thank you!