Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
open source project with graphql django
I am learning graphql django and to learn better I have to see the real source of the real project with Django and graphql on github, but I can not find any. Can anyone help me find an open source project with graphql django -
ProgrammingError after reverting migration after AttributeError
I did the migration after adding SourceBook and SourceBooksOrderable and that worked. Then I managed to add two snippets in wagtail admin. But when I tried to add them into the BlogPage in admin, I got an AttributeError. Thinking that it was somehow a problem with the migration, I reverted migrations using python manage.py migrate blog 0001. Now I get a ProgrammingError under the snippet in admin. Tracebacks, models.py and migration files are below. How can I fix this? blog/models.py from django.db import models from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.core.models import Page, Orderable from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel from wagtail.images.blocks import ImageChooserBlock from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.models import register_snippet from wagtail.snippets.edit_handlers import SnippetChooserPanel richtext_features = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', "ol", "ul", "hr", "link", "document-link", "image", "embed", "code", "blockquote", "superscript", "subscript", "strikethrough", ] class BlogListingPage(Page): """Listing page lists all the Blog pages.""" template = "blog/blog_listing_page.html" subpage_types = ['blog.BlogPage'] custom_title = models.CharField( max_length=255, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context.""" context = … -
Django HttpOnly cookie doesn't protect but user can stop it if a malicious code didn't take an action yet. Am i right?
So in my understanding there are two ways of an XSS attack. Attacker user sends malicious Javascript code to backend and when another user opens it will have access to that users data. It is generally prevented with framework itself but you can also encode the data before sending to the backend and filter them before storing them into database in the backend side. When you open want to access it in the client side you decode it again. Browser extensions. Browser extensions have a all the access of client side. They cannot access HttpOnly cookies. But they can still send requests to backend, post something etc. If you use HttpOnly cookie once a user disables extension it will not have the control anymore. Am i right or is there another way of making an XSS attack? -
How to check the fields that are being update in a partial update DRF
I am developing a expense tracker, what I wanna do is to prevent users from updating the type of transaction what I have done so far is to check it with an if statement, but as it isn't pass into the request it generates an 500 error. My question id how can I preform a validation to check if the field is being pass into the request with out it giving an error when the filed isn't include into the request? -
How to make one column fixed and other is scrollable
Here I have tried to make one column is fixed and other is scrollable. In template "Os name" and "{{ i.os_name }}" I want to make it fixed and all the other should be scrollable I have tried but facing issues I have pasted the css which I have tried please tell me where I am going wrong so i can make it corret. <div> <table class="table accountTable" id="book-table" cellpadding="0" cellspacing="0" style="width: 91%;"> <thead> <tr class="accountBorder"> <th class="osfix">Os Name</th> <th class="">Browser</th> <th>IP Address</th> <th>Location</th> <th>Session Time</th> <th>Activity</th> </tr> </thead> <tbody> {% for i in account %} <tr> <td><div class="osfixName">{{ i.os_name }}</div></td> <td> <div class = "title_elipses accordion">{{ i.browser }}</div> <div class="panel" style="display: none;"><p>{{i.browser}}</p></div> </td> <td> <div>{{ i.ip_address }}</div> </td> <td> <div>{{ i.city }}, {{ i.country }}</div> </td> <td> {% for key,value in some_date.items %} {% if i.id == key %} <!-- here we are displaying the age of the ad --> <span class="dealpagetext">{{ value }}</span><br> {% endif %} {% endfor %} <!-- <div>{{ i.last_loggedin }}</div>--> </td> <td> {% if i.activity == 1 %} <div><a href="/Logoff_p/{{i.id}}">Signout</a></div> {% else %} <div></div> {% endif %} </td> </tr> {% empty %} <tr> <td colspan="7" class="text-center">No History</td> </tr> {% endfor %} </tbody> </table> </div> css … -
Securing Nginx autoindex within the scope of Django project
New to both Django and Nginx. I have a project with most of my views secured by the @login_requred() coroutine. How could I do the same with https://example.com/file-index which returns an Nginx autoindex? -
MariaDB: ALTER TABLE command works on one table, but not the other
I have two tables (Django Models) in a MariaDB database: coredb_vsatservicerate and coredb_simservicerate. MariaDB [servicedbtest]> desc `coredb_simservicerate`; +-----------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(80) | NO | | NULL | | | service_type | int(11) | YES | | NULL | | | category | int(11) | NO | | NULL | | | old | tinyint(1) | NO | | NULL | | | year | smallint(5) unsigned | YES | | NULL | | | reseller | tinyint(1) | YES | | NULL | | | description | longtext | NO | | NULL | | | description_update_ts | datetime(6) | YES | | NULL | | | currency | int(11) | YES | | NULL | | | price | decimal(7,2) | YES | | NULL | | +-----------------------+----------------------+------+-----+---------+----------------+ 11 rows in set (0.001 sec) And MariaDB [servicedbtest]> desc `coredb_vsatservicerate`; +-----------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(80) … -
The boolean field in form is not working in django
I'm using boolean in the form to filter the product. forms.py class BrandForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) brands = Product.objects.filter(category=1).values_list('brand', flat=True) for brand in brands: self.fields[f'{brand}'] = forms.BooleanField(label=f'{brand}', required=False) views.py product = Product.objects.all().order_by("-id") formBrand = BrandForm() return render( request, 'list/processor.html', {'formBrand': formBrand, 'product': product} ) index.html <form id="formBrand" action="{% url 'main:productdata' %}" method="get"> {{ formBrand.as_p }} <input type="submit" value="OK"> </form> What is wrong with the code. When I check the LG brand and hit the OK button. The product is not filtering. -
Django formsets in formsets
I am creating a quiz app. A quiz has one or more questions, each question has one or more images. I've already used django-dynamic-formsets to allow the user to create/delete multiple questions. However, I am struggling to find a method that allows the user to upload images for specific questions, and then for Django to recognise which images 'belong' to each question. Because a question could have multiple images (up to some unknown amount) I cannot just hard code multiple fields in my question model. My current code has a model for questions, and models for 'choices' which has a foreign key to a question model. -
How to Write a blog post with slug & image (django)
** when I clicked the publish button .get this error (image field = This field is required.). not submit the post in my database [1]: https://i.stack.imgur.com/Km5TH.png ** Models: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=300, verbose_name='Put a Title') slug = models.SlugField(max_length=264, unique=True, null=True) blog_content = models.TextField(verbose_name='What is on your mind') blog_image = models.ImageField(upload_to='blog_images', verbose_name='Image', null=True) publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title views: @login_required def createblog(request): form = CreateBlogPost() if request.method == 'POST': form = CreateBlogPost(request.POST, request.FILES) if form.is_valid(): blog_obj = form.save(commit=False) blog_obj.author = request.user title = blog_obj.blog_title print(title) blog_obj.slug = title.replace(" ", "-")+"-"+str(uuid.uuid4()) print(blog_obj.slug) blog_obj.save() return HttpResponseRedirect(reverse('index')) return render(request, 'App_Blog/create_blog.html', {'form': form}) -
How can I get distinct values for the area.names using graphene?
my resolver in schema.py looks like this def resolve_areas(self, info, **kwargs): result = [] dupfree = [] user = info.context.user areas = BoxModel.objects.filter(client=user, active=True).values_list('area_string', flat=True) In GraphiQL I am using this query: { areas { edges { node { id name } } } } And get Output that starts like this: { "data": { "areas": { "edges": [ { "node": { "id": "QXJlYTpkZWZ", "name": "default" } }, { "node": { "id": "QXJlYTptZXN", "name": "messe" } }, { "node": { "id": "QXJlYTptZXN", "name": "messe" } }, But i want distinct values on the name variable (Using a MySQL Database so distinct does not work) -
maximum recursion depth is exceeded error while calling a Python object in django while making a post request in Django?
I am trying to list all the doubtclasses model using doubtclass view but there is some recursion error in the post request, which i am not able to understand , i search across for same error and i have tried if i made a similar mistake to the other developers that have asked the same question but as far as i searched mine one is different My doubtclass view class DoubtClass(LoginRequiredMixin, mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = serializers.DoubtClass_serializer queryset = models.DoubtClasses.objects.filter(is_draft=False) def get(self, request): print("error in doubtclass get") return self.list(request) def post(self, request): if request.user.is_superuser: return self.post(request) else: return Response(status=status.HTTP_403_FORBIDDEN) my doubtclass model class DoubtClasses(models.Model): doubtClass_details = models.TextField() class_time = models.DateTimeField() end_time = models.DateTimeField() doubtsAddressed = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) mentor_id = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True) is_draft = models.BooleanField(default=True) class Meta: verbose_name_plural = 'DoubtClasses' def __str__(self): return self.doubtClass_details I am new to stackoverflow and django, so please forgive me if there is poor formatting of question or anything, always open for suggestions. Thanks in advance -
nginx + django + haystack = Server Error (500)
I've cobbled together a small blog application in Django using Haystack with Whoosh backend for search. It runs nicely in development server (on the laptop) but search fails when site runs in nginx on a server (rpi). I can access search page but any search results in Server Error (500), no additional info available from either nginx or django logs. I had RealtimeSignalProcessor on but turned it off - no change. Any pointer on how to attempt to debug this would be great. -
DoesNotExist at /delete/4/ Employee matching query does not exist
When I'm deleting from the Patient table I'm getting this error: DoesNotExist at /delete/4/ Employee matching query does not exist. views.py def delete_emp(request, pk): if request.method == 'POST': pi = Employee.objects.get(id=pk) pi.delete() return redirect('/employee') def delete_pat(request, pk): if request.method == 'POST': pi = Patient.objects.get(id=pk) pi.delete() return redirect('/patient') this is html page: <td> <form action="{% url 'home:delete_pat' p.id %}" method="post"> {% csrf_token %} <input type="submit" class="btn btn-primary btn-sm" value="Delete"> </form> </td> models.py class Patient(models.Model): name = models.CharField(max_length=200) phone=models.CharField(max_length=17,default='') age=models.IntegerField(default='') gender = models.CharField(max_length=20) doctor_name = models.CharField(max_length=200) def __str__(self): return self.name urls.py path('delete/<int:pk>/', views.delete_pat, name='delete_pat'), Please, can any one help me to get out from this, any help would be greatly appreciated. -
Django-Heroku app not saving data on JawsDB mysql (Long polling)
so I created a django project to imitate an asynchronous data stream using ajax and long polling. Everything works fine on the local server however it doesn't after I deployed it on heroku. There is still buttons to control LED (IoT) however there's no readings. The error said failed to load resource which i believed that it has smtg to do with database connection. I'm not using sqlite3, in fact i'm using mysql. I know that it's not possible to call a local database on heroku app so I'm using the jawsdb mysql add ons and i configured my settings.py according to the user, password and also host. I am able to connect to it using xampp however I can't see it auto saving data which it should be doing whenever my esp32 send a data to it. Would be great if someone could provide me some answers. I have a thoughts that could be the issue. The initial postgresql is the main database? I added the add ons and configured it on my django settings.py and pushed on heroku. However I'm not sure do i need to use heroku to sort of like set the mysql as my main … -
how can I pass the id of the item selected from the dropdown in django form action url?
Problem In this I want to pass the id from the transactions items from the dropdown to the form action URL cart_add. From the value selected in the dropdown, I have taken the id but now I don't know how to pass that id to the script and then to the form of adding to the cart. If someone knows please help. {% block main-content %} <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> $(document).on("change", '.Price', function (event) { event.preventDefault(); $('#id_price').text($(this).children(":selected").attr("price")); $('#id_sale_price').text($(this).children(":selected").attr("sale_price")); $('#transactionIDValue').val($(this).children(":selected").attr("transID")); }); </script> <div class="container my-5"> <div class="row"> <div class="col-sm-6 text-center align-self-center"> <img src={{product.product_image.url}} alt="" class="img-fluid img-thumbnail"> <span class="status">{{product.discount_percentage}} %</span> <div class="overlay"></div> </div> <div class="col-sm-5 offset-sm-1"> <h2>Product Title: {{product.name}}</h2> <hr> <p>Description: {{product.description}}</p> <br> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc" id='id_price'>Rs. </span><span class="price-sale" id='id_sale_price'>Rs. </span></p> </div> </div> <h4> <select class="Price" style="width: 250px;"> <option value="none" selected disabled hidden> Select an Option </option> {% for item in transaction %} <option transID={{item.id}} price={{item.Price}} sale_price={{item.get_sale}} >{{item.AUID.unit}} - {{item.Description}}</option> {% endfor %} </select> <!-- <small class="fw-light text-decoration-line-through">Rs. {{product.selling_price}} </small> --> </h4> <br> <form id='transactionIDValue' action="{% url 'cart:cart_add' %}" class="d-inline" method="post"> {{cart_product_form}} {% csrf_token %} <input type="submit" class="btn btn-primary shadow px-5 py-2" value="Add To Cart"> <!-- <button type="submit" class="btn btn-primary shadow px-5 py-2">Add to Cart</button> --> </form> <!-- … -
Django 500 Error page doesn't load CSS file
The 500 error handler template won't load CSS even if typed everything correctly. For example, my home template loads CSS properly using the same method Here's the 500.html template <html> <head> {%load static%} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>500</title> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"/> </head> <body> html code here </body> </html> This should load the style.css file from the static folder <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"/> In the terminal it looks like everything is OK, but it still doesn't load. "GET /static/style.css HTTP/1.1" 200 734 if I try to access 127.0.0.1:8000/static/main.css (the one for the homepage) it shows it how it should if I try to access 127.0.0.1:8000/static/style.css it gives me an error I don't know if it matters but I'm doing this with DEBUG = False -
Django does not let me pass empty fields
In my forms I have a table with the following columns: type = models.CharField(max_length=11, blank=False, null=False) name = models.CharField(max_length=50, blank=False, null=False) profile_image = models.ImageField(max_length=100, blank=True, null=True) terms = models.CharField(max_length=1000, blank=True, null=True) bio = models.CharField(max_length=1000, blank=True, null=True) but when I don't enter anything for bio, it gives me an error message with "[23000][1048] Column 'bio' cannot be null". Why is this? -
Force Download existing JSON file instead of displaying it with Django
My webpage has a functionality that lets users request fairly large json files (3MB+) to be generated. The generation process takes some time and I send them an email with a download link once it is ready. My problem is that clicking the download URL will open the content of the json file in the browser instead of starting a download dialog. I have found this question: Serving .json file to download but the solution reserialize the json file into the response: mixed_query = list(invoices) + list(pcustomers) json_str = serializers.serialize('json', mixed_query)) response = HttpResponse(json_str, content_type='application/json') response['Content-Disposition'] = 'attachment; filename=export.json' As the JSON file already exists, I do not want to rewrite it entirely within the response. I just want users to download the already generated file. How can I force the URL to start a download when reached? I am using Django 3.1, with Python 3.6 -
How to create custom session variable in Django 3.2?
I want create custom partner login on my website use only mobile phone number. Need your help friends. What is best practice in this question? -
Could not resolve URL for hyperlinked relationship using view name "user-detail"
I'm new to Django and trying to add to my User Authentication fields with a profile model. I'm using a HyperlinkedModelSerializer but when I go to my url - localhost:8000/api/user/, I get this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) hello = models.CharField(max_length=50, blank=True) def __str__(self): return self.user serializers.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Profile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') extra_kwargs = {'rooms': {'required': False}} class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['hello', 'user', 'user_id'] views.py from rest_framework import generics, viewsets from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, ProfileSerializer from .models import Profile class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class UserProfileAPI(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer urls.py (Project) from django.contrib import admin from django.urls import path, … -
Fields required although sent in the payload in Djnago Rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. But I got the following error. Although I am sending all the required data. I have a made a custom parser, but cant extract all the data. The data is sent like this My custom parser looks like this. class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # for case1 with nested serializers # parse each field with json for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value else: data[key] = value return parsers.DataAndFiles(data, result.files) Seems like the parser is not able to excract brand & collection id from the data, because there is a '' inside the id. Now I have to remove '' , and exctract only id.How to do this?? My view: class ProductAddAPIView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultipartJsonParser, JSONParser] def post(self,request,*args,**kwargs): data = request.data # print(data) serializer = AddProductSerializer(data=data) # print(serializer) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors) -
How to set up the random map Id generated by Folium Python
I am using folium to create a map and it generated me an html page. Inside this html I found a div with an id="map_6d1d4987e27f4fa1a16bc19423d0cdbe". The problem is the id is changing everytime the page is refreshed. <body> <div class="folium-map" id="map_6d1d4987e27f4fa1a16bc19423d0cdbe" ></div> <script type="text/javascript" src="scripts.js"></script> </body> How can I fixe it inside may python code? def create_map(): m = folium.Map(location=[9.934739, -84.087502], zoom_start=7 ) ..... -
unresolved import "home". How do I fix this? The views file and the urls file are int the same "home" folder
enter image description here unresolved import "home". How do I fix this? The views file and the urls file are int the same "home" folder. enter image description here -
Django templates - pass data outside for loop
I have a table of users and one table data is a button that opens up a modal, I am including the modal in the tamplate with the include tag. How do I pass the user from the row in which the button was clicked to the include tag? {% for user in users %} <tr> <td> <button class="btn btn-lg device-select-button"> <span>Select Device</span> </button> </td> </tr> {% endfor %} {% include 'app/admin/users/device_select_modal.html' user={{add here user}} %} In other implementation I have generated a modal for each row, and it works but slow, So I want to reimplement that