Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Drango template not loading Facebook iFrame in Firefox
I am trying to load a Facebook Newsfeed iFrame into a Django template using <iframe src="https://www.facebook.com/plugins/page.php?href={{ obj.facebook_address }}&tabs=timeline&width=500&height=750&small_header=true&adapt_container_width=true&hide_cover=true&show_facepile=true&appId=myappid" width="500" height="750" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe> This works when browsed with Chrome, but not Firefox or Edge. With Firefox and Edge I get a Facebook error message Your request couldn't be processed There was a problem with this request ... If I take the src from the iFrame (ie https://www.facebook.com/plugins/page.php?href={{ obj.facebook_address }} and post that as the url then I get the iFrame loaded into my Firefox browser so I think it is something to do with my site causing the issue (presumably the headers), but I cannot work out what it is. Of course, thinking it the headers could be a red herring. I can get the feed to show if I disable Enhanced Tracking Protection in Firefox, but I cannot believe other sites simply allowing this to slide so I think there must be a solution which doesn't depend on the user amending the settings I've spent 5 hours trying to work out the issue and I have got nowhere. Any help much appreciated -
Why does django-haystack run the object preparation multiple times?
I'm having this in my SearchIndex: class UserIndex(SearchIndex, Indexable): text = CharField(document=True, use_template=True) likes = IntegerField() def index_queryset(self, using=None): return self.get_model().objects.all() def get_model(self): return User def prepare_likes(self, obj): # Logging here just because it's the first "prepare" function. log.debug("Indexing %s: %d" % (obj.__class__.__name__, obj.pk)) return obj.get_all_likes() I have one object in my database. When I run update_index, the log.debug is printed 3 times for the object with pk 1. What am I doing wrong? -
Angular10 File Upload to django Server
I'm trying to upload a CSV file using Angular HTTP Client. But when i check the request.FILES in backend it shows <MultiValueDict: {}>. Apparently the file data is coming in request.body as byte string. Below is sample angular code for you reference. const upload_url = `${BASE_URL}/data-upload`; // Create form data instance const formData: FormData = new FormData(); formData.append('data_file', file, file.name); // Update header const headers = {'Content-Type': 'multipart/form-data'} this.http.post(upload_url, formData, {headers: headers}).subscribe(res => { console.log(res); }); How can i get the same file data in request.FILES? -
Django caching simple auth token
I have an app which uses Django DRF with simple AuthToken, Postgres for database and Redis for caching. I am trying to reduce the number of calls to my DB and one of most common action is SELECT on AuthToken table. In fact, it needs to be called for every request on a protected endpoint to verify the permission of the user. We could reduce the number of calls to our DB by caching the token of users in Redis as {user_id: token}. Assuming we set a decent expiration for the key and that we invalidate it in case of revoked token AuthToken, is caching the auth token an anti-pattern? Is there any security issue I should be concerned about? -
Django Admin. Giving permission to a user or a group and on save, I have 500 server error
If I try to assign the user to a group or assign permission to a group or a user, I have 500 server error fault. I have the following models.py, it's in: /home/e/sc_project/sc It's autogenerated, it tells me the following message for every table in the database: This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'auth_group' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ # Unable to inspect table 'auth_group_permissions' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ and so on... That's because I have 9.2 PostgreSQL database(?)... Can it give me … -
Add additional keyword argument when overriding __init__ for Form
I want to create a form and overriding the __init___ as following: class ModifierForm(forms.Form): dummy = forms.BooleanField(required=False, widget=forms.HiddenInput()) def __init__(self, modifiers, *args, **kwargs): super().__init__(*args, **kwargs) if len(modifiers) > 0: if 'applies' in kwargs: applies = kwargs.get("applies") for modifier, applied in zip(modifiers, applies): self.fields[modifier] = forms.BooleanField(required=False, default=applied) else: for modifier in modifiers: self.fields[modifier] = forms.BooleanField(required=False) Here, I pass a mandatory list modifiers. I also want to pass an optional list applies so as to set the initial default values to the fields. But when I call this form as below, I get this error __init__() got an unexpected keyword argument 'applies' modifier_change_form = ModifierForm(modifiers=modifiers, applies='applies') But it works fine if I just call as following, without applies: modifier_change_form = ModifierForm(modifiers=modifiers) I suspect that the **kwargs is from the base Form class only. How do I insert additional but optional **kwarg argument in __init__? Thanks. -
Map User and Board in Django
I'm trying to build Reddit in Django and for that, I am creating a board where users can discuss topics. But I am not able to map user and board. Model: class Board(models.Model): id = models.AutoField(primary_key=True) unique_id = models.CharField(max_length=100, null=False, unique=True) created_by = models.ForeignKey(User_Detail, on_delete=models.CASCADE, related_name="board_creator") name = models.CharField(max_length=100, null=False, unique= True) class UserBoardMapping(models.Model): user = models.ManyToManyField(User_Detail) board = models.ManyToManyField(Board) user_type = models.CharField(max_length=10, choices=USER_TYPE, default='moderator') My view: class CreateBoard(APIView): def post(self, request): data = JSONParser().parse(request) unique_id = data.get('board_id', None) created_by = data.get('created_by', None) name = data.get('name', None) if not created_by or not name: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) if Board.objects.filter(name=name).exists(): return JsonResponse({'ERROR': "Board Already registered! "}, status=status.HTTP_409_CONFLICT) if not User_Detail.objects.filter(username=created_by).exists(): return JsonResponse({'ERROR': "Username is not registered! "}, status=status.HTTP_404_NOT_FOUND) username = User_Detail.objects.get(username=created_by) board = Board(unique_id=unique_id, created_by=username, name=name) board.save() user_board_mapping = UserBoardMapping(user=username, board=board) user_board_mapping.save() UserBoardMapping is not working, how can I map user and board. what am I doing wrong here in this code ? -
Is running makemessages necessary every time?
I'm reading the django documentation for makemessages but the wording is not very clear: Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the Django tree) or locale (for project and application) directory. After making changes to the messages files you need to compile them with compilemessages for use with the builtin gettext support. In the text above it doesn't seem clear to me what it means that makemessages would "pull out" strings marked for translation. (pull them out for what? where to?) Meanwhile the compilemessages description makes sense as this simply compiles the messages once I've changed the language files. When, if ever, should I use makemessages if compilemessages does the job I am seeking? What is the point of makemessages? -
how can i display the properties of my models that are stored in the QuerySet object?
My django app has a simple model, i created 3 instances, each has title and description properties, how can i use these properties to display in html template? models.py: from django.db import models class Solution(models.Model): title = models.CharField(max_length=200, help_text='Enter a title of solution') description = models.TextField(max_length=1000, help_text='Enter a description of solution',) def __str__(self): return self.title views.py: from django.shortcuts import render from .models import Solution from django.views import generic def index(request): solutions = Solution.objects.all() return render(request, "main/index.html", {'solutions': solutions}) I need to do something like this in a file html: <div class="content"> <h3>{{ solution.title }}</h3> -
Django: Format raw HTML to actual HTML (RichText)
I'm using Django to build a site and one of my models has a RichTextField (using ckeditor) So in my HTML template I use: {{ mymodel.richtextcontent }} But then my page displays the rich text field's tags like <p> or <em> for example. How do I make it considered normal HTML ? -
How to create a new object in Saleor Commerce?
Could somebody guide me how to add a new object to the projects? For example, Banner. Dashboard should be able to create, edit, delete banners. The banners will then be display on the storefront. I'm new to Python/Django. I watch a tutorial and find out that I may need to create an app so I do: python manage.py startapp banner but it always show the error: No module named 'module names' . After I install one it shows another. I've already run docker-compose build before, and I think it should already install everything. Thanks for your support :) -
If statement in Django not displaying the output
I want to display a delete button alongside comments that the request.user has written so that only they can remove them, but for some reason can't get my if statement to work. Here is my template: {% for post in posts %} ... {% if post.comment_set.all %} {% for comment in post.comment_set.all %} <img src="{{ comment.user.image }}"> <p>{{ comment.body }}</p> {% if comment.user == request.user %} # delete icon with modal {% endif %} {% endfor %} {% endif %} {% endfor %} It is the if comment.user == request.user tag which is not working. I have tried outputting both comment.user and request.user in <p> tags and both display the way I would expect, so can't understand why it doesn't work. I have also tested the delete button which does display correctly when the if statement is removed. Here are my relevant models for reference: class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() class Post(models.Model): content = models.TextField() author = models.ForeignKey(Profile, on_delete=models.CASCADE) image= models.ImageField(blank=True, null=True, default='profile_pics/default.png', upload_to='profile_pics') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Strangely, further up the page I have used similar code to display delete beside the blog posts themselves, using {% if post.author.user … -
HttpResponseRedirect in Django is not redirecting to the page views.py file
My views.py looks like: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from django import forms from . import util import markdown2 def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def search(request): if request.POST["q"] in util.list_entries(): return HttpResponseRedirect(reverse("entry", args=(request.POST["q"],))) else: return render(request, "encyclopedia/error.html") Here my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="entry"), path("search", views.search, name="search") ] Next comes my layout.html template which other pages extend from this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> … -
Data doesn't change after sending PUT method
I'm doing some basic CRUD application with python django. Basicly, from the Front End, I want to send some raw text data, the Backend will catch It, and re-send the cleaned ones. For now, the clean method worked but for some reason, It still sending the same raw text to the Front End. This is my code: in models.py: class Post(models.Model): content = models.TextField(max_length=3000, blank=False, default='') in serializers.py: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'content') in views.py: @api_view(['PUT']) def create_post(request): if request.method == 'PUT': post_data = JSONParser().parse(request) post_serializer = PostSerializer(data = post_data) if post_serializer.is_valid(): data_to_clean= str(post_serializer.data['content']) # this is raw text (i.e: "aBcD") cleaned = clean(data_to_clean) # this is text after cleaning (i.e: "abcd") post_serializer.data['content'] = cleaned # update the new text return JsonResponse(post_serializer.data, status = status.HTTP_200_OK) return JsonResponse(post_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can you point out what is wrong with this code. Many thanks. -
How can i pick only the first row of each hour in a db using django orm
I want to fetch only the first row of each hour in a db using django orm any suggetsions ? summary_exists = xx_table.objects.all().filter( summary_date__range=(date_from, date_to) -
Unable to import PyPDF2 module
I am using VScode text editor, and I'm trying to import PyPF2 module which I have already installed in my Django virtual environment. (project) C:\Users\Bhargava\django-apps\mysite>pip install PyPDF2 Requirement already satisfied: PyPDF2 in c:\users\bhargava\envs\project\lib\site-packages (1.26.0) But I'm still getting the following errors. error: Import "PyPDF2" could not be resolvedPylance (reportMissingImports) [Running] python -u "c:\Users\Bhargava\django-apps\mysite\home\mcq.py" Traceback (most recent call last): File "c:\Users\Bhargava\django-apps\mysite\home\mcq.py", line 1, in <module> import PyPDF2 ModuleNotFoundError: No module named 'PyPDF2' [Done] exited with code=1 in 1.337 seconds I've tried adding every path to system environment variables, but nothing worked. Can anyone help me out? Thank you. -
Which field can be used in django serializers for entering ipaddress with subnet mask
Which field can be used in django serializers for entering ipaddress with subnet mask. example: x.x.x.x\x is the input format. -
How to show a list instead of choose from choicelist in django
Here is an invoice. In this case, it shows lines of products and user can select products on each line from dropdown list. My need is to show all products, each line with one product which i can fill with details as price and quantity as example bellow. Models: class Invoice(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) number = models.CharField(max_length=64, unique=True, default=invoice_number) date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) forms: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = "__all__" class InvoiceItemForm(ModelForm): class Meta: model = InvoiceItem fields = "__all__" InvoiceItemFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=3, can_delete=False) View : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = InvoiceForm(company_instance) formset = InvoiceItemFormSet(form_kwargs={"company":company_instance}) products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = InvoiceForm(company_instance, self.request.POST) formset = InvoiceItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: … -
(Django) webp Image url Cant open in new tab, that force me to download before opened
(Django) Anyone can open webp image in new tab?, I have a problem with webp when I open webp image in new tab I always forced to download that image and then that image can opened as File in Web Browser. I mean just like png or jpg when I open in new tab, that just show me Image in new tab as url not to force download that image. Any suggestion? Example Url: http://127.0.0.1:8001/media/image.webp -
Why isn't my POST Webhook working in Django?
I use the app Salesmate and am trying to write a a client on my site that adds features through the API. For this to work I need Salesmate's Webhooks. My client is in Django. When I send a GET request webhook it makes it into my client. When I send a POST request webhook it never makes it into the view. When I send a test POST request from https://reqbin.com/ it makes it into the view and performs as expected. I've played endlessly with the JSON body and headers. There could still be something I'm missing here, or there could be a flag raised in Django invalidating the sender, or something else... Here is Salesmate webhook request, in the app. I've played with many headers, and sent requests with and without JSON bodies. Request details 1 Request details 2 Here is my django view. Super simple, but it never gets called. from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def pab(request): #Do something simple and trackable return HttpResponse(keep) -
How to serialize and de-serialize data in single field to a nested serializer Django Rest Framework?
Considering I have this model: class AddressLocation(models.Model): streetaddress = models.CharField(max_length=255, blank=True) xcoordinate = models.FloatField(null=False, blank=False) ycoordinate = models.FloatField(null=False, blank=False) created = models.DateTimeField(null=False, blank=False) And these serializers: class AddressSerializer(serializers.Serializer): streetAddress = serializers.CharField(label="Street Address", required=True) postalCode = serializers.CharField(label="Postal Code") city = serializers.CharField(label="City") country = serializers.CharField(label="Country") class AddressLocationSerializer(serializers.ModelSerializer): address = AddressSerializer() xcoordinate = serializers.FloatField(null=False, blank=False) ycoordinate = serializers.FloatField(null=False, blank=False) class Meta: model = AddressLocation fields = [ 'id', 'address', 'xcoordinate', 'ycoordinate', 'created' ] How can I serialize and de-serialize the values for "address" since the values of it's fields will be stored on a single field "streetaddress" on the model? For more info my data format for my request and response should look like this: Request: Method: POST data: { 'address':{ 'streetAddress': "Sample Street Name", 'postalCode': "9999" 'city': "City" 'country': "Country" }, 'xcoordinate': '<x coordinate value>, 'ycoordinate': '<y coordinate value> } Response: data: { 'id': <record_id> 'address':{ 'streetAddress': "Sample Street Name", 'postalCode': "9999" 'city': "City" 'country': "Country" }, 'xcoordinate': <x coordinate value>, 'ycoordinate': <y coordinate value>, 'created': <date_created> } I am fairly new to DRF so I am not sure if this is achievable. -
Having a form and some plots on the same page with django?
I'm trying to learn use Bokeh and django to visualize some data, and I'm on a windows 10 laptop doing this project using VS code and Anaconda in a virtual environment, if this is relevant. My goal is that the user shall be able to input a number into a field, hit submit, and the bokeh graph shall update. This means, if I understand it correctly that both bokeh graph and django form must lie under the same view-function in my views.py-script. I have successfully created the graph, and am hitting difficulties with the form. I think it stems from me not properly understanding the POST vs GET requests. Following a tutorial(https://www.youtube.com/watch?v=3XOS_UpJirU) I tested out the form feature by creating a forms.py with a very basic input form: from django import forms class InputForm(forms.Form): scalar=forms.IntegerField(label="A number: ") Then I created a basic "formtest.html" file just to display the form. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </form> </body> </html> And in views.py I added: def formtest(request): #This form was built to test that a value can be submitted and passed to the backend if request.method=="POST": form=InputForm(request.POST) if form.is_valid(): scalar=form.cleaned_data['scalar'] print("This is … -
How to navigate to home page? - python django
I have created an Index page using HTML and have given an URL for "Home" button, In a way that when the home button is clicked the page navigates from Index page to home page. But it doesn't navigate to home page, when clicked in URL address the address changes to the specified location correctly but the page displayed is still the Index page. <div class="top-menu"> <div class="container"> <div class="row"> <div class="col-xs-2"> <div id="fh5co-logo"><a href="{% url 'index' %}">TrainedbySamson<span>.</span></a></div> </div> <div class="col-xs-10 text-right menu-1"> <ul> <li class="active"><a href="{% url 'tbs_home:home' %}">Home</a></li> <li><a href="{% static 'gallery.html' %}">Gallery</a></li> <li><a href="{% static 'about.html' %}">Trainer</a></li> <li><a href="{% static 'pricing.html' %}">Pricing</a></li> <li class="has-dropdown"> <a href="{% static 'blog.html' %}">Blog</a> tbs_home/urls.py: urlpatterns = [ path('home',views.home, name='home'), ] tbs_home/views.py: def home(request): return render(request, 'home.html') templates/home.html: {% load static %} {% block content%} <h1 style = "font-family:Georgia;font:40px;font-style:normal;">Hi! {{name}}</h1> <form action="add" method="POST"> {% csrf_token %} Enter 1st num : <input type="text" name="num1"><br> Enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} So when I click the home button according to the code the page should navigate to home.html page?. But it stays in the same Index page, thanks in advance. -
Django queryset with complex annotation
I have a User queryset along with 3 relations: class Review(models.Model): user = models.ForeignKey(settings.USER_MODEL) class ReviewTask(models.Model): review = models.ForeignKey("Review") competency = models.ForeignKey("Competency") class Competency(models.Model): name = models.CharField(max_length=50) I'm trying to annotate this queryset with a string that contains an ordered set of competency names associated with a user. For example, i I wanted to add this as a method on the User model, it would be as simple as: class User(...): def competency_names(self): names = set() for rt in ReviewTask.objects.filter(review__user=self): names.add(rt.competency.name) return ",".join(sorted(set(names))) The annotation examples I've looked at all seem far simpler than what I'm trying to accomplish. Is it feasible or no? -
{detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter." in angular 10 and drf
I want to upload image but unable to upload when I test api in postman is doesn't gave any error but when I post data from angular and post data in json format it raised error {detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter." in angular 10 and drf} When I post data from formData it raised error "rc_proof": [ "The submitted data was not a file. Check the encoding type on the form." ]" I am not getting whats going wrong here. I search a lot but not getting the expected result in my project Thank You in Advance ------------:) views.py class AgencyCarViewSet(viewsets.ModelViewSet): permission_classes = (AllowAny,) serializer_class = AgecyCarSerializer def get_queryset(self): return AgencyCar.objects.all() parser_classes = [MultiPartParser, FileUploadParser] serializers.py class AgecyCarSerializer(serializers.ModelSerializer): class Meta: model = AgencyCar fields = "__all__ component.ts onSubmitForm() { if (this.agencyCarForm.valid){ let data = { user : 1, brand: this.agencyCarForm.value.brand, carname: this.agencyCarForm.value.carname, car_model: this.agencyCarForm.value.carmodel, rc_proof: this.agencyCarForm.value.rc_proof, manufacture_year: this.agencyCarForm.value.manufacture_year, } const formData = new FormData(); formData.append("brand", this.agencyCarForm.value.brand); formData.append("carname", this.agencyCarForm.value.carname); formData.append("car_model", this.agencyCarForm.value.carmodel); formData.append("rc_proof", this.agencyCarForm.get('rc_proof').value); formData.append("manufacture_year", this.agencyCarForm.value.manufacture_year); formData.append("user", "1"); console.log(formData); this.service.postCars(data).subscribe((data: any) => { console.log(data); this.router.navigate(['/account']); },(error:any)=>{ console.log(error) }) } } componet.html <form [formGroup]="agencyCarForm" (ngSubmit)="onSubmitForm(agencyCarForm.value)"> <mat-form-field appearance="outline" class="w-100" > <mat-label>Brand</mat-label> <mat-select formControlName="brand" required (ngModelChange)="getCarName($event)"> <mat-option value="">Select …