Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configuring import errors while installing the project
I am installing the Django==1.9.1 project of the former team (I am newcomer) to my server it runs on Centos7. I did as I usually do: installed all the required things and run: pip install -r requrements.txt Then I run the following code: python manage.py makemigrations But I am receiving the following error ImportError: No module name insurance.mixins insurance.mixins is my library. I checked and it is where it should be. What can I do to fix this! -
Django Rest API - ProgrammingError relation 'core_donation' does not exist
Here is a link to my github repo: https://github.com/hertweckhr1/api_foodcycle My user endpoints work great. However when I try to reach my endpoint localhost:8000/api/donation/donations, I get back the error: enter image description here I have tried makemigrations donation and migrate several times. It says my migrations are up to date. Other posts similar to this, I have not been able to find a solution that works for me. Thanks in advance! -
Django- How to get my current location in django
I want to get my current location in django so that I can compare the distance with my location and other city. lat1, lon1 = origin #current location lat2, lon2 = destination #location of other city Further I want to compare between these two for a distance. I have destination lat and long but looking for current lat and long -
Using selenium script to test URL but after browser opens, it does not point to the requested URL
I am following this tutorial to learn more about Test-Driven Development with Django but have hit a snag. In tutorial we are asked to use the following code which, when run, opens up my Firefox browser and dircts to the URL (http://localhost:8000). from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title When run (using PyCharm), the browser opens with no issue but does not direct to the URL and the address bar remains blank. If I manually type in the URL it shows what should appear. After some searching the only real results I found were that there were compatibility issues but after updating everything I am still encountering the error. Does anyone have any suggestions as to resources to help solve the issue or maybe know a solution? Thank you for your time. -
SMTPSenderRefused at /password-reset/ (530, b'5.5.1 Authentication Required)
I set a gmail account to send emails to reset password. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('Email_User') EMAIL_HOST_PASSWORD = os.environ.get('Email_Password') I already turned on lower access from app. I managed to receive the email in my another gmail account by testing locally. But when I tested it in website, I GOT this error. And I also got an alert email said Someone just used your password to try to sign in to your account from a non-Google app, and it was blocked. I wonder is there another way to change settings to bypass this issue? -
Difference between instantiating models by manager and model-name in Django
When I instantiate the model, I usually used the manager, e.g. user = User.objects.create_objects(name='Tom', age='25') but, sometime I can also see the code like, user = User(name='Tom', age='25') Are these two identical codes? -
Trying to pass a string for querying through Django Rest Framework urls
I have a django project and I am using Django Rest Frameowkr. I setup up a model, serializer, view, and url for a users model. I have the urls file. I want to passing in something like a username when the api url is called. I currently have it setup to have a primary key so when I enter a primary key it works. I want to switch it to username. I also want the serializer query to return the user object iwth the usename I pass in. I am using Djangos standard User object from django.contrib.auth.models Here is the code I have Urls.py from django.urls import path from django.contrib.auth.models import User from .views import UserListView, UserDetailsView from .views import ProfileListView, ProfileDetailsView from .views import RoleListView, RoleDetailsView urlpatterns = [ path('user/', UserListView.as_view()), path('user/<pk>', UserDetailsView.as_view()), ] serializer.py file from rest_framework import serializers from django.contrib.auth.models import User from users.models import Profile, Role class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'last_login') Views.py file from rest_framework.generics import ListAPIView, RetrieveAPIView from django.contrib.auth.models import User from users.models import Profile, Role from .serializers import UserSerializer, ProfileSerializer, RoleSerializer class UserListView(ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetailsView(RetrieveAPIView): queryset = User.objects.all() … -
Django app: "Docker Container does not have a com.docker.compose.container-number label"
The exact error I'm getting is: ValueError: Container e3efba4d793f does not have a com.docker.compose.container-number label I'm not sure what is going on here. I'm running from a valid, stable branch. I'm able to run the app fine using "docker-compose -f docker-local.yml up." But when I try to run the test suite using "docker-compose -f docker-local.yml run web python3 manage.py test" I get the error that I mentioned above. My configuration hasn't changed or anything. I have tried reinstalling docker (on mac) and rebuilding the container. Thanks for the help! -
How to add a condition to form valid in django
Intro: I am creating a events app, I want the user to choose a date between 3 days from today to a maximum of 30 days from today class CreateEvent(IsVerifiedMixin, CreateView): model = Event form_class = EventForm template_name = 'event/event_form.html' def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) event = self.object today = datetime.date.today() user = self.request.user if today + datetime.timedelta(days=3) <= event.date <= today + datetime.timedelta(days=30): event.user = self.request.user event.initial_stock = event.stock slug = self.kwargs['slug'] event.save() else: #I know the below line of code is wrong. How do I fix this messages.error(self.request, "The event date has to be equal or more than 3 days away and less than 30 days") return super().form_valid(form) The above gives me a IntegrityError if the date is off if the date is correct the object is created. I just want to get a form error and the form to not go to the next page -
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 …