Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handle multiple post request in Django (Python)
Have created one web application using Django and Python. I am passing some inputs to the pickle model and getting prediction value(on the web page) based on the input data passed to the ML model present in pickle format. I want the web to handle multiple requests parallelly using Django. i.e if multiple users are passing inputs on the web page and wanting prediction values at the same time. How to manage the above scenario. Please provide me high-level scenarios like how to handle this case. You can provide links, videos e.t.c. Django Version: 3.0.2 Python Version: 3.7 -
NGINX filter requests to lan IP
I have received several requests via NGINX that appear to be to my LAN IP 192.168.0.1 as follows: nginx.vhost.access.log: 192.227.134.73 - - [29/Jul/2021:10:33:47 +0000] "POST /GponForm/diag_Form?style/ HTTP/1.1" 400 154 "-" "curl/7.3.2" and from Django: Invalid HTTP_HOST header: '192.168.0.1:443'. You may need to add '192.168.0.1' to ALLOWED_HOSTS. My NGINX configurations as follows: upstream django_server { server 127.0.0.1:8000; } # Catch all requests with an invalid HOST header server { server_name ""; listen 80; return 301 https://backoffice.example.com$request_uri; } server { listen 80; # Redirect www to https server_name www.backoffice.example.com; modsecurity on; modsecurity_rules_file /some_directory/nginx/modsec/modsec_includes.conf; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains;" always; add_header X-Frame-Options "deny" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; #add_header Content-Security-Policy "script-src 'self' https://example.com https://backoffice.example.com https://fonts.gstatic.com https://code.jquery.com"; add_header Referrer-Policy "strict-origin-when-cross-origin" always; return 301 https://backoffice.example.com$request_uri; } server { listen 443 ssl http2; server_name www.backoffice.example.com backoffice.example.com; modsecurity on; modsecurity_rules_file /some_directory/nginx/modsec/modsec_includes.conf; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains;" always; add_header X-Frame-Options "deny" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; #add_header Content-Security-Policy "script-src 'self' https://example.com https://backoffice.example.com https://fonts.gstatic.com https://code.jquery.com"; add_header Referrer-Policy "strict-origin-when-cross-origin"; ssl_certificate /etc/ssl/nginx-ssl/backofficebundle.crt; ssl_certificate_key /etc/ssl/nginx-ssl/backoffice.key; access_log /some_directory/nginx/nginx.vhost.access.log; error_log /some_directory/nginx/nginx.vhost.error.log; location / { proxy_pass http://localhost:8000; proxy_pass_header Server; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header REMOTE_ADDR $remote_addr; } location /media/ { … -
Django: Why wrong user is associated after login via social auth?
I am trying to implement social auth in Django. The idea is that first user has to login in Django and then can login in google or facebook to further request data. But for some reason, Django associates all social logins in "User social auths" table with admin. Vue is used on frontend, Django on backend. My views.py @api_view(('GET',)) def test_login(request): permission_classes = [IsAuthenticated, ] user = request.user print(user) #prints the right user print(user.id) return render(request, 'connectors/registration/login-popup-url.html') My urls.py path('test_login', views.test_login, name="test_login"), connectors/registration/login-popup-url.html template The url will be renderen in a new window generated by Vue function. HTML templates Vue rejects to open. {% block content %}{% url 'social:begin' 'google-oauth2' %}{% endblock %} Vue function for Google login testLogin: function() { var that = this; console.log(that.accessTokenJWT); //Django simplejwt token fetch('http://localhost:8000/test_login', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + that.accessTokenJWT }}) .then(function(response) { console.log(response); return response.text(); }).then( function(response) { console.log(response); console.log('http://localhost:8000' + response); window.open('http://localhost:8000' + response, "", "_blank"); //open // social auth in a new window } ); } Vue function for Django login loginDjango: function() { var that = this; fetch('http://localhost:8000/users/login', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: that.django.username, … -
How to render the DateField on a page in django
Hello I just started learning django and I am having problems rending the content the way I want to. Ideally I want to manage a system of tickets and have the ticket number, start-date, end-date and status appear on the page. Similar to the below format ticket #123456 2021-07-30 2021-08-05 In Progress pages.models.py from django.db import models # Create your models here. class CR(models.Model): STATUS = ( ('N','Not Started'), ('I','In Progress'), ('C','Closed'), ) cr_number = models.CharField(max_length=250) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) status = models.CharField(max_length=20,choices=STATUS) def __str__(self): return self.cr_number pages.models.py from django.shortcuts import render from .models import CR # Create your views here. def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) pages.urls.py from django.urls import path,include from .views import crlistview urlpatterns = [ path('',crlistview,name='crlist'), ] From what I have in my views file the only thing being displayed when i view it in my web browser is only the ticket number. Any help would be appreciated. -
Related to Jenkins, Docker
I am a beginner to DevOps and I have created a new Jenkins project which should build a docker image of a Django project and pushes it to the Docker Hub, then pulls back the image from the Docker Hub and runs it . But when I performed this, getting error as "Value Error: Dependency on app with no migrations: website". And when I pulled the image directly from Docker Hub (without using Jenkins) also I am getting the same error. I understood that it is because of not performing migrations while dockerizing , Kindly help me to perform migrations task and pushes the image to hub and then pulls back and to run it -
ssl installing error nginx service. error no such file
this my nginx conf file server { listen 8001; } server { server_name my_domain; listen 443 ssl; # ssl on; ssl_certificate /ect/ssl/my_cert.crt; ssl_certificate_key /etc/ssl/my_key.key; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject/myproject.sock; } } and here is the error I am getting nginx: [emerg] cannot load certificate "/ect/ssl/my_cert.crt": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/ect/ssl/my_cert.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file) nginx: configuration file /etc/nginx/nginx.conf test failed If I restart the service it throws the error code mentioned above. ssl folder exists for sure. I do not know where I am doing wrong. I searched for the answer but I could not find can anyone help me with this, please? -
My server is not responding, it is hanging up, did not returning anything
I have a docker image successfully built on my mac. I am running this image by typing docker run -p 8000:8000 . Django server is up and ready to accept requests. but when I request to given URL via postman I am getting an error: socket hangs up. Here is my docker file. FROM python:3.6-slim-stretch ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt requirements.txt RUN apt-get -y update RUN apt-get install -y --fix-missing \ build-essential \ cmake \ gfortran \ git \ wget \ curl \ graphicsmagick \ libgraphicsmagick1-dev \ libatlas-base-dev \ libavcodec-dev \ libavformat-dev \ libgtk2.0-dev \ libjpeg-dev \ liblapack-dev \ libswscale-dev \ pkg-config \ python3-dev \ python3-numpy \ software-properties-common \ zip \ && apt-get clean && rm -rf /tmp/* /var/tmp/* RUN cd ~ && \ mkdir -p dlib && \ git clone -b 'v19.9' --single-branch https://github.com/davisking/dlib.git dlib/ && \ cd dlib/ && \ python3 setup.py install --yes USE_AVX_INSTRUCTIONS RUN pip3 install --default-timeout=100 future RUN pip3 install -r requirements.txt COPY . . CMD python3 manage.py makemigrations face && python3 manage.py migrate && python3 manage.py runserver The browser also responding by the server didn't send data. Please help me. -
Django REST Framework Delete Method Request receives Forbidden 403
views.py class DeviceView(viewsets.ModelViewSet): serializer_class = DevicesSerializer queryset = Devices.objects.all() permission_classes = [permissions.IsAuthenticated] Axios Request axios.delete(`api/devices/${data.id}/`, {}, { headers: {'X-CSRFToken': csrftoken } }) .then((response) => { console.log(response); }).catch((error) => { console.log(error); }); When I carry out this request on my front-end, I get a response of :"DELETE http://localhost:3000/api/devices/4/ 403 (Forbidden)". Where 4 is the ID belonging to the record I would like to delete. I am currently using Session Authentication in Django and I have passed in my CSRF Token value into the header of my request. When I use other methods like PUT and POST on forms, they work fine. But, not DELETE What am I doing wrong to receive this error? -
Is there any good way to make string from list of dictionary in python? [duplicate]
I have an idea to convert from list of dictionary to string in python. for example: d_list = [{name:"a", age:26},{name:"b", age:22},{name:"c", age:20}] str_l = "[{ 'name':'a', 'age':'26'},{'name':'b', 'age':'22'},{'name':'c', 'age':'20'}]" like this. When input list of dictionary to db table, I need it. So for this, I have done like this. str_l= "[" for user in d_list: str_l += "{" for attr in user: str += "'" + attr + "':'" + user[attr] + "'," str_l = str_l[:-1] + "}," str_l = str_l[:-1] + "]" But it is not good. So if you have any good idea, please share for me. Thank you. -
How to make a Django application send money to its users using PayPal
I have a Django app for online cockfights. Users can bet if their accounts on the site have balance. They do that by first buying a digital product "Online Sabong Cash-In" through PayPal. The money is sent to the website's PayPal business account. I believe, this kind of transaction is called user-to-website transaction, and I've made this work using django-paypal library. I've followed this tutorial for that simple transaction: https://overiq.com/django-paypal-integration-with-django-paypal/ . Now, I want to give the website the feature where users can cash-out or like withdraw their money if they want. I want to have the website-to-user transaction. How can I do that, please? I've searched on Google a lot and all I see are articles for user-to-website transaction. I've found one way but I don't know how to do it using django-paypal library:https://developer.paypal.com/docs/checkout/integration-features/pay-another-account/. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte
I have a custom field below, recently upgraded from py 2.7 to 3.8. The encryption doesn't work anymore and fails with the error above. I have gone through all related posts still no solution, Any ideas? class EncryptedCharField(models.CharField): SALT_SIZE = 8 def __init__(self, *args, **kwargs): self.widget = forms.TextInput super(EncryptedCharField, self).__init__(*args, **kwargs) def get_internal_type(self): return 'TextField' def to_python(self, value): if not value: return None if isinstance(value, str): if value.startswith(PREFIX): return self.decrypt(value) else: return value else: raise ValidationError('Failed to encrypt %s.' % value) def from_db_value(self, value, expression, connection, context): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): return self.encrypt(value) def value_to_string(self, instance): encriptado = getattr(instance, self.name) return self.decrypt(encriptado) if encriptado else None @staticmethod def encrypt(plaintext): plaintext = str(plaintext) salt = urandom(EncryptedCharField.SALT_SIZE) #type bytes arc4 = ARC4.new(salt + settings.ENCRYPT_FIELD_KEY.encode()) plaintext = "%3d%s%s" % (len(plaintext), plaintext, b64encode(urandom(256-len(plaintext)))) return PREFIX + "%s$%s" % (b64encode(salt), b64encode(arc4.encrypt(plaintext.encode('utf-8-sig')))) @staticmethod def decrypt(ciphertext): salt, ciphertext = list(map(b64decode, ciphertext[1:].split('$'))) arc4 = ARC4.new(salt + settings.ENCRYPT_FIELD_KEY.encode()) plaintext = arc4.decrypt(ciphertext).decode('utf-8-sig') return plaintext[3:3+int(plaintext[:3].strip())] -
Reusable progress bar
I'm new in django and web applications. I'm trying to create a reusable progress bar template that will change links depending on section ID's on the current tab. index.html <section> {% include 'progress_navbar.html' %} </section> <section id="1"> <section> <section id="2"> <section> <section id="3"> <section> <section id="4"> <section> page2.html <section> {% include 'progress_navbar.html' %} </section> <section id="A"> <section> <section id="B"> <section> <section id="C"> <section> <section id="D"> <section> progress_bar.html <nav> <ul> <li> <a href="#var">1 or A</a> </li> <li> <a href="#var">2 or B</a> </li> <li> <a href="#var">3 or C</a> </li> <li> <a href="#var">4 or D</a> </li> (...) </ul> </nav> -
Why it seem that for Clour Run Default Service Account cannot be replaced?
I am currently deploying a Django application to GCP Cloud Run. I have replaced Cloud Run Default Service Account (....compute@developer.gserviceaccount.com) with a custom one. But I get an error message: AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. ... This bit is confusing me: <class 'google.auth.compute_engine.credentials.Credentials'> The error reported of the context of Django Storages which I use to store files. Is this message means the service account which is used by Cloud Run is still the default one (GOOGLE_APPLICATION_CREDENTIALS is set as Compute Engine)? Why not the Custom Service Account is used as an Identity for the Cloud Run? Why Cloud Run still checking the Default one I expected I replaced it with te Custome Service Account? I am a bit new with the IAM, but if somebody could explian why it is happeing would be appriciated. -
Django Query - Instances with single count
I have the following classes: class Company(Model): name = models.CharField(max_length=250) class Group(Model): name = models.CharField(max_length=250) company = models.ForeignKey('Company', on_delete=models.CASCADE) country = CountryField(default='US') There are instances where a company can have multiple groups in a single country. I want to fetch all the company groups that are just the only ones in their respective countries. Please help. Thanks -
Is it ok to calling save method multiple times in same method for django model object?
Say, there is a method creates an model object and adds values to model objects fields. def main_method(): obj, created = ModelA.objects.get_or_create(a="asd", b=1) Some imported data will be append to relevant fields: obj.c = "qwe" obj.d = 2 ... sub_method_1(obj) sub_method_2(obj) Also, there are 2 or more sub methods creates new model objects and link to primary object as foreign key. def sub_method_1(obj): obj_new, created = ModelB.objects.get_or_create(...) obj.e = new_obj obj.save() def sub_method_2(obj): obj_new, created = ModelC.objects.get_or_create(...) obj.f = new_obj obj.save() But than, when sub methods are done and return back to main method, there are also several save method calls available. def main_method(): .... obj.g = "ert" obj.h = 3 obj.save() Is this approach OK in practice, or there should be only one save at the end of the main method with returning new objects from sub methods and assign objects to foreign key fields before saving the main object? -
requests.get() returns an invalid JSON
I am using Django's rest_framework to create a simple API to be called from the front end. This API is supposed to be getting JSON data from openapi.etsy.com, and I am using 'requests' to achieve that. @api_view() @permission_classes((IsAuthenticated, )) def getListings(request): data = request.query_params if data.get('shopCode') == 'etsy': url = 'https://openapi.etsy.com/v2/listings/active' params = dict( keywords=data.get('keywords'), limit=data.get('pageSize'), page=data.get('page'), includes='Images:1', api_key='placeholderApiKey', ) response = requests.get(url=url, params=params) return Response(response) When I try this either by using Postman or from the browser by going to https://openapi.etsy.com/v2/listings/active?keywords=placeholder&limit=placeholder&page=placeholder&includes=Images:1&api_key=placeholder, it simply returns exactly what it's supposed to return: a valid JSON with all the data I need. But the Python function above does not. Instead, it returns something like this: ["{\"count\":45929,\"results\":[{\"listing_id\":979511780,\"state\":\"active\",\"user_id\":68094968,\"category_id\":null,\"title\":\"Pers... I'm not sure what exactly it is, it seems like an array containing a single string that contains the entire JSON but where every double quote has been escaped. Either way, it is definitely not a valid JSON. Reading the docs, it seems like I should be able to get exactly what the API returns by returning Response(response.text), but instead it just returns the thing above but without being inside an array. I thought to try Response(response.json()) as well, even though I'm not 100% sure how … -
Python Django Post Detail Class Based View
I am trying to create a DetailView for my Django blog, I have created one using function based views but to keep my code consistent I want to translate it to a class based view. The main issue I am having is that I am trying to integrate a comment form on the same page and I am unsure how I can do this in a class based view I will attach my code below # views.py @login_required def post_detail(request, slug): template_name = "cubs/post_detail.html" post = get_object_or_404(Post, slug=slug) articles = Article.objects.filter(status=1).order_by('-date_posted')[:2] comments = post.cubs_blog_comments.filter(active=True).order_by('-date_posted') new_comment = None # Comment posted if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, template_name, { "post": post, "articles": articles, "comments": comments, "new_comment": new_comment, "comment_form": comment_form, "title": 'Post Details', }, ) # models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='cubs_blog_comments') name = models.CharField(max_length=80) email = models.EmailField() comment = models.TextField() date_posted = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=False) class Meta: ordering = ['date_posted'] def get_absolute_url(self): return reverse("cubs_blog_post_detail", kwargs={"slug": str(self.slug)}) … -
How to auto-reload django admin page when some async jobs are making changes in the database?
In my django application, there are multiple async tasks running in the background and when those tasks make some db changes then I'm reloading the admin page manually to see the changes on the gui. How can I automate this feature to make the django admin page live? P.S.- I tried django-livereload-server but that will auto reload when any changes are made in the code. It doesn't take background tasks into consideration. -
Implementation of the interface for sending emails using object models
I am implementing sending emails using the Django object models. My main problem is to correctly describe the attachment model. class MIMEHeader(models.Model): name = models.CharField(_("Name"), max_length=256) value = models.CharField(_("Value"), max_length=256) parameters = models.JSONField(_("Parameters"), blank=True, null=True) def _get_upload_path(instance, filename): extension = filename.split(".")[-1] unique_filename = "%s.%s" % (uuid4().hex, extension) return join("attachments", unique_filename) class Attachment(models.Model): name = models.CharField( _("Name"), max_length=256, unique=True ) file = models.FileField( _("File"), upload_to=_get_upload_path ) headers = models.ManyToManyField( MIMEHeader, verbose_name=_("Headers"), blank=True ) class Meta: verbose_name = _("Attachment") verbose_name_plural = _("Attachments") def __str__(self): return self.name class EmailMessage(models.Model): attachments = models.ManyToManyField( Attachment, verbose_name=_("Attachments"), blank=True ) def _get_attachments(self): attachments = [] for container in self.attachments.all(): attachment_content = container.file.read() container.file.close() if container.headers: # Required header. Exception is OK. ctype = container.headers.get(name="Content-Type") mimetype, params = ctype.value, ctype.parameters maintype, subtype = mimetype.split("/") mime_part = MIMENonMultipart(maintype, subtype, **params) mime_part.set_payload(attachment_content) for header in container.headers.exclude(name="Content-Type"): parameters = header.parameters or {} mime_part.add_header(header.name, header.value, **parameters) attachments.append(mime_part) else: attachments.append((container.file.name, attachment_content)) return attachments Would it be convenient to use the MIMEHeader model? If yes, please advise what length restrictions i could apply to this model, because it seems to me that 256 is not the best option. Otherwise, please help find a solution to conveniently form an instance of a MIMEBase subclass with … -
Django: what is the best way to create models for students and tutors and both of them have different profiles?
I've done a lot of searching for this and even watched some tutorials, and most of them have different kinds of approach which makes me question myself if what I'm doing right now is correct. But I still tried to implement which I think is the best way base on what I learn in those tutorials, but I need some validation for this. This is what I did so far. class User(AbstractUser): is_student = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=11, blank=False, null=True) current_address = models.CharField(max_length=100, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' class TutorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=255, blank=True) def __str__(self): return f'{self.user.username} Profile' -
Django - python - more inner join manytomanyfields
Good morning, here are my models: class Events(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='events_user', on_delete=models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=140) slug = models.SlugField(max_length=200, unique=True, blank=True, null=True) description = models.TextField(blank=True, null=True) event_date = models.DateField(auto_now=False, auto_now_add=False) event_hours = models.TimeField(auto_now=False, auto_now_add=False) event_duration = models.DurationField(blank=True, null=True) location = models.CharField(max_length=100, blank=True) latitude = models.DecimalField(max_digits=999, decimal_places=12, blank=True, null=True) longitude = models.DecimalField(max_digits=999, decimal_places=12, blank=True, null=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="events_like", blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Tags(models.Model): events = models.ManyToManyField(Events, related_name='tags') name = models.CharField(max_length=100) if I make the query: Events.objects.filter(tags__id__in: [1, 2, 3, 4]) The result is: SELECT "events_events"."id", "events_events"."author_id", "events_events"."title", "events_events"."slug", "events_events"."description", "events_events"."event_date", "events_events"."event_hours", "events_events"."event_duration", "events_events"."location", "events_events"."latitude", "events_events"."longitude", "events_events"."created_at", "events_events"."updated_at" FROM "events_events" INNER JOIN "events_tags_events" ON ( "events_events"."id" = "events_tags_events"."events_id" ) WHERE "events_tags_events"."tags_id" IN ( 3, 4, 2, 1 ) but i whant have the second INNER JOIN which allows me to have the names of the tags so: SELECT "events_tags"."name", "events_events"."id", "events_events"."author_id", "events_events"."title", "events_events"."slug", "events_events"."description", "events_events"."event_date", "events_events"."event_hours", "events_events"."event_duration", "events_events"."location", "events_events"."latitude", "events_events"."longitude", "events_events"."created_at", "events_events"."updated_at" FROM "events_events" INNER JOIN "events_tags_events" ON ( "events_events"."id" = "events_tags_events"."events_id" ) INNER JOIN "events_tags" ON ( "events_tags"."id" = "events_tags_events"."tags_id" ) WHERE "events_tags_events"."tags_id" IN ( 3, 4, 2, 1 ) how can i get the above query into django? With the double INNER JOIN … -
Problem when save data in database with Django
I have a problem saving data. I receive the message as if they are saved successfully but they are not saved in the database ... This is the code I wrote APi VIEW class CreateApiView(APIView): def post(self, request): data_serializer = ProductsSerializer(data=self.request.POST) if data_serializer.is_valid(): data_serializer.save() return Response(data={'message': 'Succes'}, status=200) Serializer class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ('id', 'title', 'description') url urlpatterns = [ url(r'^api/test', views.CreateApiView.as_view(), name='post') ] I used exceptions to see what data I get from the keyboard and they are correct, what do you think is the problem? -
Format-dependent field representation in Django REST framework
In Django REST framework, I need to have different string representations of the value of a field depending on the selected display format (renderer). Looking at the arguments of the to_representation() and to_internal_values() methods for custom fields, it is not possible out of the box. Can this be done with standard DRF tools? -
Django - missing 1 required positional argument: '_id'
im getting an error BlogDetailView() missing 1 required positional argument: '_id' when im trying to access the function BlogDetailView. views.py : from django.http.response import Http404 from .models import BlogModel,CommentModel from .forms import SearchForm,CommentForm from django.shortcuts import render,redirect def BlogDetailView(request,_id): try: data = BlogModel.objects.get(id = _id) comments = CommentModel.objects.filter(blog = data) except BlogModel.DoesNotExist: raise Http404('Data does not exist') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Comment = CommentModel(your_name= form.cleaned_data['your_name'], comment_text=form.cleaned_data['comment_text'], blog=data) Comment.save() return redirect(f'/blog/{_id}') else: form = CommentForm() context = { 'data': data, 'form': form, 'comments': comments, } return render(request,'Test_one/detailview.html',context) urls.py : from django.conf.urls import url from django.urls.conf import path from blogapp.views import BlogDetailView, BlogListView from . import views app_name = "Blogapp" urlpatterns = [ url(r'^blogs/', views.BlogDetailView, name="blogs"), url(r'^blog/<int:_id>', views.BlogListView, name="blog"), ] Can anyone solve this problem? -
Summernote icons are not loading after upload static files to aws
I uploaded my static files to aws s3 buckets. font awesome css files are not loading. And also in admin page also loads fine.but icons in the summernote are not working in admin page. Picture of a admin page.Error in console is "The server respond with a status of 403 (Forbidden)" help in advance thanks , Dinindu.