Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send two pk in one url link when Update and Delete
my superb Internet friends. I have been creating an easy pfc calculator Django app as a beginner. While making it, I have got an error, which is "Generic detail view CommentUpdate must be called with either an object pk or a slug in the URLconf." I don't even know why this error showed up coz I think my way in urls.py is correct. If you know how to solve this error, please leave your comment below. Any comments help me and thanks for your time in advance!! # urls.py # path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'), path('blog/<int:blog_pk>/comment/update/<int:comment_pk>/', CommentUpdate.as_view(), name='comment_update'), path('blog/<int:blog_pk>/comment/delete/<int:comment_pk>/', CommentDelete.as_view(), name='comment_delete'), <div class="comment-right"> {% if request.user == blog.user %} <a href="{% url 'comment_update' blog.id comment.id %}" class="far fa-edit"></a> <a href="{% url 'comment_delete' blog.id comment.id %}" class="far fa-trash-alt"></a> {% endif %} </div> # view.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() form = CommentForm() comments = Comment.objects.order_by('-created').filter(blog=blog.id) number_of_comments = comments.count() if blog.link_1 is not None or blog.link_2 is not None: link_1 = blog.link_1 link_2 = blog.link_2 context = { 'blog': blog, 'link_1': link_1, 'link_2': link_2, 'form': … -
【Django】Can't Create Objects while Deploying on Heroku
I was trying to deploy a web that can get titles from a youtube playlist by pytube. Although it works fine at local, it can't work while I deployed it on Heroku. I've checked some possible problems, it can get titles from a playlist, but can't create objects. I also tried to create through admin and it worked. The logs of the web: 2021-06-26T02:01:39.314791+00:00 app[web.1]: techno 2021-06-26T02:01:41.049869+00:00 heroku[router]: at=info method=POST path="/add/" host=t3chn0-l0ver-sharing.herokuapp.com request_id=eaa2092e-29f0-4d78-89ec-44ec2638d0e6 fwd="114.32.78.170" dyno=web.1 connect=5ms service=2437ms status=302 bytes=407 protocol=https 2021-06-26T02:01:40.969867+00:00 app[web.1]: ['German Underground Techno | Dark & Hard | Fear N Loathing in Berlin [FNL043]', 'Amelie Lens - Stay With Me'] 2021-06-26T02:01:40.970261+00:00 app[web.1]: List:['German Underground Techno | Dark & Hard | Fear N Loathing in Berlin [FNL043]', 'Amelie Lens - Stay With Me'] 2021-06-26T02:01:40.970336+00:00 app[web.1]: ready to add 2021-06-26T02:01:41.023841+00:00 app[web.1]: len:0 2021-06-26T02:01:41.035167+00:00 app[web.1]: can't add 2021-06-26T02:01:41.035203+00:00 app[web.1]: ready to add 2021-06-26T02:01:41.041182+00:00 app[web.1]: len:1 Whole program: https://github.com/cojemma/techno_web -
pyhon based amazon web scraper working fine on local machine but getting blocked after deployment
I have built an Amazon product price tracker and the code works perfectly fine on Django local server but after deploying it, it is getting blocked by amazon. what could be the cause and how can I solve it? utils.py from bs4 import BeautifulSoup import requests from django.conf import settings # Windows 10 with Google Chrome user_agent_desktop = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\ 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 '\ 'Safari/537.36' headers = { 'User-Agent': user_agent_desktop} def getproduct(url): result = requests.get(url, headers=headers) soup = BeautifulSoup(result.text, 'lxml') print(soup) price = 0 deal_price = 0 title = soup.find('span',attrs={'id':'productTitle'}).text.strip() ''' other scrapping code ''' return product -
bulma sass compiler ruturns error on edit the .scss file in django project
I'm working on a django project, and I'm using bulma. I run python3 manage.py sass-compiler --watch and when I edit the mystyles.scss file, sometimes I get some errors like in this picture and it stops, but sometimes there is no error or stoping. Where is the problem? -
How to send two pk when Update and Delete
my superb coding friends, I want to ask you how to send two pk(blog's and comment's). I want to let users edit their comments and delete them if they want. But, to do so, I need to send two pk which I don't know how to. I googled and tried what a website said, but doesn't work well. Any comments help me and thanks for your time in advance!! Here are the codes I wrote... # urls.py # the two HTML names are comment_update.html and comment_delete.html from django.urls import path from . import views from .views import BlogCreate, BlogUpdate, BlogDelete, BlogList, CommentUpdate, CommentDelete # blogs urlpatterns = [ path('', views.index, name='latest_blogs'), path('my_blogs/', views.my_blogs, name='my_blogs'), path('my_blogs/my_blog_search', views.my_blogs_search, name='my_blogs_search'), path('drafts/', views.drafts, name='drafts'), path('blog/<int:pk>/', views.blog, name='blog'), # path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'), path('blog/<int:blog_pk>/comment/update/<int:comment_pk>/', CommentUpdate.as_view(), name='comment_update'), path('blog/<int:blog_pk>/comment/delete/<int:comment_pk>/', CommentDelete.as_view(), name='comment_delete'), path('create/', BlogCreate.as_view(), name='blog-create'), path('update/<int:pk>/', BlogUpdate.as_view(), name='blog-update'), path('delete/<int:pk>/', BlogDelete.as_view(), name='blog-delete'), path('all_blogs/', BlogList.as_view(), name='all_blogs'), path('all_blogs/all_blogs_search/', views.all_blogs_search, name='all_blogs_search'), ] # views.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() comments = Comment.objects.all().filter(blog=blog.id) number_of_comments = comments.count() # if request.method == 'POST':+ # form = CommentForm(request.POST) … -
Validation of an inline formset dependent on one field from the parent form
I want to use custom validation in a django inline formset (form_date_event) so that I get different validation according to one value on the parent (form_event) form. Specifically, I'd like the form_date_event inline formset to accept an empty venue if the type of the form_event is 'recording release'. How can I achieve that? The type = cleaned_data.get('type') below doesn't work, I suppose because it's getting the clean data of the formset, not of the parent form. models.py: class Event(models.Model): EV_TYPE = ( ('performance', 'performance'), ('recording release', 'recording release'), ('other', 'other'), ) title = models.CharField(max_length=200) type = models.CharField(max_length=20, choices=EV_TYPE, default="performance") class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) forms.py: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'type', 'title', ] views.py: class BaseDateEventFormSet(BaseInlineFormSet): def clean(self): cleaned_data = super().clean() type = cleaned_data.get('type') def event_edit_view(request, id): event = get_object_or_404(Event, id=id) form_event = EventForm(request.POST or None, instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), formset = BaseDateEventFormSet) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), queryset=dateEvent.objects.filter(event__id=id)) -
How can i use UpateView and ListView together?
I have a form to update, but this page also has a list of objects to display, and I don't know how to combine functionality of UpdateView and ListView. I read about mixins but did not understand how to use them with UpdateView views.py class VacancyEdit(UpdateView): model = Vacancy template_name = 'vacancies/vacancy-edit.html' fields = ['title', 'skills', 'description', 'salary_min', 'salary_max'] pk_url_kwarg = 'vacancy_id' success_url = '/' context_object_name = 'Application' -
React Native, Expo Video: Encountered a fatal error during playback: The server is not correctly configured
I'm having trouble with video playback using expo video in my React Native app. Originally playback worked fine when I temporally used dropbox to serve the media files. Now, I'm serving them on my own backend written with Django and I get this error: Encountered a fatal error during playback: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". What's going wrong here? Thanks! <Video ref={video} style={styles.backgroundVideo} source={{ uri: 'http://127.0.0.1:8000/media/q1intro.mp4', }} resizeMode="contain" shouldPlay onPlaybackStatusUpdate= {(playbackStatus) => _onPlaybackStatusUpdate(playbackStatus)} /> -
Update templates with external API data in django
[example] i have cities in my datatable and want to get data for each city (temp, humidity etc) from API for each city. in the view i can print this data for each city but have problem to do this in datatable (templates). Django templates -
How to add data to a Django IntegerField Model
I am creating an application that gives users donations and points after they fill out the form on my donate.html. In the donate view, I have some code that goes with a different model so please ignore that. I want to know how I can add data to the django integer field. For example if the integer field is equal to 3 and I add one I want it to be equal to 4. Can someone please help? My code is down bellow. Donate View: def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, ) ins.save() return render(request,'donate.html') Model: (I want to add to this data after the ins.save) class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) -
POST request from website server to a game's sqlite database in Python
My friends and I are writing a game. The registration is located on the website and the login is in the game application. I want to send a POST request from the website to the game's database which contains the email, username, and password. The website will use Django to accept registration and send a POST request using it. The game's server will use Flask and SQLAlchemy to put it in their database. Now the problem is, how can I achieve this goal without having people randomly emulate data using 3rd party POST requests? This way is very insecure. What should I do? -
How to create an soft link to a specific django admin table
How do I create a link to a django admin table using the url tag? I have been trying to create a link to a django admin table. This table was registed in the app called store inside a module called admin.py, and was refering to a model called Products. It's possible to access this table at link /admin/store/products/. I would like to know how do I create a link dynamically without writing the hardcoded link in the template. -
How to catch a subclass of DRF ValidationError?
I have a custom error class subclassed from DRF's ValidationError. I can raise it, but I can not catch that error subclass, only ValidationError. from rest_framework import serializers, status class CustomValidationError(serializers.ValidationError): status_code = status.HTTP_400_BAD_REQUEST default_detail = "Something did not go well" default_code = "custom_error" class CustomSerializer(serializers.Serializer): custom_data = serializers.JSONField() def validate_custom_data(self, data): raise CustomValidationError() try: s.is_valid(raise_exception=True) except CustomValidationError as exc: print("caught custom error") except serializers.ValidationError as exc: print("caught default DRF error") # output is always # "caught default DRF error" I feel like I'm missing something very basic here... can anyone help? -
Querying a data with Django ORM to return a specific data that belongs to a user
so I'm trying to build a Ledger App. When new users sign-ups, they create a new Business account that is linked to them (ForeignKey). Here is my model: User = get_user_model() class Business_Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) business_name = models.CharField(max_length=50) Type_of_service = models.CharField(choices=SERVICE_CATEGORIES, max_length=50) business_email_address = models.EmailField(max_length=254) class Meta: verbose_name = "Business_Account" verbose_name_plural = "Business_Accounts" def __str__(self): return self.business_name Now, I want to make a get request view that can query and returns a business account that belongs to a particular user. My current view just returns all the business accounts available in the database irrespective of which user is login. Here is my view: class AddBusinessAcctView(APIView): def get_object(self): try: return Business_Account.objects.all() except: raise status.HTTP_404_NOT_FOUND def get(self,request): queryset = self.get_object() serializer = BusinessAcctSerializer(queryset, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) Now, How can I query business accounts that belong to a particular user?. Thanks in advance -
Is it possible to integrate an old/legacy Django application into Zappa for serverless integration?
I am trying to find a way to integrate our company's Django Web app into Zappa so we can go completely serverless with our REST API. The problem is that our app has existed for several years, making it a lot heavier than the brand new apps that all of these Zappa tutorials init over. Is there a format that Zappa requires for integrating an old Django app into its framework? I have no wait of knowing how much refactoring will be required for Zappa to know how to transition our API into lambda functions. When I tried running Zappa deploy in our root directory, I got the following error, which probably means our app is poorly optimized for the Zappa system: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 896, in deploy function_name=self.lambda_name File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/core.py", line 1520, in get_lambda_function response = self.lambda_client.get_function(FunctionName=function_name) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 386, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 705, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:us-east-1:253119149513:function:src-dev During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 3422, in handle sys.exit(cli.handle()) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 588, … -
cant render Json Data in Django template?
i have simple Filter and Search Function but result dosent showup excatly my views.py if request.method == "POST": post=request.POST.get("category") name=request.POST.get("name") print(name) try: category=Type_Child.objects.filter(type_id=post) response_content=list(category.values()) my_products=Product.objects.filter(name__icontains=name) response_content_product=list(my_products.values()) except Exception: response_content=list({}) response_content_product=list({}) pass data=[{ "name":response_content_product, "category":response_content }] print(data) return JsonResponse(data,safe=False) and that's my Ajax </script> $("#id_name").change(function () { const nameId = $(this).val(); // get the selected subject ID from the HTML dropdown list $.ajax({ // initialize an AJAX request type: "POST", url: '{% url "ajax:ajax_home" %}', data: { 'name': nameId, // add the country id to the POST parameters 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { // `data` is from `get_topics_ajax` view function let html_data = ` `; data.forEach(function (data) { html_data += ` ${data.name} Some quick example text to build on the card title and make up the bulk of the card's content. Go somewhere ` }); $("#id_product").html(html_data); // replace the contents of the topic input with the data that came from the server } }); }); -
Django - The "> symbols appear on the outside of the forms fields manytomany and foreignkey
There's something wrong in my template of html rendered in my django project, the follows symbols "> appear on the outside of my forms fields, this fields call a foreignkey (subjects_id) from a manytomany relation (comorbidities_ids). I think that i'm making some mistake when i call the ids of the manytomany relations and foreignkey fields in the html. Can anybody help me? class Medical_Record(models.Model): subjects_id = models.ForeignKey(Subjects, on_delete=models.CASCADE) HC_number = models.CharField(max_length=20, null=False) diseases_id = models.ForeignKey(Diseases, on_delete=models.CASCADE, null=True) comorbidities_ids = models.ManyToManyField(Comorbidities, null=True) surgery = models.TextField(null=True) clinical_outcomes = models.TextField(null=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) <div class="input-group mb-3"> <div class="input-group-prepend"> <label class="input-group-text" for="id_comorbidities_ids">Comorbidities:</label> </div> <select class="custom-select" name="comorbidities_ids" required="" id="id_comorbidities_ids" multiple=""> <option value="{{ form_medical_records.comorbidities_ids }}"></option> </select> </div> -
Pass request as argument in a ready function of an application in django
I want to perform a query and a request must be passed in order to filter my queryset inside a ready function in apps.py file. class AcademicConfig(AppConfig): name = "academic" def ready(self): from academic.models import AcademicSession AcademicSession.objects.get(some_field=request.user.some_field) How do I suppose to pass a request? -
Is there a way to restrict an API on a public webserver to a specific frontend?
My web application has public API endpoints. I have two frontends one for internal admin and the other for customers both using the same backend endpoints. The goal is to allow certain APIs to only be available to the internal admin frontend. I thought about using HTTP ORIGIN header which would contain the frontend url. Is that a good approach? -
Nested or multiple select_for_updates
I wish to acquire locks on more than one unrelated object using .select_for_update. Do I need to wrap each call with a transaction.atomic? I've read the sections in the Django documentation and postgres' Row Locking but it's unclear on the matter. from django.db import models class A(models.Model): data = models.TextField() class B(models.Model): data = models.TextField() This is a bit of a contrived example, but given the above models, can I do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() b_object = B.objects.get(pk=pk_b).select_for_update() # modify values, etc or do I need to do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() with transaction.atomic(): b_object = B.objects.get(pk=pk_b).select_for_update() -
Django: Dynamically generated form fields are not show in view
I have the following form in my forms.py: class ObjectForm(forms.Form): object_text = forms.CharField(max_length=1000) def __init__(self, *args, **kwargs): krs = kwargs.pop('krs', None) super(ObjectForm, self).__init__(*args,**kwargs) i=6 self.fields['mytry%s' %i] = forms.CharField(label="mytry%s" %i) if krs: for kr in krs: self.fields['text_%s' %kr.no] = forms.CharField(label="kr_text") Now, the field 'mytry6' above the for-loop is shown when I display the form in the html template. But the fields generated in the for-loop are not shown. When I log the content of the form, I see that the additional fields with 'text_1' etc. are included in the form. But somehow they are not shown?!? Can anybody help? Thanks -
django + gunicorn + uvicorn + nginx 504 gateway timeout after adding --preload
Everything works fine for me when I don't use preload option in gunicorn, but when I add --preload to gunicorn, nginx gets 504 gateway timeout. here is my /etc/systemctl/systemd/gunicorn.service: [Unit] Description=uvicorn daemon After=network.target [Service] Environment=DJANGO_SETTINGS_MODULE=MyProject.settings.production User=user1 Group=www-data WorkingDirectory=/home/user1/myproject ExecStart=/home/user1/myproject/venv/bin/gunicorn MyProject.asgi:application --preload -w 2 -k uvicorn.workers.UvicornWorker --log-file - [Install] WantedBy=multi-user.target -
Multiple field boolean filtering by value with Django
I have 3 fields in a dataset that I want to create querysets over the possible permutation values for those fields. These fields are based on a numerical rating scale, so the queries are based on whether a value is matched in the given field. I've already filtered the fields to ensure that the values in all three fields are at minimum a 7 (out of the possible integer values of 7, 8, 9 for those three fields). Now I want to find the following potential comparisons as querysets (!7 means the value can be 8 or 9): [7, 7, 7] [7, !7, 7] [7, 7, !7] [!7, 7, 7] [7, !7, !7] [!7, 7, !7] [!7, !7, 7] I was able to do this with pandas by creating comparison columns with boolean evaluation to check the following permutations, (i.e. column 1 = 7, column 2 != 7 (so either 8 or 9), column 3 != 7 (so either 8 or 9)). permutation_dict = { "all": (True, True, True), "one and three": (True, False, True), "one and two": (True, True, False), "two and three": (False, True, True), "one": (True, False, False), "two": (False, True, False), "three": (False, False, True), } … -
how to get id from object in POST request
Here I m making a POST request with the following data: { "ruleAssignmentDetails": { "id": 1, "ruleAssignment": { "id": 1, "empId": 1, "roleId": 1, "empName": "Emp01", "roleName": "CEO" }, "detailSrl": 12, "rule": 4, "validityType": "F", "startDate": "2021-06-14", "endDate": null, "frequency": { "id": 1, "frequencyName": "Test", "frequencyTpe": "Weekly" } }, "detailSrl": 12, "parameterName": "Param1", "valueType": "D", "overwriteValue": null, "targetDefination": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" } } split the objects into respective models but when I m not getting the 'id' of targetDefination and ruleAssignmentDetails serializer.py class RuleAssignmentParamsSerializers(serializers.ModelSerializer): ruleAssignmentDetails = RuleAssignmentDetailsSerializers() targetDefination = TargetDefinationSerializers() class Meta: model = RuleAssignmentParams fields = ( 'id', 'ruleAssignmentDetails', 'detailSrl', 'parameterName', 'valueType', 'overwriteValue', 'targetDefination', ) def create(self,validated_data): ruleAssDetails = validated_data.pop('ruleAssignmentDetails') targetdef = validated_data.pop('targetDefination') serial = RuleAssignmentParams.objects.create(**validated_data) return serial views.py def getSimpleRules(request): simpleRules = RuleSimple.objects.all() simpleRulesSer = OnlySimpleRules(simpleRules,many=True) return JsonResponse(simpleRulesSer.data,safe=False) @api_view(['GET']) def getRuleAssignment(request,pk): if request.method == 'GET': print("get working") q=get_object_or_404(RuleAssignmentParams,pk=pk) f=RuleAssignmentParamsSerializers(q) return JsonResponse(f.data) @api_view(['POST']) def ruleAssignment(request): if request.method == 'POST': data = JSONParser().parse(request) validated_data = data serializer=RuleAssignmentParamsSerializers(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I run this it shows me this error: IntegrityError at /api/rules/ruleassign (1048, "Column 'ruleAssignmentDetails_id' cannot be null") How do I get the id of ruleAssignmentDetails and targetDefination ? -
Django: How to check that an inline action has been executed?
I have three actions and it just so happens that I have to fix this code so that the application makes sure or at least warns the user (this is still being defined) that they have skipped a step. In my admin.py I have three inline actions: actions = [clean_data, rel_from_db, send_production] They just run actions related to a database in this manner: def send_production(modeladmin, request, queryset): for qs in queryset: qs.clean_data() How can I instead stop the execution (before the loop) to make sure the performed the two previous steps? Could I just save a variable in admin.py that keeps the state. I read the ValidationError indicated in this solution but I'm confused because I wanna validate inline actions (functions) and not exactly a form field.