Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Plotly-Dash multiple users/browser tabs causing mixing of data on plots
I am creating an app in Django that uses Dash and Plotly components. To test some functionality, I dumbed the app down to a page that has a dropdown where a user chooses “latitude” or “longitude” and then the script calls an ISS location API that plots the latitude or longitude of the ISS depending on what the user chooses. This is a live plot that gets updated using dcc.Interval every 3 seconds. This works great, until I open two instances of the app in my browser. If the first browser tab has “latitude” and the second browser tab has “longitude” the plots will mix the data and bounce back and forth plotting both values. Has anybody ever run into this? I have been playing with clientside callbacks and some other things but I am not sure how to get it to not have this bug anymore. I will include the code and what the plot behavior looks like below. data = deque(maxlen=30) timeStamp = deque(maxlen=30) liveOut = DjangoDash("LiveOutput") liveOut.layout = html.Div([ dcc.Dropdown(id='graph-indicator', style={'display': 'block'}, options=[ {'label':"latitude", 'value':"latitude"}, {'label':"longitude", 'value':"longitude"}, ],), dcc.Graph(id='graph', style={'width':'49%', 'display': 'inline-block'}), html.Div(style={'width':'1%', 'display': 'inline-block'}), html.Div(id='hidden-div', style={'display':'none'}), dcc.Interval( id='graph-update', interval=3000, n_intervals=0 ), ]) @liveOut.callback( Output('hidden-div','value'), [Input('graph-indicator','value')],) def … -
Deploy a Django project to AWS EB using Docker and nginx
Currently, I try to deploy a Django project to AWS EB but I'm facing a lot of problems. I could dockerize the project and deploy it on the AWS elastic beanstalk. But when I try to access the site I always see: 502 Bad Gateway. Locally, the project runs smoothly. I am not really into nginx and I have no idea how to solve this problem. This is my project structure: Project structure This is my Dockerfile: # Creating image based on official python3 image FROM python:3 MAINTAINER Jaron Bardenhagen # Sets dumping log messages directly to stream instead of buffering ENV PYTHONUNBUFFERED 1 # Creating and putting configurations RUN mkdir /config ADD config/app /config/ # Installing all python dependencies RUN pip install -r /config/requirements.txt # Open port 8000 to outside world EXPOSE 8000 # When container starts, this script will be executed. # Note that it is NOT executed during building CMD ["sh", "/config/on-container-start.sh"] # Creating and putting application inside container # and setting it to working directory (meaning it is going to be default) RUN mkdir /app WORKDIR /app ADD app /app/ This is my docker-compose file: # File structure version version: '3' services: db: image: postgres environment: … -
Can't run django server in ATOM
I'm trying to run server in atom but I can't! https://i.stack.imgur.com/1OnMY.png -
Django rest framework, migrating from session authentication to token authentication
So this is a generic question, in our django project we have been using session authentication all along. Now for a few reasons, we are planning to move to token based authentication for our project. What are all the things that i should consider while doing this move? I know that we have to add rest_framework.authtoken to our installed apps and change the authentication in REST_FRAMEWORK in settings file. Are there any other steps that i should consider while making this move -
How do I display only some objects in django?
I have a basic blog app, where you can write blogs from the django admin panel. I want to display only ten blogs per page(on the public homepage) and then display the next ten blogs in the next page and so on and display a page number at the bottom of the page, like stackoverflow does on the questions page. It displays 15 questions and then shows which page you're currently on. I am new to django and don't know if any function is available for this purpose. I tried searching on google and stackoverflow, but cannot find any relevant answer. -
Django Model Manager Circular Import issues
Having looked at Django models - Circular-Import-Issue and several other issues reported: slightly different Still having no luck with the following: We have three models: User / Organisation / Actor all within the same app. The user model has the following attributes: class CustomUser(AbstractBaseUser, PermissionsMixin): """ Description: Class holding data about people. People can be members of organisations. Methods: """ id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField( max_length=75, help_text='Enter First Name', verbose_name="First Name" ) # GivenName: IfcLabel middle_name = models.CharField( max_length=75, help_text='Enter Middle Name', blank=True, verbose_name="Middle Names" ) # MiddleNames: IfcLabel actor = models.OneToOneField( Actor, on_delete=models.CASCADE, help_text="Actor ID", verbose_name='Actor ID', null=True, editable=False ) member_of = models.ManyToManyField( Actor, help_text="User is member of which department?", verbose_name='Organisation ID', related_name='user_organisation' ) The Organisation model has the following attributes: id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) identifier = models.CharField( max_length=10, verbose_name='Organisation Code', help_text='Organisation identifier', default='NULL', blank=True, null=True ) name = models.CharField( max_length=75, help_text='Organisation Name', verbose_name="Organisation Name") # actor = models.OneToOneField( actor.Actor, on_delete=models.CASCADE, help_text="Actor ID", verbose_name='Actor ID', null=True, editable=False, ) # Sets up the parent-child relationship between organisations, departments and sub-departments etc. # Departments are modelled as organisations, which have parent_organisation = models.ForeignKey( Actor, on_delete=models.CASCADE, null=True, blank=True, related_name='parent' ) and finally the Actor … -
How to change the existing autofiled id to custom Integer primary key in django - Sqlite3?
We didn't decide any primary key before creating the database and Django created a custom autoincrement primary key called 'id'. We have 20 tables with this primary key. Now, I want to migrate from this auto-increment 'id' primary key to a custom integer primary key without auto-increment. Also, I would like to keep the name of the new primary key as 'id' itself. What is the shortest and easier way of migrating without changing the existing id? Will this work? If I change the SQLite database (remove auto increment) CREATE TABLE "users" (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `name` varchar ( 5 ) NOT NULL, `place` varchar ( 5 ) NOT NULL); Add this line in my model id = models.BigIntegerField(primary_key=True) After this, I can use makemigrations and migrate ? DB used: SQLite3 Thank you in Advance. -
Is Django many to many really necessary?
I have been learning to use Django over the last year and Python is not my native programming language. Normally, when I want to create a many to many relationship, I would create 3 tables, one of which contained two foreign keys to each of the other two tables. For this reason, I find the Django manytomany field very unnatural. Does this many to many field create a third table in the database to store the relationship ? If this is the case, then using a many to many field will stop the class structure from directly representing the table structure. What I am wondering is if there is a reason I should be using this manytomany field or could I get away with using 3 classes to represent a many to many relationship ? Thanks Mark -
searching for encrypted data fields like email django
I am authenticating my user using django email and password . Now I have encrypted my email using pip packedge django-cryptography==1.0. and now when I authenticate user like self.user = authenticate( email='myemail@gmail.com', password='mypass') its giving error Unsupported lookup 'exact' for EncryptedEmailField or join on the field not permitted, perhaps you meant exact or iexact? Is there any work around for it ? Or any way to keep data in db encrypted and use it for authentication . -
Django Celery Task
views.py class ConfirmOrderView(View): def get(self,request): cart=Cart.objects.get(client=request.user.id) products_cart=CartProducts.objects.filter(cart=cart) total_price = sum([product_cart.product.price * product_cart.quantity for product_cart in products_cart]) return render(request, "Products/order.html",{"products_cart":products_cart, "total_price":total_price}) def post(self,request): email_task(request).delay() task.py @app.task def email_task(request): total_price = request.POST.get("totalprice") send_mail( "Total price of your purchases", f"Total price of your purchases is {total_price} zł", "radziszewski.aleksander@gmail.com", [f"{request.user.email}"], fail_silently=False) return render(request,"Products/check_email.html") And I 've got error "AttributeError: 'HttpResponse' object has no attribute 'delay'".Any ideas? -
Set-Cookie Firewall issue
I am a junior dev trying to understand a cookie problem that arose at work. Here is the situation: At the start of the day, all but one development servers failed to accept login via google AuthO. Upon inspection, this was due to cookie issues (Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure). I found the blocked cookie using Network tool, then added the arguments SameSite='None' and Secure to a set_cookie() function. This was part of Django middleware code that I believe was responsible for issuing a response to successful AuthO. One caveat is that it also has the param httpOnly=true. This fix worked; the error disappeared and I successfully received a session cookie. Today, however, I was told by devOps that the issue was caused by a 'nameserver being moved, causing a timeout', and that a 'firewall fix' resolved the problem. Please help me understand: 1. How does a firewall issue cause this cookie behavior? 2. Are there security concerns with my fix as I read that the Secure tag is noneffective if over HTTP? -
Django PasswordResetDoneView displayed but email not send
I use Django authentication and try to use a new email service. EVen if PasswordResetDoneView is well displayed and other email are sent (send_mail function), mail with link is never received How can it be exokaned and how to resolve this? I have use another eamil services like SendGrid and it works... -
I'm trying to deploy Django via Apache WSGI and It's not going well
I am losing hope with this, I've been trying for weeks but with no success. I'm trying to run a Django project on a windows server accessable via external HTTPS traffic. I've succesfully managed to get Django to serve over http interally using waitress on port 8000, all the static files work correctly and the app runs fine. However, when I try to then move it to Apache I just keep hitting dead end after dead end. I've got this in my Apache vhost.conf <VirtaulHost *:8000> ServerName localhost LoadFile "C:/python37/python37.dll" WSGIPassAuthorization On LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIScriptAlias / "C:/AZPortal/AZPortal/AZConsole/AZConsole/wsgi.py" WSGIPythonPath "C:/AZPortal/AZPortal/AZConsole/" <Directory "C:/AZPortal/AZPortal/AZConsole/AZConsole/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/AZPortal/AZPortal/AZConsole/staticfiles/" <Directory "C:/AZPortal/AZPortal/AZConsole/staticfiles/"> Require all granted </Directory> </Virtaulhost> As it stands, I just want to be able to see it being hosted by Apache, I'm sure I'd be able to work the rest out after that, but I can't even get that working, please, this is a desperate plea for any advice of help! -
How to access multiple files stored in a file field in django?
We can save multiple files in one filefield, using multiple attribute in HTML input tag and using request.FILES.getlist() and for loop in views. This works properly, but the question is: When we save several files in one filefield of an object, how can we access all of them in templates? I tried the same as the code below but it did not work: {% for foo in obj.filefield %} {{ foo }} {% endfor %} -
Django, accessing nested Many To Many field
I have the following models schema: class Site(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT, related_name=RelatedNames.ADDRESS, blank=True, null=True) account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name=RelatedNames.ACCOUNT_SITES) _type = models.IntegerField(choices=SiteTypeChoices.CHOICES) primary_email = models.EmailField(null=True, blank=True) objects = models.Manager() def __str__(self): return self.name def get_site_address(self): return str(self.location) class SiteScore(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name=RelatedNames.SITE_SCORES) date = models.DateTimeField(default=timezone.now) score = models.IntegerField(default=0) score_type = models.IntegerField(choices=SiteScoreChoices.CHOICES, null=True, blank=True) class CustomUser(AbstractUser) username = None email = models.EmailField(_(Fields.EMAIL_ADDRESS), unique=True) accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS) USERNAME_FIELD = Fields.EMAIL REQUIRED_FIELDS = [] I'm trying to filter out the site scores by date and by the user connected to the sites: worst_scores = SiteScore.objects.filter(date__date=today, site__users=self.request.user).order_by('-score') But this raises this error: The QuerySet value for an exact lookup must be limited to one result using slicing. -
django rest framework api endpoint to direct to foreignkey data
I have two models which are each in a different app. Stock model references Financials model through a foreignkey relationship as shown below. with the current Stock Viewset, also displayed below, I am able to access the individual stock through localhost:8000/stocks/aapl, but I would like to extend that url to include the financials foreign key data such as localhost:8000/stocks/aapl/financials/balance-sheet/. how can I do this ? Stock model class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) financials = models.OneToOneField( Financials, on_delete=models.CASCADE, default=None ) Financial Model class Financials(models.Model): # ticker = models.ForeignKey( # Stock, on_delete=models.CASCADE, related_name="balance_sheets" # ) balance_sheet = models.ForeignKey( BalanceSheet, on_delete=models.CASCADE, related_name="balance_sheets" ) income_statement = models.ForeignKey( IncomeStatement, on_delete=models.CASCADE, related_name="income_statements" ) cashflows_statement = models.ForeignKey( CashflowsStatement, on_delete=models.CASCADE, related_name="cashflows_statements", default=None, ) stocks.views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_url_kwarg = "ticker" lookup_field = "ticker__iexact" -
How to render template with context in a django backend api call?
I have a frontend react app... Now on clicking a button in frontend it will go through a server side rendering and the middleware will take the authorization token and fetch user info from api/me endpoint...then using that user info i will render user specific form... here is my front end-> <a href="apply-form/31">Apply Job</a> here is my middleware-> access_token = request.COOKIES.get("AccessToken") headers = { "Authorization":f"Bearer {access_token}", "Content-Type":"application/json" } r = requests.get(url='https://im/api/v1/me',headers=headers) json = r.json() request.META["user"] = json my view file is simple , just getting the request meta user data ...querying the user specific information from the database and rendering the template with context def index(request): user = request.META["user"] data = models.Post.objects.filter(user_id = user["id"]) return(request, "index.html", {"data": data}) the problem is that i dont want to fetch the authorization token from the cookies rather i want it from an api call in headers-> fetch("https://apply-form/31",{ headers: { "Content-type": "application/json", "Authorizaton" : "Bearer Token" } }) then the middleware will not have to fetch the token from the cookies but rather from the request.header["Authorization"] headers = { "Authorization":request.headers.get('Authorization'), "Content-Type":"application/json" } r = requests.get(url='https://im/api/v1/me',headers=headers) json = r.json() request.META["user"] = json but the problem is that if the view function turns in to a … -
How to identify generic relationship after model is passed to React
I've built a Django app with a React frontend. Now, I want to use generic relationships and not sure of a reliable way for my React app to identify which model the relationship is. I've considered : adding a new field to my model to keep track of the model type but this seems counter to the idea of generic relationships Looking at the fields of the object once it reaches my react app to determine what the model is. But this seems difficult to maintain as things grow. I use 100% Typescript in my React, so perhaps there is some way to leverage Typescript to help. What is a good way to identify different models in generic relationships once they reach the React app? -
How to pass percentage of two django db field as a template tag
I have two fields in my django db which called like and dislike. I want to pass I need to pass the average of these two values to the template to be used as the width of <div style="width:x%">. in views.py: def PostListView(request): posts = Post.objects.all() context['posts'] = posts return render(request, 'app/mytemplate.html', context) and in template: {% for post in posts %} <div class="ratings-css-top" style="width: {% widthratio post.like post.dislike 100 %}"> </div> {% endfor %} how to pass this average value of fields as a width? like % (like + dislike ) * 100 -
trying to make a carousel slider in django and trying to take picture from database then render on frontend
I am trying to make a carousel slider. Picture comes from the database and then render it on the frontend slider. But the picture is rendering but it is creating new slider and when i change to next slide then it shows the same picture. What to do?? My code is here... `{% for post in object_list %} <h2>{{ post.title }}</h2> </ul> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ post.image.url}}" class="d-block w-100" alt="{{ post.title }}"> </div> <div class="carousel-item"> <img src="{{ post.image.url }}" class="d-block w-100" alt="{{ post.title }}"> </div> <div class="carousel-item"> <img src="{{ post.image.url }}" class="d-block w-100" alt="{{ post.title }}"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endfor %} {% endblock %} ` -
Javascript incorrect output of datetime from rest API
I'm not getting the right time from my datetime field data when trying to fetch the data using fetch API. So here's the data from my database. See image: Now, my problem is when I'm trying to print the data using console.log it is giving me a wrong time. See image: Here's the field in my model: date_created = models.DateTimeField(auto_now=True, auto_created=True) Here's my serializer: class Meta: model = Message fields = [ 'date_created',] Here's also the settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Manila' USE_I18N = True USE_L10N = True USE_TZ = True I'm not sure where is the problem if it is with the timezone settings? Anyone had an experience of this? -
How to restrict user who can make a blog post
I am working on blog site and making it with django also came across https://www.youtube.com/watch?v=TAH01Iy5AuE this tutorial from codemy. In this tutorial he told a hacky way to do the restrict thing can anyone tell me the recommended way to do so -
How to set fields/model to readonly if one attribute is set to true in Django?
So, I got three classes: class User(...): #... other fields name = models.CharField() class Equipment(...): #... other fields inUse = models.Boolean(default=False) class Ticket(...): #... Other fields user = models.ForeignKey(...) equipment = models.ForeignKey(...) ended = models.Boolean(default=False) Now, when I create a new Ticket, the equipment "inUse" attribute changes to True, so I cannot give the same Equipment to more than one User. The thing is that when I set the Ticket to "ended" I'll still be able to change it to not "ended". I want not to be able to change that once I set the "ended" attribute of the Ticket to True. PS: I'm overriding the method save to make changes in the Equipment when setting up a new Ticket or changing it to "ended". -
What is the correct way to bring only the relationship on a Queryset (django)?
I have this models: class Thing(models.Model): thing_name = models.CharField(max_length=200) thing_stuff = models.SlugField(max_length=200, unique=True) class AllowedThing(models.Model): thing = models.ForeignKey( 'Thing', on_delete=models.PROTECT) foo = models.ForeignKey('Foo', on_delete=models.PROTECT) bar = models.ForeignKey(Bar, on_delete=models.PROTECT) class Meta: unique_together = (('thing', 'foo'),) and I would like to access "thing_name" and "thing_stuff" directly in the queryset objects, as in obj.thing_name instead of obj.thing.thing_name without having to do this qs = AllowedStuff.objects.all().annotate( thing_name=F('thing__thing_name') ).annotate( thing_stuff=db.F('thing_thing_stuff') ) -
Image not loading in apache web server
I made a django project with a raspberry pi and I tried loading it into apache2. I'm trying to stream images from the raspberry pi cam into the website but the images dont seem to be loading. The CSS and everything else looks like it working fine but the images arent loading. Heres what I get on my error log: [Tue Oct 13 13:22:48.910217 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] mod_wsgi (pid=520): Exception occurred processing WSGI script '/home/pi/dev/Rover/src/Rover/wsgi.py'. [Tue Oct 13 13:22:48.911093 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] Traceback (most recent call last): [Tue Oct 13 13:22:48.911339 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] File "/home/pi/dev/Rover/src/roverBase/views.py", line 27, in gen [Tue Oct 13 13:22:48.911388 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] frame = camera.get_frame() [Tue Oct 13 13:22:48.911481 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] File "/home/pi/dev/Rover/src/RoverLibs/CamWebInterface.py", line 24, in get_frame [Tue Oct 13 13:22:48.911528 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] ret, jpeg = cv2.imencode('.jpg', frame_flip) [Tue Oct 13 13:22:48.911688 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-p4wkaqpf/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:919: error: (-215:Assertion failed) !image.empty() in function 'imencode' [Tue Oct 13 13:22:48.911737 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] This is what my wsgi.py looks like: import os …