Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render Python seaborn Plot on Django Template
I am trying to render the plot generated by seaborn on Django template. I have the following code in my views.py: def booking_hour_plot(): qs = bookings_today() df = read_frame(qs) plot = sns.countplot(data=df) return plot def render_stats_page(request): #general info user_count = total_users_until_now() cancel_rate = activity_cancel_rate() #activity/booking details activity_set = activities_today() booking_set = bookings_today() plot = booking_hour_plot() return render(request, "stats.html", {'name':'Avonmore Statistics', 'total_user':int(user_count), 'cancel_rate': round(float(cancel_rate), 2), 'booking_count_today': booking_set.count(), 'activity_count_today': activity_set.count(), 'activities_today': activity_set, 'bookings_today': booking_set, 'booking_hour_plot': plot, }) And I have a html template called stats.html that containing the plot. The templates directory and views.py are in the same directory: <li>Real Time Plot: {{booking_hour_plot}}</li> However, the rendered html page is not really showing the plot. It's more like the plot object: enter image description here Any Idea how to put the real plot on the html page, rather than this plot object? -
dlib makes videostream laggy on django
im pretty new in codes and i just start new project using django opencv and dlib. My project have face recognition feature so i use opencv videostream. But i got problem with videostream becomes so laggy everytime i try to call dlib face detector, not only the face detector but whenever i tried to call another dlib's function the videostream still lag. Im using my laptop webcam for the project, is it does also affecting the codes? Can anyone help me? I've been stuck for week and still not found the answer:( -
Strange "on" type being recorded in MySQL database (Navicat Premium) in Django
I have been trying to insert information with an HTML form into my database. However, when I submit, my "gender" and my "website_rating" has been strangely replaced with "on", when it is supposed to be replaced with my website input. Image of the Database: https://i.stack.imgur.com/94d8L.png Here is my models.py # _*_ coding:utf-8 _*_ from __future__ import unicode_literals from django.db import models """ Quick Guide to Model Fields that We Did Not Use: - models.ForeignKey() - models.DateTimeField() - models.IntegerField() - models.IPAddressField() - models.FileField() - models.ImageField() """ # Create your models here. class PersonalInfoResponse(models.Model): # Personal Info Section name = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"Name") age = models.IntegerField(verbose_name=u"Age", default="N/A", null=True) email = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"text#@thing.com") gender = models.CharField(max_length=7, null=True, verbose_name=u"gender") # Website Response Section website_rating = models.CharField(max_length=3, verbose_name=u"1-10", null=True) heardof_flag = models.BooleanField(verbose_name=u"truefalse", null=True) heardof = models.CharField(max_length=255, null=True, verbose_name=u"How did you know about the C&C Education Center?") # Misc Section fav_subject = models.CharField(max_length=50, null=True, default="None", verbose_name=u"truefalse") fav_website = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is your favorite part about this website?") website_improve = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is something that this website needs improvement on?") class Meta: verbose_name = u"User Contact Info" verbose_name_plural = verbose_name And here is my views.py from django.shortcuts import render from … -
Django-vimeo 'NoneType' object is not iterable
Model structure is like below: class Video(models.Model): video_header = models.CharField(max_length=350, verbose_name="Video Başlığı", blank=False, null=False) video_description = models.TextField(verbose_name="Video Açıklaması", blank=False, null=False) date_created = models.DateField(auto_now_add=True, verbose_name="Oluşturma Tarihi", blank=False, null=False) video = fields.VimeoField(null=True, blank=True) def __str__(self): return self.video_header class Meta: verbose_name = "Video İçeriği" verbose_name_plural = "Video İçerikleri" When I click on any video object which created in django admin to edit it, get " 'NoneType' object is not iterable " error. But actually there is a object and it is not "None" when I look at database and also checked it in frontend. So it seems like meanless to me. Could you please help me to get through this problem. -
Custom save method with condition in django model
I am trying to do a django project where a user can describe pictures using one or more taggings, as soon as more than one user has entered the same tagging for the same picture, this word or tagging should be saved to the Tag table. I thought I can solve this by adding a custom save method to the Tag model. Would this be the right approach or would I write this logic inside a view? class Tag(models.Model): LANGUAGES = (('en', 'english'), ('de', 'deutsch'), ('fr', 'francais') ) name = models.CharField(max_length=256) language = models.CharField(max_length=256, choices=LANGUAGES) class Tagging(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, blank=True, default='') picture = models.ForeignKey(Pictures, on_delete=models.CASCADE, related_name='taggings', default='') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) -
Get data from external URL in JSON format with Django REST
I want to do simple Rest API in Django. It's my first approach to Rest in django, but for now it isn't going that bad ;) For now I have a model database with two fields brand and model. With the use of Postman, I can GET, POST and DELETE objects, cool. But what I'm stuck with is -> When I POST an object, first I'd like to check if that model with given brand even exists. I want to check it on specific website: link. (In the URL of that website I can change brand name so it gives me a list of model with given brand) My approach would be, when request.method=='POST' first GET data from website, load it to a model and then somehow compare it with data in POST request. But I don't know how to get to that point :) Is it a good approach or is there a way to directly look at data on the given website? (For me there is no need to give you my code, because there is nothing special in it, but tell me if I'm wrong!) -
How to run a rabbitMQ script in a django rest framework project
So I have a django rest framework project, and what I want to do, is to push into a rabbitMQ queue some values from a file with a python script, and as soon as my django server starts running, I want the project to start consuming the messages available in the queue, and with those values, insert entities in my database. So here is my producer python script: import pika, csv, time url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') with open('sensor.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter='\n') for row in reader: channel.basic_publish(exchange='', routing_key='hello', body=row[0]) print(row[0]) time.sleep(1) connection.close() This script doesn't belong to the django project, I will run this script outside of it. This is my consumer script: import pika from app.models import Measurement url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): measurement = Measurement.objects.create(sensor=3, energy_consumption=float(str(body))) measurement.save() channel.basic_consume('hello', callback, auto_ack=True) channel.start_consuming() connection.close() I want to integrate this consumer script inside my django project, so that as soon as I start putting messages in my queue with the procuder script, the consumer script is ready for them, intercepts them and inserts a new entity … -
("Django tried these URL patterns... The empty path didn't match any of these.") How to fix "Page not found (404)" error
I am using the visual studio code for the basic Django project and whenever I try to run the server it gives the error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in startup.urls, Django tried these URL patterns, in this order: login/ admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Whereas I write the code correctly landing app folder views file code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def loginpage (request): return render (request, 'login.html') landing app file urls.py code from django.contrib import admin from django.urls import path from. import views urlpatterns = [ path('login/',views.loginpage, name="login" ), landing app file login.html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h1> Login </h1> </body> </html> main project urls.py file code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('login/',include('landing.urls')), path('admin/', admin.site.urls), ] Please help me regarding this. -
Google Cloud Django if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): not working
I am working on a Google Cloud Django Project. I am trying to check in settings.py if I am running in Development or Production mode. I added the following block of code to test if the SOFTWARE where the program is running either is on my machine or on Google Cloud Servers. # | settings.py | if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): #code to execute in production else: #code to execute in development I noticed that the if statment is always false, so I decited to debug the os.environ dict. The result of the debug is that the value of the key SERVER_SOFTWARE of the enviroment is equal to gunicorn/20.1.0. As written in the correct answer of this stackoverflow question, when running on production (so on Google Cloud Severs App Engine), the value of SERVER_SOFTWARE should be Google App Engine/X.Y.Z, where X, Y and Z represent the version of Google Cloud. But, as I said, my value, when running on App Engine, is not like that, it is gunicorn/20.1.0. So, how do I make the program know if I am running either in development or production? -
Why DRF IsAuthenticatedOrReadOnly class permission class allowing Post method
I am performing test on Django rest framework, here is my view, class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly,] queryset = Post.postobjects.all() serializer_class = PostSerializer Url pattern like bellow, urlpatterns = [ path('<int:pk>/',PostDetail.as_view(),name="detailcreate"), path('',PostList.as_view(),name="listcreate"), ] Here is my test : def create_post(self): self.test_category = Category.objects.create(category='django') self.test_user = User.objects.create_user(user_name="test_user",password="123456789") data = {"title": "new", "author": 1, "excerpt": "new", "content": "new"} url = reverse('api:listcreate') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) i ran followiing command: coverage run --omit='*/myvenv/*' manage.py test and get output : Ran 1 test in 0.215s OK as my understanding, as here permission class is [IsAuthenticatedOrReadOnly,] , self.client should not have permission to post and test should Failed. I don't understand what i am missing here. -
Djange NoReverseMatch error - reverse for 'edit' with no arguments not found
In a Django app I am building for a course, I am attempting to pass a parameter from one template to a function in views.py through a url path. The path definition in urls.py contains the parameter name, and the same name is required by the function in views.py. The link in my template points to the correct url path and names a value for the parameter, but I am still receiving a NoReverseMatch error. Weird because I have another url path that requires a parameter and which is working perfectly. entry.html Here is the link to the path called edit in urls.py. I want to pass the value of the variable entryTitle to the url as entry: {% extends "encyclopedia/layout.html" %} {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py the edit path is the last one defined in urlpatterns from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/edit/<str:entry>", views.edit, name="edit") ] views.py This is the edit function, requiring entry as an argument … -
Django: The Model could not be created because the data didn't validate. error
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is my code and when I try to submit a new file I'm getting this error The Dataset could not be created because the data didn't validate. I can't also access the file If I create it in admin because I get this error Dataset matching query does not exist. I think my problem is within the ForeignKey and the OneToOneField that I'm not able to save properly? Or that I'm not actually creating a new Dataset atl all? Only the model File is compiled by the user, while Dataset should be filled from the information in the file and linked to the file and the user automatically . Thank you all for your help! VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() or data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) data_form.save() file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': … -
Revoking Celery task causes Heroku dyno worker timeout
My Django API app has a view class that defines a post and a patch method. The post method creates a reservation resource with a user-defined expiration time and creates a Celery task which changes said resource once the user-defined expiration time has expired. The patch method gives the user the ability to update the expiration time. Changing the expiration time also requires changing the Celery task. In my patch method, I use app.control.revoke(task_id=task_id, terminate=True, signal="SIGKILL") to revoke the existing task, followed by creating a new task with the amended expiration time. All of this works just fine in my local Docker setup. But once I deploy to Heroku the Celery worker appears to be terminated after the execution of the above app.control.revoke(...) causes a request timeout with an H12 error code. 2021-11-21T16:39:35.509103+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=PATCH path="/update-reservation-unauth/30/emailh@email.com/" host=secure-my-spot-api.herokuapp.com request_id=e0a304f8-3901-4ca1-a5eb-ba3dc06df999 fwd="108.21.217.120" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https 2021-11-21T16:39:35.835796+00:00 app[web.1]: [2021-11-21 16:39:35 +0000] [3] [CRITICAL] WORKER TIMEOUT (pid:5) 2021-11-21T16:39:35.836627+00:00 app[web.1]: [2021-11-21 16:39:35 +0000] [5] [INFO] Worker exiting (pid: 5) I would like to emphasise that the timeout cannot possibly be caused by calculation complexity as the Celery task only changes a boolean field on the reservation resource. For reference, … -
Why can't I serve my static files to Django?
Before anyone marks this as a duplicate I have seen all of the other questions on similar topics and tried all of the solutions without effect. My Django application is small and I am happy to serve the static files from the same server In settings.py I have STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have uploaded my application to the server and run python.manage.py collectstatic All of my static files are in the appropriate directories under staticfiles project-root ├── staticfiles │ ├── css │ │ ├── base.css │ ├── js │ │ ├── common.js In my html I have {% load static %} <link href="{% static 'css/base.css' %}" rel="stylesheet"> On loading the page I get the error Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I think this is because it cannot filed the css file Where am I going wrong? Do I need to provide any more information? -
How do I display a img in html (django)
html file: <!DOCTYPE html> <html> <head> <title>Resume Homepage</title> </head> <body> <img src="main_photo.jpg" alt="Image Unable To Be Displayed"> </body> </html> Note the photo is in the same directory as the html file so why wont it display ? I keep just getting 404 errors. I am also near positive the name of the photo file is correct as its very simple how could I mess that up. -
Django admin object already exists, when using Django 4 functional unique constraints
When creating a new object from Django Administration site, I'm getting an error "Tag with this already exists.". I suppose this is related to the contraints put on the model. However, creating a Tag object with code - e.g. Tag.objects.create(...) - works fine. It only fails in Django admin. Any idea why ? Note: I'm using functional unique constraints introducted in Django 4.0 (https://docs.djangoproject.com/en/dev/ref/models/constraints/#django.db.models.UniqueConstraint). I'm wondering if I shoud raise a bug? This is my model: class Tag(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('user')) name = models.CharField(max_length=50, db_index=False, verbose_name=_('name')) slug = models.SlugField(max_length=50, verbose_name=_('slug')) class Meta: ordering = ['name'] # Create an index to make tags unique per user and also an index on lowercase name to prevent inserting duplicate tags with varying case constraints = [models.UniqueConstraint(fields=['user', 'name'], name='unique_tags_per_user'), models.UniqueConstraint(Lower('name'), name='lower_tag_name_idx')] def __str__(self): return self.name This is the admin configuration: @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'name', 'slug') list_display_links = ['pk'] fields = ('user', 'name', 'slug') list_filter = ('user__email',) search_fields = ('name',) prepopulated_fields = {'slug': ('name',)} -
How to get objects that contain a specific string
I want to retrieve objects that contain a specific string in their CharField. In normal Python without Django, I can do this to check: if "something" in string: pass However, I don't know how to do so using .filter() in Django: posts = Post.objects.filter(field = "string") # how can I do something like 'in' here? I don't just want to get objects that have exactly the value as "string". Please teach me how to retrieve objects that contain a specific string in Django using .filter(). -
Derived (Calculated) Field From Another Model
I have started a simple entry-level django project for practicing, it uses sql-server as the database (mssql-django). How can I have a derived attribute (calculated column) from a different table as a field on my model? Let's say I have this model from django.db import models class Person(models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() class JobTitles(models.Model): job_title = CharField(max_length=20) class Jobs(models.Model): job_id = models.OneToOneField( JobTitles, on_delete=models.CASCADE, ) person_id = models.ForeignKey( Person, on_delete=models.CASCADE, ) job_income_in_usd = models.IntegerField() class Salary(models.Model): person_id = models.ForeignKey( Person, on_delete=models.CASCADE, ) name = 'SELECT name FROM Person WHERE Salary.person_id = Person.id' income_in_euro = 'SELECT job_income_in_usd * 0.89 FROM Jobs INNER JOIN Salary ON Salary.person_id=Jobs.person_id' age = 'SELECT datediff(year, (SELECT birth_date FROM Person WHERE Salary.person_id=Person.id), getdate())' How do I implement the above SELECT codes in Python-Django codes? Related questions: Derived attribute in Django model How to add a calculated field to a Django model Django getting field names from different models Related SQL-Server question: How to create derived attribute? -
convert TIFF base 64 string to jpeg format using python
i have a base 64 string which has TIFF format and i need to send it in the response below is my code def get(self, request, *args, **kwargs): try: try: base64_string = CkycDetail.objects.last().image_details.get('image')[2].get('imageData') content_type = 'image/jpeg' _ext = '.jpeg' file = BytesIO(base64.b64decode(base64_string)) file_obj = InMemoryUploadedFile( file, field_name=None, name=f'file_name.{_ext}', content_type=content_type, size=len(file.getvalue()), charset=None, ) return HttpResponse(file_obj.file, content_type=content_type) except ObjectDoesNotExist: return Response("Not Found", status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(str(e.__str__()), status=status.HTTP_400_BAD_REQUEST) i am converting it into jpeg format but image is not showing on my browser for tiff format but working fine for jpeg format can anyone help me out -
How to pass extra information to a form in Django
I have the following form which should return a queryset of Cashpool where cashpool__name=request.user.company.cashpool. To execute the correct query, it needs information from the view. # views.py class AddAccountForm(forms.Form): # The entity on whose behalf the account shall be added company = forms.ModelChoiceField(queryset=Company.objects.get(name=....)) ... Is there any way to pass an extra argument to the form in the view to make the user object available in the form so it can get the correct queryset somehow? # forms.py def add_account(request): # Return the form on get request if request.method == 'GET': form = AddAccountForm() ... -
can anyone help me with this
**I am getting an error as list index out of range, can anyone help me with this,why I am getting, how to resolve this , thanks ** def home(request): import json import requests if request.method == "POST": zipcode = request.POST['zipcode'] api_request = requests.get("http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=" + zipcode + "&distance=5&API_KEY=96A38DFD-5C56-4740-AD99-E38C0C855A1B") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." if api[0]['Category']['Name'] == "Good": category_description = "(0 -50) Air quality is considered satisfactory, and air pollution poses little or no risk." category_color = "good" elif api[0]['Category']['Name'] == "Moderate": category_description = "(51-100) Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution." category_color = "moderate" elif api[0]['Category']['Name'] == "Unhealthy for Sensitive Groups": category_description = "(101 - 150) Although general public is not likely to be affected at this AQI range, people with lung disease, older adults and children are at a greater risk from exposure to ozone, whereas persons with heart and lung disease, older adults and children are at greater risk from the presence of particles in the air." category_color = "usg" elif api[0]['Category']['Name'] == "Unhealthy": category_description = "(151 - 200) Everyone may … -
How to send form to REST API page and login or register users without seeing the page in Django?
hey I'm learning REST and I made a page like this: class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer and this is my serializer: class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True}, } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user and I have an form that works good and used POST method for it and its action is that page that I defined with REST and you can see at the first of text. I tried this and it works but how I can register with REST and user don't see the page of my API? sorry for getting your time and thank you for help -
Common fields for different django models in one place
I have some columns that are repeated in multiple models. is there any solution to place them somewhere and use it any model? -
Django query date
I have 4 rows in db. #Dates Fri 18 Nov 2021 13:45 pm. - 14:45 pm. Fri 18 Nov 2021 14:47 pm. - 15:47 pm. Fri 18 Nov 2021 19:53 pm. - 20:11 pm. Thu 18 Nov 2021 20:39 pm. - 21:39 pm. How to perform a query in Django and get a result like below, i'm using postgresql: #Dates Fri 18 Nov 2021 13:45 pm. - 14:45 pm. 14:47 pm. - 15:47 pm. 19:53 pm. - 20:11 pm. Thu 18 Nov 2021 20:39 pm. - 21:39 pm. Let's say: MyModel.objects.filter(.. -
Django show same content (of a model) in sidebar of every page (also in different apps)
I have two apps: blog and mysite. In the project folder, I have a template which includes a sidebar template. This sidebar is shown on every page of the project (index pages, mysite pages, blog pages). One part of this sidebar should show a list of the latest x blog entries (independent of the page where the user is). blog/models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=264) text = RichTextField(config_name='detail_text_field', default='') created_date = models.DateTimeField(default=timezone.now) blog/views.py class LatestBlogEntriesListView(ListView): model = Post template_name = 'blog/_latest_blog_entries_list.html' def get_queryset(self): return Post.objects.all().order_by('created_date')[-3:] sidebar.html <div class="row"> {% include 'blog/_latest_blog_entries_list.html' %} </div> _latest_blog_entries_list.html <h4>Latest Blog Entries</h4> {% for post in objects %} <a href="{% url 'blog:post_detail' pk=post.pk %}">{{ post.title }}</a> {% endfor %} Unfortunately, this does not work. My sidebar only shows the h4 "Latest Blog Entries", but not the posts. How can I do this? Any help is highly appreciated!