Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use group by and get every record in each group?
I want to summarize all attendance records of each person every day,in my current solution, i need to get all records then use for loop, is there a better way to get the queryset like the following: class AttendanceRecord(models.Model): f_UserInfo = models.ForeignKey(to=UserInfo, on_delete=models.CASCADE) f_Device = models.ForeignKey(to=Device, on_delete=models.CASCADE) f_time = models.DateTimeField(auto_created=True) # How to group record by user and get a queryset like the following? [ {user_id1: [ {'f_Device_id': 1, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 1, 'f_time': '2020-11-11 18:00:00'} ]}, {user_id2: [ {'f_Device_id': 2, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 2, 'f_time': '2020-11-11 18:00:00'} ]}, ] -
Python Datetime Showing one day ahead date
I encountered one weird issue. I have one Django project, which uses (America/Denver) timezone by default. I got a couple of records into the database. id name date_create 1 foo Dec. 8, 2020, 6:15 p.m. 2 bar Dec. 1, 2020, 8:28 p.m. When I print the above record, it behaves weirdly. >>> print(record_one.date_create.date()) >>> Dec. 9, 2020 >>> print(record_one.date_create) >>> Dec. 8, 2020, 6:15 p.m. >>> print(record_two.date_create.date()) >>> Dec. 2, 2020 >>> print(record_one.date_create) >>> Dec. 1, 2020, 8:28 p.m. I am using python 3.5 and Django2 Django setting LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Denver' USE_I18N = True USE_L10N = True USE_TZ = True -
django with dynamic country state and city selection field in template
I want a country, state, and city selection field in my HTML. I want to use Django forms for dynamically changing state list if I change the country. and also require Django form validation. for example how can I achieve this with Django forms and models? -
django.core.exceptions.ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'basic_app.urls' from 'C:\Users\shree\learning_users\basic_app\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. code in basic_app.url from django.urls import path from basic_app import views app_name = 'basic_app' url_patterns = [ path('register', views.register, name='register'), ] code in learning_users.url from django.contrib import admin from django.urls import path,include from basic_app import views # from django.conf.urls import url,include urlpatterns = [ path('',views.index,name='index'), path('admin/', admin.site.urls), path('basic_app/',include('basic_app.urls')), ] -
gunicorn: command not found in django app configured for docker and azure
I'm trying to deploy a pretty simple dockerized Django app to Azure. I was successfully able to push the containerized repository to Azure. When I run docker run <myloginserver>/myappname:v1, per instructions here: https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-azure-cli I get two errors: /usr/local/bin/init.sh: line 2: -e: command not found /usr/local/bin/init.sh: line 6: gunicorn: command not found gunicorn is installed in both my pipfile and my requirements.txt, and comes up as a satisfied requirement when I try to reinstall. How should I approach this? -
Reverse for 'add_comment' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P<id>[0-9]+)/$']
Hello I am trying to add comments to a page but when I press submit I get this error: Reverse for 'add_comment' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P[0-9]+)/$'] forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['response'] Form on the page <form action="{% url 'CA:add_comment' id=climb.id %}" method="POST"> {% csrf_token %} <label for ="comment"></label> <textarea class="form-control" name="comment" id = "comment" rows = "5"placeholder="Add a comment"></textarea> <br> <input type="submit" class = "btn btn-primary" value="Add Comment"> </form> models.py class Comment(models.Model): response = models.CharField(default="Blank Comment", max_length=500) username = models.ForeignKey(User,default= 1, on_delete = models.CASCADE) date = models.DateTimeField(auto_now=True) climb = models.ForeignKey(Climb, on_delete = models.CASCADE) views.py def addcomment(request, id): climb = Climb.objects.get(id=id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.response = request.POST["response"] data.username = request.user data.climb = climb data.save() return redirect('CA:cd', id=climb.id) else: form = CommentForm() context={ "form" : form } return render(request, "climbDetail.html",context=context) urls.py path('addComment/<int:id>/', views.addcomment, name='add_comment'), I can't figure out what is going wrong. Any help would be greatly appreciated. -
How to clear an image field in django forms?
So my views look like this: class PostCreateView(CreateView): model = Post fields = ['title','content','image', 'status'] The image field currently looks like this: Is there a way to have like a button to clear the image from the field? The only way to remove the image is to do it from django admin page. -
Importing a class with only the package name?
So, I'm trying out Django and I noticed that we do something like this whenever we want to work with a model in model.py: from django.db import models and whenever we want to subclass a Model class we do something like this: class SomeModel(models.Model) I was curious to see what was in models so I looked at the django directory in the site-packages. It has a directory like this: django db models //some-other-modules so "models" is just a subpackage within the "db" subpackage. My question is how are we able to subclass Model the way I did above? We're only importing the subpackage "models" and the class "Model" must be located somewhere in one of the modules inside models, but that module isn't ever specified. Can someone explain? Let me know if I need to clarify. -
which error occurs in python when data is not found in database?
I am working on a project in python Django and there I am fetching data from a database there are some code where fetching data is related to product attributes so when the product has attribute size then I have to fetch data otherwise not so which exception class should I use in "try" "catch" and how? -
Circle progress bar using python and django
my project is about getting texts from input and counts how many words and numbers are in that text.i want to show it as percentage too. how can i make Circle progress bar in django like this here thanks -
style.css didnt update with collecstatic - AWS
I'm currently trying to update my aws static files with python manage.py collectstatic, but it won't update. Here is what it looks like header{ position: absolute; z-index: 10; width: 100%; } .header-in{ position: absolute; z-index: 10; width: 100%; } .headerContent{ margin: 10 auto; } .navbar{ margin-top: 0; padding: 20px 0; } .navbar-light .navbar-nav .nav-item .nav-link:hover, .navbar-light .navbar-nav .nav-item.active.nav-link { background:#f6e58d } .banner{ position: relative; background: url('/static/bg.jpg'); min-height: 100vh; background-size: cover; background-position: center; padding: 250px 0 250px; } .banner h2{ margin: 0; padding: 0; font-size: 2.3em; } .banner p{ margin: 1em 0 0; padding: 0; font-size: 1.2em; } Now how it should be looking header{ position: absolute; z-index: 10; width: 100%; } .header-in{ position: absolute; z-index: 10; width: 100%; } .headerContent{ margin: 10 auto; } .navbar{ margin-top: 0; padding: 20px 0; } .navbar-light .navbar-nav .nav-item .nav-link:hover, .navbar-light .navbar-nav .nav-item.active.nav-link { background:#f6e58d } .banner{ position: relative; background: url('/static/bg.jpg'); min-height: 100vh; background-size: cover; background-position: center; padding: 250px 0 250px; } .banner h2{ margin: 0; padding: 0; font-size: 2.3em; } .banner p{ margin: 1em 0 0; padding: 0; font-size: 1.2em; } .slidershow{ width: 700px; height: 400px; overflow: hidden; } .middle{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } My setting.py related to … -
Django crispy forms not accepting fields in UpdateView: .|as_crispy_field got passed an invalid or inexistent field
I need some help trouble shooting. So my problem is that the update view seems to work fine when I set field = '__all__' but when I try to specify the fields, then it provokes this error: |as_crispy_field got passed an invalid or inexistent field I'm not sure why this is happening views.py class FooUpdate(UpdateView): model = Foo fields = ['bar'] def get_success_url(self): return reverse('Foo_list', kwargs={'pk': self.object.bar.id}) foo_form.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.bar|as_crispy_field }} </form> -
Django Heroku, ValidationError at /admin ['“admin” is not a valid UUID.']
When trying to access the admin page on my Heroku deployment I keep getting this error. ValidationError at /admin ['“admin” is not a valid UUID.'] It seems to be redirecting me to a different view that uses a slug in the url, setting the slug to 'admin'. This only happens on the Heroku deployment. I think I may need to define 'admin/' in urls.py but i'm not sure how. urls.py urlpatterns = [ path('', views.homeView, name='home'), path('profile/', views.profileView, name='profile'), path('game/', views.gameView, name='game'), path('login/', views.loginView, name='login'), path('logout/', views.logoutView, name='logout'), path('register/', views.registerView, name='register'), path('info/', views.infoView, name='info'), path('mygame1v1/', views.mygame1v1View, name='mygame1v1'), path('mygameteamplay/', views.mygameteamplayView, name='mygameteamplay'), path('mygameffa/', views.mygameffaView, name='mygameffa'), path('<slug:slug>', views.gamepageView, name='gamepage') ] views.py (the view being redirected to) @login_required(login_url='/login/') def gamepageView(request, slug): game = OneVsOneGame.objects.get(player1=request.user, gameid=slug) -
HTTP GET returns undefined or everything in Ionic with Django REST filters
I'm working on an app with ionic that consumes an API built with Django REST. I have two views where I set the REST filters, but when I try to do an HTTP GET request on the ionic App, the "Residente" view returns "undefined" and the "Vigilante" view doesn't respect the filtering. I'm not sure what's going on. Here are my Django views class ResidenteView(viewsets.ModelViewSet): """ Obtiene todos los residentes existentes """ queryset = Residente.objects.all() serializer_class = ResidenteSerializer filterset_fields = ('telefono', 'codigo_acceso') class VigilanteView(viewsets.ModelViewSet): """ Obtiene todos los vigilantes existentes """ queryset = Vigilante.objects.all() serializer_class = VigilanteSerializer filterset_fields = ('usuario', 'password') Here is the code of the http requests getResidente(phone: string, code: string) { return this.http.get( this.constants.API_URL + "residentes", { telefono: phone, codigo_acceso: code }, {} ); } getVigilante(user: string, password: string) { return this.http.get( this.constants.API_URL + "vigilantes", { usuario: user, password: password }, {} ); } -
DRF url doesnt work when i add parameters
i created this API to retrive session_data based on session_key from the table django_session. i get the requested behavior with the session_key as a static field, like in the below code and this screenshot #urls.py path('session_data/',views.get_session_data,name='session_data'), #views.py @api_view(['GET'],) def get_session_data(request): session_key='pirxxzoh3rifjqch403ro8nfmkzmg972' response_content=decode_session_data(session_key) return JsonResponse(response_content,safe=False) once i change my code by adding a paramter str:session_key to urls.py and to the get_session_data, i get 404 Not found response. here is the code: @api_view(['GET'],) def get_session_data(request, session_key): #session_key='pirxxzoh3rifjqch403ro8nfmkzmg972' response_content=decode_session_data(session_key) return JsonResponse(response_content,safe=False) and for urls.py i tried both and it didnt work. path('session_data/<str:session_key>',views.get_session_data,name='session_data'), path('session_data/<str:session_key/>',views.get_session_data,name='session_data'), first_error POSTMAN_ERROR another_error thanks in advance. -
Django friend feed view
I have a custom user model extended with a one to one relationship to a Profile model, I also have a Post model. I want to create an attribute inside of Profile to store Posts of the users friends to make a recent updates feed. However I am struggling with what attribute or type of data storage to use (idk what to call it). Can anyone help? The line of code relevant is bolded in the code below. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name = 'profile', on_delete = models.CASCADE) image = models.ImageField(default = 'Default.png', upload_to = 'Profile_pics') slug = AutoSlugField(populate_from = 'user') bio = models.CharField(max_length = 255, blank = True) relationship = models.ManyToManyField('Profile', blank = True) **feed_posts = ArrayField(blank = True, default = list)** -
Django Radio buttons customize with bootstrap 4
I'm building a site in Django 2.2.13, and I need to seriously customize some radio buttons from RadioSelect in Django, here's the expected result above the current output: And here is the code in forms.py: gender = forms.MultipleChoiceField( required=True, widget=forms.RadioSelect, choices=GENDER_CHOICES ) Now in the HTML template: <div class="form-group"> <label><h4>Soy / Somos...</h4></label> <br> <div class="container"> <div class="row"> <label class="form-check form-check-inline col-5 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option1"> <span class="form-check-label"><i class="fas fa-mars fa-2x"></i><h6>Hombre</h6></span> </label> <label class="form-check form-check-inline col-5 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus fa-2x"></i><h6>Mujer</h6></span> </label> <label class="form-check form-check-inline col-10 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus-mars fa-2x"></i><h6>Otro(s)</h6></span> </label> <label class="form-check form-check-inline col-10 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus-mars fa-2x"></i><h6>Mixto</h6></span> </label> </div> </div> </div> <!-- form-group end.// --> {{ form.gender }} <hr> I'd really appreciate your help!! -
How to make donation buttons to different non-profits?
I would like to make an website where people could come and place a small donation to a non-profit of choice. Then the site would rank the givers and the organizations based on amount. Like here when people answer questions and so on. Instead of shouting at a sports game, users could make their favorite organization 'win'. After searching for donate-buttons to implement I realized there isn't any. No API's either. It would be awesome to have a donate-to-favorite-org button that looks like buy-me-a-coffee button. How could this be done in a way that no one could tamper with the money given and at the same time make the entire process transparent? I would like to use Django as a back-end. Thanks! -
How do I post the first value of a query set in HTML?
Hey guys I need to post the first value of a query set in HTML. Currently, I'm iterating through the entire query site and printing out every match but I don't want that. I'm using Django and I use the objects.get() filter which I thought only grabs one record but it is grabbing multiple. I just want it to grab the category they were just in so after they make a post, they can easily return back to that categories forum page. How do I print it out in HTML or how do I do the Django query to only get one record so I can easily just display that in HTML? Thanks! HTML: {% for query in queries %} <h4>Return to the <a href="/movies">{{query.category}}</a> Forum</h4> {% endfor %} views.py: query = NewPost.objects.get(category = category) return render(request, "network/posted.html", {"queries": query}) -
How to wait for the get request to finish in React?
I'm new to react and need to represent a JSON array in a table. The format of the array is [{"transaction_amount": 39.98, "transaction_date": 2020}, {...}]. This works when I assign this fixed data to a constant but if a request it from props, it isn't rendered. The below code doesn't work: <App transactions={this.state.transactions} /> const App = props => { const data = props.transactions; const columns = [ { title: "#", data: "id" }, { title: "Transaction Amount", data: "transaction_amount" }, { title: "Transaction Date", data: "transaction_date" }, ]; return ( <> <h5 className="mt-2 mb-4 text-center">Recent Transactions</h5> <DataTable data={data} columns={columns} /> </> ); }; but if I replace data with: const data = [{"transaction_amount": 39.98, "transaction_date": 2020}, {...}] then everything works fine. I'm guessing that the error is that the first time the page is rendered, props.transactions is empty. How can I fix that? This is the function for the get request: load() { axios.get('http://127.0.0.1:8000/api/payments?type=company',{ headers: {'Authorization': 'Token ' + sessionStorage.getItem('token')} }) .then(res => { this.setState({failed:false}); setTimeout(() => { this.setState({ transactions: res.data, loading: false }); }, 500) }) } -
max-aspect-ratio or -webkit-fill-available not working correctly on IOS14
So I'v been working on this web project, the login and register page have a bunch of content in a div with class "maincontainer" that I'm forcing to have 9/16 aspect ratio. Everything has been working great so far, I'v tried multiple devices/browsers. But there is one that just won't go, my friends iphone 11 running ios 14. The problems exists when he is using chrome and safari. Below pictures of the pages where I have added a border to mark the "maincontainer" div. This is who it looks almost everywhere: Iphone se good: PC good: And this is who it looks on the Iphone 11: And this is the CSS code that controls the main container: .maincontainer{ border: 1px green solid; align-content: center; text-align: center; min-height: 100vh; min-height: -webkit-fill-available; width: calc((100vh/16)*9); margin: 0 auto; font-size: calc((100vh/50)*(9/16)); } @media (max-aspect-ratio: 9/16) { .maincontainer { width: 100vw; min-height: calc(100vw*16/9); margin: 0 auto; padding-top: calc((100vh - (100vw*16/9))/2); font-size: calc(100vw/50); } } And the body and main: body{ overflow: hidden; height: 100vh; height: -webkit-fill-available; width: 100vw; margin: 0; padding: 0; min-height: 100vh; background: linear-gradient(0deg, rgba(253, 76, 113, 0.1) 0%, rgba(255,255,255,0) 13%), url("images/background_highres_dark.png"); background-repeat: no-repeat; background-position: center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: … -
Get Direct URL for uploads in search - Wagtail
I have customized my search to look at images and documents as part of that search. This is working fine. However I am not sure how to get the URL to the uploaded images/documents that are returned. Ideally there would be a link to download/display in browser. I am ok with the ../media/images/xxx url. But I can't seem to figure out how to get that data in the template. Thoughts? Search is performed by this. # Search if search_query: results = [] page_results = Page.objects.live().search(search_query) if page_results: results.append({'page': page_results}) doc_results = Document.objects.all().search(search_query) if doc_results: results.append({'docs': doc_results}) img_results = Image.objects.all().search(search_query) if img_results: results.append({'image': img_results}) search_results = list(chain(page_results, doc_results, img_results)) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() And the html looks like this {% if search_results %} {{ count }} results found. {% for result in search_results %} {% for k, v in result.items %} {% if k == 'page' %} {% for item in v %} <p> <h4><a href="{% pageurl item %}">{{ item }}</a></h4> Type: Article<br> Author: {{ item.specific.owner.get_full_name }}<br> Publish Date: {{ item.specific.last_published_at}} </p> {% endfor %} {% elif k == 'docs' %} {% for item in v %} <p> <h4><a href="">{{ item.title }}</a></h4> Type: Document<br> … -
KEY ERROR on self.cleaned_data.get('file')
I'm getting a key error while I'm trying to validate a simple form in Django: I've tried accessing the file name using: all_clean_data['file'] self.cleaned_data.get('file') self.cleaned_data['file'] To no avail. If i'm accessing as a key, I'm getting key error, if I'm using the get method I get None. Can you please tell my what I'm doing wrong? class UploadForm(forms.Form): url_cell_start = forms.IntegerField() url_cell_end = forms.IntegerField() write_cell_start = forms.IntegerField() write_cell_end = forms.IntegerField() file = forms.FileField() def clean(self): all_clean_data = super(UploadForm, self).clean() url_c_start = all_clean_data['url_cell_start'] url_c_end = all_clean_data['url_cell_end'] write_c_start = all_clean_data['write_cell_start'] write_c_end = all_clean_data['write_cell_end'] xl_file = all_clean_data["file"] extension = os.path.splitext(xl_file.name)[1] VALID_EXTENSION = '.xlsx' if extension.lowercase != VALID_EXTENSION: self.add_error('file', 'The file has to be .XLSX') if (url_c_start is None) or not (url_c_start > 0): self.add_error('url_cell_start', 'The URL column needs to be a number grater than zero.') if (url_c_end is None) or not (url_c_start > 0): self.add_error('url_cell_end', 'The URL column needs to be a number grater than zero.') else: if url_c_start is not None: if url_c_end <= url_c_start: self.add_error('url_cell_end', 'The URL-End column need to be a number grater or equal than URL Start') if (write_c_start is None) or not (write_c_start > 0): self.add_error('write_cell_start', 'The URL column needs to be a number grater than zero.') else: … -
Cannot Operate on a closed Database, django, python manage.py dumpdata
Trying to upload mass data to a json using python manage.py dumpdata > mydb.json i am getting this error CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u2005' in position 120: character maps to Exception ignored in: <generator object cursor_iter at 0x000001A9F7FB96D0> Traceback (most recent call last): File "C:\Users\schaefer\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1609, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. Been stuck on this for a while any help appreciated. -
Can a POST to Django REST Framework backend trigger an update of the frontend through Django Channels?
Background: I am creating a chat app using Django Channels that is the pilot for a more complicated app down the road that will need real-time data updates. Right now, the backend for the chat app is set up with Channels and Django REST Framework. When the chat app is opened, a websocket is created and messages are sent through the websocket, as any other basic chat app does. Also, when a message is sent, the message is posted to the REST framework to store the message in the database. Question: This complicated app that I will be creating has other resources that will be posting data to the Django REST Framework, and this data needs to be shown on the front end in real-time. My idea for this is when the REST framework gets a POST request from one of the resources, the data from the POST request gets sent as a message through the websocket so the data gets updated on the frontend. Is there a way to do this? I have been struggling finding resources on this.