Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /notes/create/ Reverse for 'notes_list' with no arguments not found. 1 pattern(s) tried: ['notes/list/(?P<username>[^/]+)$']
I don't know how can i add link of user notes list in side bar. the error is coming in the given following lines of template pages/base_stuff/side_bar.html <li class="active treeview"> <a href="{%url 'notes:notes_list' notes.author.username %}"> <i class="fa fa-dashboard"></i> <span style='font-weight: normal;'>Your Notes</span> </a> </li> notes/urls.py app_name = 'notes' urlpatterns = [ path('list/<str:username>',views.NotesListView.as_view(),name='notes_list'), ] notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' # paginate_by = def get_queryset(self): user = get_object_or_404(auth.models.User, username=self.kwargs.get('username')) return Notes.objects.filter(author=user).order_by('-create_date') -
How to add multiple images to a model?
Wagtail My model code: class HomePage(Page): images = models.ImagesField(max_count = 20) // How to do it right? content_panels = Page.content_panels + [ ImagesChooserPanel('images'), ] How it should look Please help! -
Django external API requests (question mark / ampersand)
I'm trying to get the result of an APi. The thing is I don't really know how to make it like that: https://api.spoonacular.com/food/images/analyze?apiKey=MY_KEY&imageUrl=IMAGE_URL. When I do it manually everything works. apiKey works with ? imageUrl works with & Assume I got a Post model and inside of this model I got a field url_image. if self.url_image: url = "https://api.spoonacular.com/food/images/analyze" querystring = {"imageUrl":self.url_image} headers = { 'apiKey': "MY_KEY" } result = requests.request("GET", url, headers=headers, params=querystring) if result and len(result): self.fat = result[0]['fat']['value'] self.proteines = result[0]['protein']['value'] self.glucides = result[0]['carbs']['value'] super().save(*args, **kwargs) The thing is with this code I can not access to it because the order is not good. Do you have any similar post you can advice me to read in order to understand how I can make API_KEY as ? and imageURL as & -
OSError: [Errno 9] Bad file descriptor in oauth2client on Ubuntu 20.04
This code below runs fine on my macOS 10.15.6. However, when I deployed the code on an Ubuntu 20.04-server I'm getting OSError: [Errno 9] Bad file descriptor class Command(BaseCommand): def handle(self, *args, **options): credentials = ServiceAccountCredentials.from_json_keyfile_name( self.get_json_file_path(), ['https://www.googleapis.com/auth/analytics.readonly']) self.http_auth = credentials.authorize(Http()) service = build('analytics', 'v3', http=self.http_auth) print(service) def get_json_file_path(self): return settings.BASE_DIR + "/onf/" + "google_client_secrets.json" I'm running the same python versions on macOS and the Ubuntu server: macOS 10.15.6 Python 3.8.2 (default, Aug 25 2020, 09:23:57) [Clang 12.0.0 (clang-1200.0.32.2)] on darwin Ubuntu 20.03 Python 3.8.2 (default, Aug 25 2020, 09:23:57) [Clang 12.0.0 (clang-1200.0.32.2)] on darwin Any ideas on what's going wrong here? -
Django Rest Framework: How to render data from database with specific object id
I'm building a project in Django Rest Framework where users get to see the list of shoes or the detail of the shoe. When I enter the url to list all the shoe it display correctly, when I enter the url with the id of the object, the HTML displays nothing. Here is my model class shoes_brand(models.Model): brand = models.CharField(max_length=15) class Meta: db_table = 'Brand' verbose_name='Brand' verbose_name_plural = 'Brands' def __str__(self): return self.brand class shoe(models.Model): name = models.CharField(max_length=15) foot_size = models.DecimalField(max_digits=3, decimal_places=1) price = models.DecimalField(max_digits=4, decimal_places=2) quanity = models.DecimalField(max_digits=3, decimal_places=0) available = models.BooleanField(default=False) brand = models.ManyToManyField(shoes_brand) def __str__(self): return self.name My view from .models import shoe, shoes_brand from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Response from rest_framework.views import APIView class list_object(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'rest/list.html' def get(self, request): queryset = shoe.objects.all() context = { 'object' : queryset } print(context) return Response(context) class detail_object(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'rest/detail.html' def get(self, request ,pk): queryset = shoe.objects.get(pk=pk) context = { 'object' : queryset } print(context) return Response(context) My url from django.urls import path from .views import list_object, detail_object app_name = 'shoes_app' urlpatterns = [ path('list/', list_object.as_view(), name="List_all"), path('detail/<int:pk>/', detail_object.as_view(), name="Detail_object"), ] My serializer class ShoeSerializer(serializers.ModelSerializer): class Meta: model = … -
Why we use dj_rest_framework on Django ? Sorry is that flop question . Please help me to understand this
I can use serializers.py and permission.py from the rest. However, I don't get it about rest. Many forms show me about dj_rest_framework used for API. -
how to use custom fonts in django-ckeditor?
first time i am using ckeditor in django project. i want to use custom font family in django-ckedtor. i have spent lots of time to about that but it's not working. if anybody know about using custom font in django-ckeditor. please tell me? settings.py CKEDITOR_CONFIGS = { 'default': { 'contentsCss': ["body {font-size: 18px;}", '{% static "desk/fonts/Nafees-Nastaleeq/css/font.css/"'], 'font_formats': 'Nafees Nastaleeq; Andale Mono = andale mono, times Arial Black = arial black, Comic Sans MS = comic sans ms, sans-serif', 'width': 'auto', 'toolbar': [ ['Bold', 'Italic', 'Underline'], ['Font', 'FontSize', 'TextColor', 'BGColor'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] ], } } -
AJAX is not passing hard-coded data
In index.js I have: $("#weather_form").on("submit", function(event){ event.preventDefault(); $.ajax({ url: "/weather/", type: "POST", data: {type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"}, dataType: "json", contentType: "json", success: function (data){ alert("success"); }, error: function(xhr,errmsg,err) { alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText); } }); }); I'm getting the following error: So we know it's going into the error function of the AJAX call because of the popup. But why? I specifically hard-coded the JSON values to pass. Things I've tried, but to no avail: data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"}) -
Django and amazon aws s3 bucket, static and media, how to setup correctly?
i am configuring aws s3 for my django project, i have seen various tutorials but i am not sure if i configured it properly. Some infos that might be useful: My IAM user is in a group with a AmazonS3FullAccess policy; I enable public access to my bucket; I updated the bucket CORS configuration according to this heroku tutorial. <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> policy bucket: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my_bucket/*" } ] } these are my configurations. are safe or need to do some further configuration? Thank you very much! -
POST data using XMLHttpRequest
I've the following endpoint in django that I send data to, in order to be saved to disk: if request.method == 'POST': fout = open('leak.txt', 'a') leak = request.POST['leak'] fout.write(leak) fout.close() return HttpResponse('<h1>ok</h1>') return HttpResponse('<h1>Post data here</h1>') Then I send the following sample data (which includes character like { } ;) to it: var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://127.0.0.1:8000/leak/", true); xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhttp.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE && this.status >= 200) { console.log(this.responseText) } }; let str = "leak=function(){ eval(1+2); var x = 3;}" //data sent xhttp.send(str); But only "function(){ eval(1 2)" is saved at the endpoint. How should I format the string in java-script before sending in order to receive everything properly? -
search a calculated field django?
So i have a secret in code and use sha256 encode it in logs. so i need to search this in admin i have tried annotation but it does not work so i want to add a calculated field so i don't keep redundant data is but property decorated functions in django cannot be searched in admin. Is there any other ways to do this? this is the annotation way: def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset |= self.model.objects.annotate(sha256_search=sha256_hash("key")).filter(sha256_search__contains=search_term) return queryset, use_distinct and i get the error: TypeError: QuerySet.annotate() received non-expression(s): 2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683. this is the property field witch i cannot add to the: @property def sha256_key(self): return sha256_hash(self.key) -
Django error ''Page not found (404)'' even objects exists in database
Well i am getting 404 error even my user exist in database i tried to solve this but i couldn't can you guys help me. I really need help. notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' # paginate_by = def get_queryset(self): user = get_object_or_404(auth.models.User, username=self.kwargs.get('username')) return Notes.objects.filter(author=user).order_by('-create_date') if i comment out the user line and in return line i replace user variable with user primary key than it shows all notes related to that user. But obviously i can't use same primary key in views or every user so i need to grab specific user and show him its notes list. and I am unable to do this. I need little help can you guys help me.? -
Django Stateless API
I am trying to understand the excat meaning of stateless and found this in Google and I have a small doubt. I have a Django API which fetches some data from PostgreSQL database and returns the same. How is this API stateless, as it is relying on external database? -
Deploy Django projec via Git to Azure Web App failed (Linux)
I developed a simple Django app, it was pushed to git. When I deployed to Azure Web App, it failed with the following. I tried to research the zip issue. There aren't much information. Can someone help? I have put ALLOWED_HOSTS = ['*'] in setting.py. The app is running at localhost fine. I tried many deploy many times, and also retried by creating new web app. Still the same issue. My python is 3.8 Deployment Failed with Error: Error: Failed to deploy web package to App Service. Error: Request timeout: /api/zipdeploy?isAsync=true&deployer=GITHUB_ZIP_DEPLOY -
error with slug in django - template it show all posts data in each post
error with slug in django - template it show all posts data in each post when i create new post and write my data it's show all data from other posts why is that ? and how i can fix it ? also how i can add auto generation slug ? models.py : from django.urls import reverse from django.utils.text import slugify class Android(models.Model): title = models.CharField(max_length=50,default="",help_text="this is title for slug not post!") name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) post_tag = models.CharField(max_length=50,default="",choices = BLOG_SECTION_CHOICES) slug = models.SlugField(null=True,uniqe=True) # new def get_absolute_url(self): return reverse('android_posts', kwargs={'slug': self.slug}) # new def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def android_posts(request,slug): android_posts = Android.objects.all() context = {'android_posts':android_posts} return render(request,'android/android_problems_fix.html', { 'android_posts': android_posts }) html page : {% for android in android_posts %} <h1 id="font_control_for_header_in_all_pages">{{android.name}}</h1> <hr> <p id="font_control_for_all_pages">{{android.app_contect}}</p> {% endfor %} -
Django, boardcast of HttpResponseRedirect
I create a web site on django and get errors. I have need broadcast response on view of method. Params may not exist. Help please. Code with views method where need get response: def blog_once(request, post_id): try: post = Blog.objects.get(id=post_id) except: raise Http404('Статья не найдена :(') comments = post.comment_set.order_by('-pub_date') count = post.comment_set.count() return render(request, 'blog/details.html', {'post': post, 'comments': comments, 'count': count, 'GOOGLE_RECAPTCHA_SITE_KEY': settings.GOOGLE_RECAPTCHA_SITE_KEY}) Code with HttpResponseRedirect: def leave_comment(request, post_id): try: post = Blog.objects.get(id=post_id) except: raise Http404('Статья не найдена :(') if request.POST['author'] != '' and request.POST['text'] != '': response = 'Ваш комментарий добавлен!' if request.FILES: post.comment_set.create(author=pymysql.escape_string(request.POST['author']), image=request.FILES['image'], text=pymysql.escape_string(request.POST['text'])) else: post.comment_set.create(author=pymysql.escape_string(request.POST['author']), text=pymysql.escape_string(request.POST['text'])) else: response = 'Вы не заполнили имя или текст сообщения!' return HttpResponseRedirect(reverse('blog_once', args=(post.id,))) -
ValueError: Field 'id' expected a number but got 'index.html'
I am trying to create a simple to-do list app using Django. But face this error will running the server ValueError: Field 'id' expected a number but got 'index.html'. models.py from django.db import models class List(models.Model): item = models.CharField(max_length=200) completed = models.BooleanField(default=False) def __str__(self): return self.item + '|' + str(self.completed) urls.py from . import views urlpatterns = [ path("index",views.index, name="home"), path("delete/<list_id>/", views.delete , name="delete"), ] views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages # Create your views here. def index(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request,('Items has been Added to List !!')) return render(request,'home.html', {'all_items': all_items}) else: all_items = List.objects.all return render(request,'index.html',{'all_items': all_items}) def delete(request, list_id): item = List.objects.get(pk=list_id) item.delete() messages.success(request,('Item has been deleted')) return redirect('index') index.html {% extends 'home.html' %} {% block content %} {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> {{ message }} </div> {% endfor %} {% endif %} {% if all_items %} <table class="table table-bordered"> {% for things in all_items %} <tr> <td>{{ things.item }}</td> <td><center>{{ things.completed }}</center></td> <td><center><a … -
Plotly slider missing when plotted on a webpage
I have plotted a choropleth map with a slider using Ploty. The slider and the choropleth both appears fine when I plot it on a Jupyter notebook or on Colab notebook but when I used the same plot to display on a webpage using Plotly Dash the slider disappears from the plot and only the choropleth map is shown. Below Code is when plotted on Jupyter Notebook data_slider = [] for month in world_df['Date'].unique(): df_month = world_df[world_df['Date'] == month] for col in df_month.columns: df_month[col] = df_month[col].astype(str) data_one_month = dict( type='choropleth', locations = df_month['Country'], z=df_month['Confirmed'].astype(float), locationmode='country names', colorscale = "purples", ) data_slider.append(data_one_month) steps = [] for i in range(1,int(len(data_slider))): step = dict(method='restyle', args=['visible', [False] * len(data_slider)], label='Day {}'.format(i) ) step['args'][1][i] = True steps.append(step) sliders = [dict(active=0, pad={"t": 1}, steps=steps)] layout = dict(geo=dict(scope='world', showcountries = True, projection={'type': 'equirectangular'}, ), sliders= sliders ) fig = dict(data=data_slider, layout=layout) iplot(fig, show_link = True) Plot output when plotted on Jupyter Below code is when plotted on a webpage using Plotly Dash data_slider = [] for month in world_df['Date'].unique(): df_month = world_df[world_df['Date'] == month] for col in df_month.columns: df_month[col] = df_month[col].astype(str) data_one_month = dict( type='choropleth', locations = df_month['Country'], z=df_month['Confirmed'].astype(float), locationmode='country names', colorscale = "purples", ) data_slider.append(data_one_month) steps … -
Django tabularinline from different app models
I am new with Django. My question is how to showing the data as Tabularinline in DetailView in django from two different apps, my issue is how to show the results in the HTML form, the results are shown in the django admin but i cant show them in the html code i wrote, here is the codes: 1st App: CustomeUser class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) memberOf = models.ManyToManyField("Team", blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) second app Project class Client(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="client_team") title = models.CharField(max_length=150, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) client=models.ForeignKey(Client,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) purchase_number= models.CharField(max_length=50, null=True, blank=True) PO_date = models.DateTimeField( blank=True, null=True) completion_date = models.DateTimeField( blank=True, null=True) i modified app1. admin.py to show the Tabularinline form. from projects.models import Project, Client class ProjectInline(admin.TabularInline): model = Project fields = ['title','client', 'purchase_number'] class TeamAdmin(admin.ModelAdmin): inlines = [ ProjectInline, … -
How to disable autoplay in iframe. Without using video tag
I need to be able to disable autoplay in an iframe because I want to be able to display the file. And the thing is I don't know what is the file type cause it will be a file the user selected. So like it can be a text file, image, or a video the best I would is the iframe cause I can put any file to be displayed. And that's the reason I don't want to use the video tag cause the file could even be an image or a text file. So I can be able to do that. If it means to be done by JS I wouldn't mind, but NOT JQUERY. And all these files are stored in a Django model so I get the file in a URL or link. So I hope someone could help -
How can I get a comment that corresponds to a post in django rest framework?
I'm going to make an api that only brings up comments from the post when I send a request to the router with comments attached to the pk value of the post. So urls as follows.After writing py and views.py, I sent the request and 404 error occurred. How can I get comments by composing an api? Here's the code I made. Thanks in advanced. urls.py urlpatterns = [ path('post', CreateReadPostView.as_view({'post': 'create', 'get': 'list'})), path('post/<int:pk>', UpdateDeletePostView.as_view({'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})), path('post/<int:post.pk>/comments', CreateReadCommentView.as_view({'post': 'create', 'get': 'list'})), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class CreateReadCommentView (ModelViewSet) : serializer_class = CommentSerializer permission_classes = [IsAuthenticated] queryset = Comment.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) -
how to get a specific object in detailview django
i've these class ModelA(models.Model): admin = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True) name = models.CharField(max_length=30) class ModelB(models.Model): users = models.CharField(max_length=30) balance = models.DecimalField(max_digits=20,decimal_places=3) def __str__(self): return self.users between ModelA and ModelB there is no any relations my forms.py class ModelAForm(forms.ModelForm): name = forms.ModelChoiceField(queryset=ModelB.objects.all()) class Meta: model = ModelA fields = ['name'] class ModelBForm(forms.ModelForm): class Meta: model = ModelB fields = ['users'] and in my views.py in DetailView of ModelA i have to return balance field in the ModelB class ModelAView(DetailView): model = ModelA template_name = 'templates/tem.html' context_object_name = 'objs' queryset = ModelA.objects.all() def get_object(self): id = self.kwargs.get('pk') return get_object_or_404(ModelA,pk=id) # i need to get balance field in ModelB for the exact object , i tried this but doesn't work #def get_balance(self): #users = ModelB.objects.all().values_list('users',flat=True) #if ModelA.objects.filter(name__in=users): # name = ModelA.objects.filter(name__in=users) # balance = ModelB.objects.get(name=name).balance # return balance #else: # return False but the above solution dont work and raised this error int() argument must be a string, a bytes-like object or a number, not 'ModelA' i need to display balance field in the ModelA DetailView !? is it possible please note : i dont want to make any connection between ModelA and ModelB i appreciate your helps ... regards -
Using firebase to sign up and authenticate users for a React & Django Rest Framework app
I have a Django Rest Framework backend with a React client. I want to use Firebase authentication in the following way: Ability to register and authenticate users via Django Rest Framework. Email registration should be supported. (I'm mainly interested in using Firebase to avoid building custom logic for email verification, password resets, etc) Ability to Django Rest Framework -
AWS S3 bucket serves image locally but on production image is not loading
I am having a problem with AWS S3 bucket. I searched and couldn't find a solution, I have a Django project hosted on Heroku and serve static images using s3 bucket. Some days back I deleted my old IAM credentials created new now the images works locally but on production it doesn't serve this images. By checking on the image URL I noticed the app locally could access the IAM credentials from env variables but on production it is still using the old deleted credentials. Here are my AWS settings setting environmental variables for S3 AWS_ACCESS_KEY_ID = os.environ.get('MY_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('MY_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('MY_AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'us-east-2' AWS_DEFAULT_UCL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Thanks for your help in advance. -
pass two of pk into url
If the 'school year' value is changed, 404 does not appear. I want data to be displayed only when both 'school_year' and 'pk' have the right values in url. for example If you have data that (School_Year = 2020, pk = 33) when you enter url https://190.0.1/190/190/33 and https://190.0.1/190/whatthell/33 Both are the same results. However, I would like to display the result only when both values are correct. i really dont know if i explained correctly, thanks. view.py class StudentDetail(DetailView,FormView): model = Student template_name = 'student/member.html' context_object_name = 'student' form_class = AddConsultation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk')) return context url.py path('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'), html link <a href='{% url 'student_detail' student.school_year student.pk %}'> models.py class Student(models.Model): school_year = models.CharField( max_length=10, choices=SCHOOL_YEAR_CHOICES, default='2021N', verbose_name='school year' ) ... etc