Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fitting mapbox and div inside a content-section
I am following this mapbox example (https://www.mapbox.com/help/building-a-store-locator/) and trying to fit it inside a Django web app. I believe my problem is in base.html because in the Mapbox tutorial they do not have a navbar or use template inheritance. base.html may be causing problems because it uses content from Home.html. In my screen shot you can see that the map and sidebar div do not fill the content-section div height wise. The map also only takes up half of the div it is inside of. I have tried many times to figure out the problem but cannot get it. base.html {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <!-- Bootstrap CSS, and other meta html --> </head> <body> <header class="site-header"> <!-- header for website containing navbar config --> </header> <main role="main" class="container"> <div class="row"> <div class="col-md" align="center"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </div> </div> </main> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> Home.html {% extends "geotracker/base.html" %} {% load static %} {% block content %} <body> <div class="content-section"> <div class='sidebar'> <div class='heading'> <h1>Our locations</h1> </div> … -
how to solve django with mysql error in inserting
i am new to django when i create models for mysql the foriegn key constraints always returing error enter image description here the model is class AirPort(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=100) def __str__(self): return f"{self.id} - CODE =>{self.code} :: CITY=> {self.city}" class Flight(models.Model): orgin_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="dep") dest_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="arrival") duration = models.IntegerField() def __str__(self): return f"{self.id} - {self.orgin} TO {self.dest} will take {self.duration} minutes" and the shell output is a=Flight(orgin_id=1,dest_id=2,duration=120) Traceback (most recent call last): File "", line 1, in File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/base.py", line 467, in init _setattr(self, field.name, rel_obj) File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 210, in set self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "1": "Flight.orgin_id" must be a "AirPort" instance. -
Django - SocketIO - NodeJS - Redis
I would like to integrate Socketio django redis and nodejs. My problem is that i dont know how to make a room specific to two logged in users. Say, For example user A is logged in and user B logs in after 20 minutes, User B should automatically join the room with user A when he clicks on user A's chat. -
Error Using BeautifulSoup Script Executing on Droplet
I have a beautifulsoup script which runs perfectly on my local machine as a Django custom command. However, when I execute the same script as a custom command on my ocean droplet, I get the following nonetype error: AttributeError: 'NoneType' object has no attribute 'prettify' I'm not sure why this script would work on my machine but not on the droplet. As far as I can see I have the same versions of python and django running. heading = soup.find('h1',class_="gem-c-title__text gem-c-title__text--long") heading = heading.prettify() d['heading'] = heading What am I missing? -
Execute queries on AWS RDS MySQL database instance via SSH
I have a scenario where I cannot directly access the application database even though I know the host/port/password/user (due to some security groups which I can't change). I can, however, connect to the application instance via ssh: Now I wanted to somehow execute mysql commands on the database instance. I can't seem to understand how. -
changing a field in the model when retrieving the detail object in Django rest framework
I have a model as follows: class PPost(models.Model): owner = models.ForeignKey( get_user_model(), related_name='posts4thisowner', on_delete=models.CASCADE) furnished = models.BooleanField(verbose_name="Is Furnished", default=False,null=True,blank=True) description = models.TextField(verbose_name="Description", max_length=500, blank=True, null=True) viewnum=models.IntegerField(verbose_name="view num", default=0) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('timestamp',) and my detail view is as like this: class PPostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = PPost.objects.all() serializer_class = PPostSerializer name = 'ppost-detail' permission_classes = ( permissions.IsAuthenticatedOrReadOnly, custompermission.IsCurrentUserOwnerOrReadOnly, ) which will be used in the following url: urlpatterns = [ ... path('<int:pk>', views.PPostDetail.as_view(), name=views.PPostDetail.name), ] now I need to be able to increase viewnum,one of the fields in the model representing viewing number of the a post to be increased by one whenever the request.GET is called; I was wondering how can I achieve this in my view. Thanks, -
How to use an aggregate in a case statement in Django
I am trying to use an aggregated column in a case statement in Django and I am having no luck getting Django to accept it. The code is to return a list of people who have played a game, the number of times they have played the game and their total score. The list is sorted by total score descending. However, the game has a minimum number of plays in order to qualify. Players without sufficient plays are listed at the bottom. For example: Player Total Plays Jill 109 10 Sam 92 11 Jack 45 9 Sue 50 3 Sue is fourth in the list because her number of plays (3) is less than the minimum (5). The relevant models and function are: class Player(models.Model): name = models.CharField() class Game(models.Model): name = models.CharField() min_plays = models.IntegerField(default=1) class Play(models.Model): game = models.ForeignKey(Game) class Score(models.Model): play = models.ForeignKey(Play) player = models.ForeignKey(Player) score = models.IntegerField() def game_standings(game): query = Player.objects.filter(score__play__game_id=game.id) query = query.annotate(plays=Count('score', filter=Q(score__play__game_id=self.id))) query = query.annotate(total_score=Sum('score', filter=Q(score__play__game_id=self.id))) query = query.annotate(sufficient=Case(When(plays__ge=game.minimum_plays, then=1), default=0) query = query.order_by('-sufficient', '-total_score', 'plays') When the last annotate method is hit, a "Unsupported lookup 'ge' for IntegerField or join on the field not permitted" error is reported. I tried … -
I have a website running on local server ... need help making it public
Note: The ip addresses given are not the exact addresses. They are just for examples I have a website built on flask running on a linux server that is using the internal ip address and a specific port... 192.168.10.10:1001. I know that the works on other computers on the same wifi. How can I make the ip address public so that I can access the website without the wifi (outside network)? I know my the external ip address of the server... 100.250.250.25. I have set up port forwarding so that I can 'access' my server from outside the network... 192.168.10.10:1000. I have accessed the server using the port forwarding but again it was on the same network. (Extra Question) Is that enough to access my server outside the network (or even using 100.250.250.25:1000)? This applies to django as well because I have websites with django that I would like to use my server as well in the future. (Hopefully 192.168.10.10:1002). -
Django Rest Framework Filter related model by lookup_field (uuid) in DRF instead of pk
I have two django models that are related. Let's call these two models book and author. For simplification let's assume it's a one to one relation. I am using the Django Rest Framework lookup_field to make the basic api calls, using uuid instead of pk as shown here. https://www.django-rest-framework.org/api-guide/generic-views/ so The API calls I have are /books/e56c231c-0a11-48fa-ab6a-dcdae0a53620/ and /authors/e56c231c-0a11-48fa-ab6a-dcdae0a53620/ instead of /books/1/ and /authors/1/ where 1 is the pk. This works great so far. However Now I am implementing the DRF filtering feature. And the filtering by default works as follows. /books?author=1 This works great, but I don't want the pks to be exposed. I would like the filtering to be working like this /books?author=e56c231c-0a11-48fa-ab6a-dcdae0a53620/ I was able to get it working by doing /books?author__uuid=e56c231c-0a11-48fa-ab6a-dcdae0a53620/ but this is not what I am looking for. I would really like the UI generated by the drf filters to include the UUID as the values as well, instead of pk. Thank you -
Perform action on background django
If a new data is entered in by a user or someone else, what I want my app to do is to get that data from the queue, perform a background action on its own, then remove and/or leave that data alone and move onto the next. I shouldn't be touching anything. I want to set a task, then want django to do its own work without any intervention. In this case, would django-background-tasks be the best job for this? What are some other similar packages that I should be looking at? -
django how to set background colour in html based on context
I am trying to change the background colour in a django project based on some information sent via the context body base { padding:$base-spacing-unit; font-family:'Source Sans Pro', sans-serif; margin:0; ext-align:center; } body alert { background-color: #FCFF33; padding:$base-spacing-unit; font-family:'Source Sans Pro', sans-serif; margin:0; ext-align:center; } def check_alert() -> bool: return ... def index(request): template = 'proj/index.html' ... context['alert'] = check_alert() return render(request, template, context) How can I select the body class in the proj.html based on the field alert in html looks like {% load static %} <html> <link rel="stylesheet" href="{% static 'css/proj.css' %}" /> <body class="base"> <-- I tried manually switching class here, but it appears body doesnt take that. If I do this it doesnt take the base config ... </body> </html> -
Is there a way to plug a seperate instance of Django model objects into different containers without going through a for loop in the template?
I've created a simple Project model with just a title and summary field. I want to put unique instances of this model into different containers because I don't know enough about CSS to make a flexible iterable container. Is there a way to do this in the template outside of declaring unique context variables for each instance of the object? I put a for loop here to show where I would put it. Do I need to make four unique context dictionaries each with its own unique loop? <section class="box features"> <h2 class="major"><span>Project Portfolio</span></h2> <div> <div class="row"> <div class="col-3 col-6-medium col-12-small"> <!-- Feature --> <section class="box feature"> <a href="#" class="image featured"><img src="images/pic01.jpg" alt="" /></a> <h3><a href="#">A Subheading</a></h3> <p> Phasellus quam turpis, feugiat sit amet ornare in, a hendrerit in lectus dolore. Praesent semper mod quis eget sed etiam eu ante risus. </p> </section> </div> <div class="col-3 col-6-medium col-12-small"> <!-- Feature --> <section class="box feature"> <a href="#" class="image featured"><img src="images/pic02.jpg" alt="" /></a> <h3><a href="#">Another Subheading</a></h3> {% for project in projects %} <p>{{ project.summary }}</p> {% endfor %} </section> </div> <div class="col-3 col-6-medium col-12-small"> -
Celery change content_encoding
I want make apply_async task with celery, but my argument is a file with encoding in ISO-8859-1, but celery serializer data with UTF-8. I recive the file from one url using this code: import urllib data = urllib.request.urlopen(url) content = data.read() update_task.apply_async([content]) When I try call the method I have this erro: UnicodeDecodeError: 'utf-8' codec can't decode byte -
Unable to connect to containerized Django web server while running Pycharm remote debugging session
I have a Django application running in a Docker-compose configuration and I would like to be able interactively debug it from Pycharm. I first tried and failed to set up debugging using Pycharm's built-in Docker Compose configuration (result: the application runs and is accessible, but debugging is not available, I suspect because of a known bug where the debugger fails to connect if the entrypoint script takes too long to return). I am now attempting to set up debugging using remote debugging with pydevd, roughly following the instructions contained here and summarized below: Add a Python Remote Debugger run configuration in Pycharm In my Django application, copy pycharm-debug-py3k.egg to the root directory, add it to the path, import pydevd & initialize it in my app code like so: import sys sys.path.append("pycharm-debug-py3k.egg") import pydevd pydevd.settrace('ip.address.of.my.machine', port=4444) Start the debugger in Pycharm Start my application with docker-compose up Press the Play/Resume program button in the debugger The result of this is that in Pycharm, the debugger console reports that a connection is active ("Connected to pydev debugger"). The debugger tab shows the expected variables and values present in the file I added the code snippet to. No errors appear in the container … -
Django: Subclassing UserCreationForm: doesn't have get_user() method?
I created a custom user in Django by subclassing the normal User model. This user's only difference is that it doesn't have a username. Now, I'm trying to use the built in Django UserCreationForms to log users in. I subclassed UserCreationForm and created SignUpForm, which doesn't have a username field. My control flow is as follows: 1) Check to see if input form is valid 2) if it is, get the user out of the form 3) save the form (thereby saving the user) 4) log the user in However, when I try to get a user out of the SignUpForm instance, it throws me this error: AttributeError at /user/signup 'SignUpForm' object has no attribute 'get_user' I don't understand this because SignUpForm is directly subclassed from UserCreationForm, which implements the get_user() method. My code for views.py is below: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django.db import models User = get_user_model() # Create your views here. class SignUpForm(UserCreationForm): email = models.EmailField(max_length=254, help_text='Required. Enter a valid email address.') username = None class Meta: model = User fields = ('email', 'password1', 'password2',) def signup(request): if … -
JavaScript showChange() to dynamically change value in django template seems to have no effect. What am I doing wrong?
I have a Django template where I am displaying products from a database along with a dropdown menu containing various conditions for the product. I have a static price for the item, that I would like to change based on the condition currently selected without loading the page. The dropdown menu was generated via django forms. I expect that when I choose the condition from the menu, the price would change to the value of whichever option I choose, but nothing is happening. What am I doing wrong? Django generated form <select name="condition" id="id_condition"> <option value="NM / LP">Near Mint / Lightly Played</option> <option value="MP">Moderately Played</option> <option value="HP">Heavily Played</option> <option value="Damaged">Damaged</option> <option value="Unopened">Unopened</option> Script at the bottom of my template <script> function showChange(){ var selected_material = document.getElementById("id_condition").value; document.getElementById("price_id").innerText = selected_material; } </script> template {% for product, card_price in products %} <div style="margin-bottom: 3%;" class="col-sm-3"> <div class=col-sm-12> <form action="{% url 'add_to_cart' product.id %}" method="post" target="submit-frame">{% csrf_token %} <div style="" class="row" id=""> <img class="img-responsive center-block" src="https://someImage.jpg"> </div> <div style="" class="row" id=""> <center> {{form|crispy}} <input id='card_price' type="hidden" name="card_price" min={{card_price}} max={{card_price}} value={{card_price}}> <div class="col-sm-3"></div> <div class="col-sm-2"> <b style="">&nbsp;$<span id="price_id">{{card_price|floatformat:2}}</span></b> </div> <div class="col-sm-2"> <input style="color: black;" size="2" id='qtyBox' type="number" name="quantity" min="1" max="8"> </div> <div class="col-sm-1"> <button … -
Django: using enums for multiple language tables and choices
How can I use Enums in Django to quickly create list of choices for enable more choices than pair tuples, e.g. 4 or 5 columns a quick method to convert enums to tuples for enable multiple languages in a drop down from enums, choice list is recycled for other parts of the project when tables are needede -
How do I have a Boolean True False form in Django for a list of models?
Whats the best way to have a boolean HTML form for a list of models? Lets say this is my model: class Comparison(model): id = models.AutoField(primary_key=True) score = models.IntegerField(blank=True, null=True) is_matching = models.NullBooleanField() And my view: def display(request): comparisons = Comparison.objects.all() context = { 'comparisons': comparisons } return render(request, 'display_comparisons.html', context) And my template: <table> {% for comparison in comparisons %} <tr> <td> Here is some True / False button that should update is_matching </td> </tr> {% endfor %} </table> Now ideally, if I click the True button or the False button, my comparison model will update. Whats the best way to do this? -
How limit choices in a ManyToMany field depending on wich user is logged?
I'd like the view only show the "personajes" that were created by the current user. If I i'm not understanding wrong, what I have to do is filter the choices, depending who is the current user logged in, before the form render. I guess that what I have to edit is the queryset argument in ModelChoiceField(**kwargs) but I don't know where I have to do this. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Autor(models.Model): nombre = models.CharField(max_length=40) apellido = models.CharField(max_length=40) usuario = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "%s %s" % (self.nombre, self.apellido) class Personaje(models.Model): nombre = models.CharField(max_length=40) personalidad = models.CharField(max_length=20) creador = models.ForeignKey(Autor, on_delete=models.CASCADE) def __str__(self): return "nombre: %s Creador: %s" % (self.nombre, self.creador) class Historia(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) personajes = models.ManyToManyField(Personaje) desarrollo = models.TextField() views.py I'm not catching the request.user.id yet by simplicity (I'm really stuck with the filter thing) I know how to do that, hardcoding the user id will be just fine. from django.shortcuts import render from django.views.generic import CreateView from core.models import Historia # Create your views here. class CrearHistoria(CreateView): model = Historia fields = ['personajes', 'desarrollo'] template_name = 'core/crear_historia.html' The current result: What I … -
Crispy forms and bootstrap styles
I am trying to use UserCreationForm in django in users model for registration, my forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and my users/views.py is : from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) and my html is : {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> {% endblock content %} i added crispy in settings.py installed app and i CRISPY_TEMPLATE_PACK = 'bootstrap4' and I added the latest bootstrap 4.2 CDN in my styelsheet but my page still looks awful , any guide please and thanks in advance -
Filtering Dates :TypeError at / expected string or bytes-like object
I'm trying to make a filter based on dates for scheduled events. I want items that happened between 60 days ago and that are scheduled 60 days from now. So the start of the range is today - 60 days and the end of the range is today + 60 days. I haven't used Django in a long time and I don't know if this is a new issue with the current version and the auto_now and auto_add_now or if the issue is using DateField. I used DateField on the models because I don't care about the time and don't want this time fields added to the database. I want clean dates. Index.html <!DOCTYPE html> {% load static %} <title>Document</title> <body> <div id=form> <select name="Title" id="title_box"> {% for item in items %} <option value="{{item.name}}">{{item.name}}</option> {% endfor %} </select> </div> </body> </html> Models.py from __future__ import unicode_literals from django.db import migrations, models import datetime class Cycle(models.Model): name= models.CharField(max_length=255) start_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) I changed the field from DateField to DateTimeField and it made no difference, so I changed it back to DateField. Views.py from django.shortcuts import render, HttpResponse, redirect from .models import * … -
Python django html
I am with a doubt create the product class that has name, price, bar_code and the class of Sale that has product and price. In other words, by adding a new sale, she will select a product. How do I get the value of the selected product and add to the sale price? -
Cleaning date field returned to django view from ajax call
I have a date field that comes across in the data field of an ajax call. I can get the data just fine in my views.py dateJ = request.GET.get('date_joined_group') This is great, but when I try to throw it into my model it dies everytime. I need to 'clean' the data, I know my forms when I am just doing standard get post ops works and does this automagically. Is there a way I can invoke this automagic when not using form stuff but using the ajax call? I tried this: dateObj = datetime.datetime.strptime(str(dateJ), '%m-%d-%Y') Then in my model: grpProvInfo.date_joined_group = dateObj grpProvInfo.save() This worked, till I used the date picker on the form which put it in as 4/29/2009 So the slashes broke my 'slick fix', gotta be an easier way then trying to account for all the possibilities just not sure how to invoke it from a little def method I have for the ajax call in my python. -
Django models retrieve specific records daily
I have a django application that will retrieve and display 3 records (questions) to all users of the app during a 24hr window beginning at a specific time, say 11:00 daily. Preferably, I would like to randomise the list of records or just use the question id which autoincrements. There are more than 14,000 records. I can retrieve records from the db and randomly display those records. However, every http get request (refreshing browser window) retrieves different questions Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Questions(models.Model): question = models.CharField(max_length=254, blank=True, null=True) answer = models.CharField(max_length=254, blank=True, null=True) question_used = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render from django.views.generic import CreateView, View from .models import * from wallet.models import UserWallet class DailyDrawView(View): template_name = 'daily_draw/daily_draw.html' def get(self, request, *args, **kwargs): que_attempt = DailyDraw.objects.filter(user=request.user, is_active=True).last() question_objs = Questions.objects.all().order_by('?')[:3] points = WinnerPoint.objects.last().amount return render(request, self.template_name {'question_objs':question_objs, 'que_attempt':que_attempt, 'points':points }) At a particular time daily, retrieve 3 records. Display those records to all users throughout a 24hrs period. Update those 3 rows so that those same records are not displayed again. Rinse and repeat. -
Do I need a manager when creating and saving objects in Django?
I'm using Django with Python 3.7 and PyCharm. I'm following this tutorial for learning how to create model and save them into the database -- https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects . The tutorial refers to manager for retrieving objects, but not for setting them, so I'm confused as to why I get the below error Article.objects.create_article(main page, '/path', 'url', 10, 22) Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'Manager' object has no attribute 'create_article' when I'm trying to create and save an object. Below is how I define my object in my models.py file ... class Article(models.Model): mainpage = models.ForeignKey(MainPage, on_delete=models.CASCADE,) path = models.CharField(max_length=100) url = models.TextField time = models.DateTimeField(default=datetime.now) votes = models.IntegerField(default=0) comments = models.IntegerField(default=0) def __str__(self): return self.path @classmethod def create(cls, mainpage, path, url, votes, comments): article = cls(mainpage=mainpage,path=path,url=url,votes=votes,comments=comments) return article I'm sure I'm missing something really obvious, but I don't know what it is.