Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework query data is not json serialiable Error
This is my views: class BillDetailView(APIView): def get(self, request, format=None): bill = Bill.objects.get(flat__id='a flat id') return Response(bill) I know to get detailed data, we can use RetriveAPIView but I will not use it for some reasons for my business logic. That is why I am using APIView I am trying to Response the query data as you see but it firing following error: Object of type 'Bill' is not JSON serializable Can anyone help me how to Response the query data? If I pass a dictionary in Response method, It will work great but you it is bad practice for my case. I just Pass the queried data in Response method. Can anyone help me in this case? -
Unable to catch ElasticSearch Connection Error
I have a model that looks like this: class Topic(models.Model): name = models.CharField(max_length=50, unique=True) def indexing(self): try: connections.create_connection() obj = TopicIndex( meta={'id': self.id}, name=self.name, ) obj.save() return obj.to_dict(include_meta=True) except ConnectionError: raise ValidationError("Something is wrong.") Whenever a new Topic is saved, it also saves it into ElasticSearch. However, let's say ElasticSearch is down. If I save a new Topic, I'll start getting errors like this: elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) The error makes sense, however, I never catch it. "Something is wrong." never gets displayed. Instead, a connection tries to be made over and over again. -
What happens after executing the 'python manage.py runserver' command?
I am curious to know what all steps occur at the execution of the 'python manage.py runserver' command. -
GraphQL django with relay implementation not able to fetch particular ID
My node looks like - class CustomNode(graphene.relay.Node): """ For fetching object id instead of Node id """ class Meta: name = 'Node' @staticmethod def to_global_id(type, id): return id class ReportFileNode(DjangoObjectType): database_id = graphene.Int() class Meta: model = ReportFile interfaces = (CustomNode,) filter_fields: List[str] = ['id'] convert_choices_to_enum = False And my graphql query schema is like - class Query(graphene.ObjectType): all_report_files = DjangoFilterConnectionField(ReportFileNode) But when I query like this : query { allReportFiles(id: "367") { edges { node { id } } } } I get returned all the records and not just the one I queried. Also I have one more requirement that I should be able to input a list of ids and only those records should be fetched. -
Setup django social auth with vuejs frontend
I just started a project with a frontend developer. We are trying to add social authentication (Discord), without success. I want to use django as a REST API for the backend, I installed django-allauth which seems to work when I use a django template to connect using Discord: {% load socialaccount %} {% providers_media_js %} <html> <head> <title>Discord Registration</title> </head> <body> {{user}} <a href="{% provider_login_url "discord" method="oauth2" %}">Discord Connect</a> </html> But I have no idea how to share this connection with the frontend (made with vuejs). I've never worked on a project where backend and frontend are not in the same application... What to do on the frontend and what to do on the backend? And the main question, how? I've been working on it for two days and I'm still completely lost. -
GeoDjango multipolygon to polygon
As the title says how can I convert an entire database of geodjango models with geom fields of multipolygons into single polygons? The geojson is massive and I don't need multipolygons for zip codes. -
how to do HTML/CSS positioning
I am new to html and css so im sorry for asking this Q but how do you manage more than 1 item in html it seem so hard....im trying to have a image and a hover effect to it and have a text beneath this effect and then have a gallery beneath it .....pls suggest me the ways to do so. I'll include the code i've written below and this is for a django website so some contents may be different from actual html/css. Thanks in advance :) html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hey</title> <link rel="stylesheet" href="{% static "portofolio/css/cc.css" %}"> </head> <body> <div class="card"> <img src="{% static 'portofolio/img/save.png' %}" alt="Card Back"> <img src="{% static 'portofolio/img/try.png' %}" class="img-top" alt="Card Front"> </div> <div class="text"> <h1>Hello. This is me</h1> </div> </body> </html> css: body{ background-color: black; } .card { position: relative; display: inline-block; } .card .img-top { display: none; position: absolute; top: 0; left: 0; } .card:hover .img-top { display: inline; } .text{ color: white; font-family: 'TYPOGRAPH PRO',sans-serif; margin-left: 500px; margin-bottom: 500px; } -
Django: Querying two tables based on URL slug
I have created a database of music Producers and their Samples. class Producers(models.Model): producer_id = models.AutoField(db_column='Producer_ID', primary_key=True, blank=True, null=False) # Field name made lowercase. slug = models.SlugField() name = models.TextField(db_column='Name') # Field name made lowercase. info = models.TextField(db_column='Info', blank=True, null=True) # Field name made lowercase. image = models.ImageField(null=True, blank=True) class Meta: managed = False db_table = 'producers' class Samples(models.Model): song_id = models.AutoField(db_column='Song_ID', primary_key=True, blank=True, null=False) # Field name made lowercase. producer = models.ForeignKey(Producers, models.DO_NOTHING, db_column='Producer_ID') # Field name made lowercase. artist = models.TextField(db_column='Artist') # Field name made lowercase. title = models.TextField(db_column='Title') # Field name made lowercase. class Meta: managed = False db_table = 'samples' I have set up Slug Urls directing to the according Producer. ex) "producers/j-dilla/" I want each producer's bio to list their samples. Tried utilizing def bio(request, slug): producer_list = Producers.objects.all().filter(slug=slug) samples_list = Samples.objects.all() queryset = sorted( chain(producer_list, samples_list), key=lambda instance: instance.producer_id) {% for sample in queryset %} <li> <span>Artist: {{ sample.artist }}</span> <br/> <span>Title: {{ sample.title }}</span> <br/> <span>Title: {{ sample.producer_id }}</span> <br/> <hr/> </li> {% endfor %} returns the entire database of samples. -
How to get data from 2 different models in Django
I am new at this, trying to learn new django and python tricks I am making a project where authors can upload a design, the name of this app is "score" where there model.py as shown below: score app model.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='') I also have another app which is called "core" where there is an Item model. I want to be able manually from the admin to chose the name of the author and in the next design choice i only get his uploaded designs. I know I have to make a tuple of choice here is the core app model.py class Item(models.Model): title = models.CharField(max_length=100) author = models.CharField() design= models.ImageField() -
How can I style the filefield button on django?
I have been trying to style the filefield upload button but since it is run on the forms.py and not on the html, even with ours of investigation, I still don't know how to do it. Is there any way I can style the button? models.py class Post(models.Model): text = models.CharField(max_length=200) posti = models.ImageField(upload_to='media/images', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default=2) forms.py (I am missing the posti = form.ImageField under the text variable) class PostForm(forms.ModelForm): text = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Add a comment...' } )) class Meta: model = Post fields = ('text', 'posti') exclude = ['author'] uploadimage.html (It posts the image on the imagelist view) <div class="container" style="margin-top: 200px; margin-left:50px;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div id="formtext" class="overflow-hidden" type="input">{{ form.text }}</div> <div id="formimage" class="overflow-hidden" type="button">{{ form.posti }}</div> <button type="submit" class="btn btn-primary mb-2">submit</button> </form> </div> -
Can't properly connect MYSQL with Django settings.py
I've checked that I have a live mysql server, database created, and ran pip freeze to ensure that mysqlclient is installed.The only error I see is that Mysqlclient isn't connected but I can see that mysqlclient==1.4.6 is installed and is in my requirement.txt file. My settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bradynce_crm', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', } } I try to run the server and get this error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x10d5271f0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File … -
How can i use keras model in other python file? at django
loading model is so slow, so i load model in settings.py. then reuse the model in other file not load model. but i have a error such as "Tensor Tensor("predictions/Softmax:0", shape=(?, 3), dtype=float32) is not an element of this graph" many people anwserd error that is similar to my error like : use with graph.as_default(): and with sess.as_default(): but that didn't work for me i guess that answer works for loading model in multi thread i really appreciate if you can help me plz.. -
After creating a blog pot using Ajax I cannot make any other Ajax calls and JsonResponse return empty string
I have built a website where users can post. After using Ajax to create the post object it seems that I cannot like it. Basically my django view returns an empty JsonData. So I need to refresh the page for it to work. Below are what I'm using to submit my ajax calls. for creating a post: var SaveForm = function(e){ e.preventDefault(); e.stopImmediatePropagation(); var form = new FormData(this); $.ajax({ url: $(this).attr('data-url'), type: $(this).attr('method'), data: form, cache: false, processData: false, contentType: false, dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } $('.post-like-form').on("click", ".likeBtn", function (e) { var like_count = $(".input-like-count", this).val(); $(".like-count-d").text(like_count); e.preventDefault(); if($(this).find("i").hasClass("fa-thumbs-up")){ like_count++; $(".input-like-count", this).val(like_count); $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down") $(".like-count", this).text(like_count); $(".like-count-d").text(like_count); } else { like_count--; $(".input-like-count", this).val(like_count); $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up") $(".like-count", this).text(like_count); $(".like-count-d").text(like_count); } var tk = $(this).attr("data-token"); var pg = $(this).attr('value'); $.ajax({ type: "POST", url: $(this).attr("data-url"), dataType: 'json', data: {'guid_url': pg, 'csrfmiddlewaretoken':tk }, success: function (data){ var like_count = parseInt($(".like-count", this).text()); if($(this).find("i").hasClass("fa-thumbs-up")){ like_count++; $(".input-like-count", this).val(like_count); $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down") $(".like-count", this).text(like_count); } else { like_count--; $(".input-like-count", this).val(like_count); $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up") $(".like-count", this).text(like_count); } $("#post-detail-container div").html(data.post_detail) }, error: function(rs, e){ console.log(rs.responeText); }, }); }); } }) return false; } Which successuly creates the post object (It takes a lot … -
Efficient geojson queries with massive datasets
How can I efficently query massive amounts of geospatially linked data (10s of millions of rows) which are bound to some spatial region and needs a cloropleth / ranking metric applied to them. Naturally, this requires mathematical functions on the properties of teh region itself. So, we have 30k+ zip codes, demographics for each of this, need to apply metrics to items inside of this demographic data and the demographic data itself is significant. Seems there's no way around this being incredibly slow. I can layer things. Do the tiling map, then grab the zip code polygons. Then once those features are loaded I can do a callback within the bounding box to grab the demographics attached to those regions, then apply the metrics in the frontend / javascript. But, that's only localized regions. What happens when you zoom out and you're looking at an entire country. That's massive amounts of data. -
Django Rendering Forms Manually and using csfr token
I think I am slowly getting the hang of Django, but am relatively new and self taught at programming. I have been using form.as_p and form_ul in templates, but wanted to get a better understanding of how to make them look better. I looked at the Django documentation of how to manually render forms. That seems to work as advertised, and I can show the individual fields etc. on my html page. However in the documentation this is highlighted: Forms and Cross Site Request Forgery protection Django ships with an easy-to-use protection against Cross Site Request Forgeries. When submitting a form via POST with CSRF protection enabled you must use the csrf_token template tag as in the preceding example. However, since CSRF protection is not directly tied to forms in templates, this tag is omitted from the following examples in this document. I don't think I understand what is meant by the last line. I assume it means that I can render the form all I want, but unless there is a Post request being made I don't need a CSRF token. Is there an example of how to manually render forms with post requests and CSRF tokens? I am … -
How to add Google Calendar to a Django Webapp which is already using Django-allauth google social login
I am trying to add a google calendar to my webpage for a user who has logged into the website using a google account via the Django-allauth package social login. I have set up the social login, and I am able to login and authenticate users. Next step will be to add a calendar to the webpage, since I have already logged in with a google account to my website. How do I go about adding a google calendar? -
Alternate rows of a queryset from different order_by() clauses
I'm trying to implement a custom view where posts are alternated between newest and most voted: | post | vote_score | created_at | ==================================== | A | 20 | 01/01/2020 | ---> Top voted | F | 0 | 05/01/2020 | ---> Newest | I | 19 | 02/01/2020 | ---> Second to Top Voted | B | 2 | 04/01/2020 | ---> Second to Newest I know I could just run 2 queries, one sorting by vote_score and another one by created_at and then interleave the rows in Python. I was wondering if there was a more efficient way to do this in the database so that I could use LIMIT and OFFSET to support simple paging on my website. I was playing with annotate, Window() and RowNumber() but I couldn't make it work: qs.annotate(row_number=Window( expression=RowNumber()*2, order_by=F('created_at').desc()) ).annotate(row_number=Window( expression=RowNumber()*2+1, order_by=F('vote_score').desc()) ).order_by('row_number') -
Is there a better way to create model while the database already have the table
In my MySQL database I already have a table fo_dic. mysql> desc fo_dic; +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(30) | YES | | NULL | | | desc | text | YES | | NULL | | | author | varchar(20) | YES | | NULL | | | priority | int(5) | YES | | NULL | | +----------+-------------+------+-----+---------+----------------+ Now I want to create the FoDic model for Django Rest Framework to ORM the data. from django.db import models class FoDic(models.Model): id = models.IntegerField() name = models.CharField() desc = models.TextField() author = models.CharField() priority = models.IntegerField() def __str__(self): return self.name def __unicode__(self): return self.name I want to know whether this will generate migrations when I sync the database, then there will have conflict? is there a way to create the Model as the same structure as the MySQL table? -
django cannot view database items in template
I have data that I insert into my database but cannot view the items. I can see a index, but no data. $ python3 manage.py shell Python 3.7.3 (default, Dec 20 2019, 18:57:59) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from userdash.models import AssetList >>> ls = AssetList.objects.get(id=2) >>> ls <AssetList: Mike's List> >>> ls.items_set.all() <QuerySet [<Items: Batcoin>, <Items: Drum set>, <Items: Dildo>, <Items: Koodie>]> >>> ls.items_set.create(user_asset="5th Item", sell_asset=False) in userdash/templates/userdash/list.html {% extends 'userdash/base.html' %} {% block title %} <h1>List Page</h1> {% endblock %} {% block content %} <h2>{{ls.name}}</h2> <ul> {% for item in ls.items_set.all %} <li>{{items.user_asset}}</li> {% endfor %} </ul> {% endblock %} in exchange2/userdash/models.py from django.db import models # Create your models here. class AssetList(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Items(models.Model): currencylist = models.ForeignKey(AssetList, on_delete=models.CASCADE) user_asset = models.CharField(max_length=300) sell_asset = models.BooleanField() def __str__(self): return self.user_asset output: html output The ul output indicates data is there, but it's not displaying it. How do I properly display my database query in a django template? -
Django: Getting a reverse error, but data still goes through the database
I'm getting a reverse error when redirecting to the details page after filling out the form (and the information actually going to my db). I'm not sure how to fix it since it was working before, so it must've somehow broke in the middle while coding. The error that I'm getting : NoReverseMatch at /finches/create/ Reverse for 'finches_detail' with keyword arguments '{'pk': 20}' not found. 1 pattern(s) tried: ['finches/(?P<finch_id>[0-9]+)/$'] Here's part of my models.py: class Finch(models.Model): name = models.CharField(max_length=100) breed = models.CharField(max_length=100) description = models.TextField(max_length=250) age = models.IntegerField(default=0) toys = models.ManyToManyField(Toy) def __str__(self): return self.name def get_absolute_url(self): return reverse('finches_detail', kwargs={'pk': self.id}) It should return /finches/ upon creation, but it doesn't. My views.py class and function: finch = Finch.objects.get(id=finch_id) toys_finch_doesnt_have = Toy.objects.exclude( id__in=finch.toys.all().values_list('id')) feeding_form = FeedingForm() return render(request, 'main_app/finch_detail.html', { 'finch': finch, 'feeding_form': feeding_form, 'toys': toys_finch_doesnt_have }) class FinchCreate(CreateView): model = Finch fields = ['name', 'breed', 'description', 'age'] and the urls.py path('finches/<int:finch_id>/', views.finch_detail, name='finches_detail'), path('finches/create/', views.FinchCreate.as_view(), name="finches_create"), I'll update more info if it's needed. Upon creating, I notice that the link is still at finches/create even pressing submit. Any ideas on what's happening or any solutions? Thanks -
Path / URL error in application created for Django/Python course I'm taking
This is the error I receive from the browser This is the code of the urls.py file from django.urls import path from blog import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), # sets home page to all current blogs that are published path('about/',views.AboutView.as_view(),name='about'), path('post/<int:pk>',views.PostDetailView.as_view(),name='post_detail'), # will match primary key to whatever we click on path('post/new/',views.CreatePostView.as_view(),name='post_new'), path('post/<int:pk>/edit/',views.PostUpdateView.as_view(),name='post_edit'), path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), path('post/<int:pk>/comment/',views.add_comment_to_post,name='add_comment_to_post'), path('comment/<int:pk>/approve',views.comment_approve,name='comment_approve'), path('comment/<int:pk>/remove',views.comment_remove,name='comment_remove'), path('post/<int:pk>/publish',views.post_publish,name='post_publish'), ] Please help! Thanks! -
How to implement Many to many relation in django when the relation contain attributes?
I'm begginer at django and I knew that you can use ManyToManyField to link two models like author-post user-groups. so I have this relation in my UML How can I implement this in my code ? my shot was like this class User(models.Model): # user fields class Group(models.Model): # group fields class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, db_index=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING, db_index=True) IsAdmin = models.BooleanField(default=False, verbose_name='Est un admin') class Meta: unique_together = (("group", "user"),) I want to use ManyToManyFields so I can refer between them (if I haven't IsAdmin field, I don't have to create the third class 'GroupMember') -
Python Django - ModuleNotFoundError: No module named 'picamera'
I'm making my first Django-based web page, and trying to live stream video from my raspberry pi to said web page, but for some reason, I can't import the 'picamera'-module in Django... I have written a script that outputs the camera-feed, and it works fine when i run it outside of the server, but when i import my camera-script to views.py, i get the error message ModuleNotFoundError: No module named 'picamera'. Does anyone know why? All the other modules i'm using works fine both in and outside of Django. Importing my own modules also works fine. I'm certain that i have installed the picamera-module (https://picamera.readthedocs.io/en/release-1.13/) correctly, I even tried removing and reinstalling it. I got the same error when trying to import NumPy(https://pypi.org/project/numpy/)... I am using a virtual environment. Don't know if that may be a factor, but i thought I'd mention it, just in case. Eternally grateful to anyone who can help! -
Cannot access Django Model from Celery in Docker
I've been working on this problem most of the day and I am hoping someone can point me in the right direction. I am building an application with django and I started messing around with deploying it to docker and using celery to schedule tasks. I have celery running a custom manage.py command using call_command once per minute. Everything is working! Except I cannot seem to access django models from my custom django admin command. I have tried to import the model inside my function, and also use get_model to no avail. When I do Model.objects.all() the query is always empty. When I try to grab a specific Object with Mode.objects.get(id=##) it gives me an error. The command works perfectly when I call it using docker-compose -f docker-compose.yml exec web python manage.py [custom-command] but not when run by celery. Hopefully, someone out there knows of a fix because From when I have read so far it seems like this should be working. Alright, enough talking here is some code. Here is my docker-compose file for celery redis: image: redis:alpine celery: build: ./app command: celery -A [appname] worker -l info volumes: - ./app/:/usr/src/app/ environment: - DEBUG=1 - SECRET_KEY=[secret-key] - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 … -
I have a question about how to get data from HTML in Django
So my problem is that when I render my home page in Django I make a request to a movie API and display the top-rated 20 movies. Now I want to display each movie as it's a poster and that poster would be clickable and would take me to a page for that specific movie. What I need to do (please let me know if there is a better way to do that in Django) is get the information that I have passed to the render function back in my next movie function. def home (request): r = requests.get("https://api.themoviedb.org/3/movie/top_rated?api_key=key=en-US&page=1") movies_json = r.json() context = { 'movies' : movies_json['results'] } return render(request, 'movies/home.html', context) HTML <div class="row"> {% for movie in movies %} <div class="column"> <a href = "/movie" class = "column col-xs-6" id = "sepia"> <img src = "https://image.tmdb.org/t/p/w500{{movie.poster_path}}" style="width:50%; height:75%;" alt="..."> <span class="caption">{{movie.title}}</span> <span class="caption">{{movie.id}}</span> </a> </div> {% endfor %} </div> </div> What I want to do is get that movie.id in my next function which will make another request to the API with that specific id so it would display the right page.