Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get django-private-chat package to work
I have installed django-private-chat package latest version (0.3.0) and followed the steps listed in the documentation: https://django-private-chat.readthedocs.io/en/latest/usage.html But I can't get it to work properly. I've started both servers and when I write something to the other user and hit Send button nothing happens. I get no erros in both consoles. There other steps that I should do ? -
calling url of main app to template of other app
I am trying to call a URL from main apps view function into child apps template This is my directory structure: App/ Main/ templates/ main/ index.html urls.py views.py Other/ templates/ other/ base.html urls.py views.py This is my urls.py from main app urlpatterns = [ path('', views.home, name="home"), path('admin/', admin.site.urls), path('other/', include('other.urls')), ] I am trying to call home page in base.html of other app on navbar like this Main App I am not calling the link in urls of other app. This is my view function in main views.py def home(request): return render(request, 'main/index.html') I have tried importing the home function in views of other app and then passing into urls of other app which makes url localhost:8000/other/home I want that url to stay as localhost:8000/ for main page whenever that link is clicked. -
React state wont update specific values
Hey so I am currently trying to get data from my backend, then modify it by going through the list and grabbing the corresponding image from the database. However, for some reason, only the variables returned by the initial get request seem to be updated in the state and 'image' which is basically appended to the fields stays as undefined. The strange thing is when I console log the temporary array it shows the image field with the corresponding url: 0: id: 8 image: "http://localhost:8000/media/images/IMG_0017_nA75om3.jpg" instigatorProductID: 61 instigatorUsername: "matt" recieverProductID: 62 recieverUsername: "matt2" I also have an issue where I can't use the loop variable [i] when accessing the array to add to the dictionary fields. However, it works if I for example hard code it to [0]. If you guys can explain what's going wrong I would really appreciate it as this seems like it should be pretty trivial. Thanks state = { requests: [], } componentWillReceiveProps(newProps) { if (newProps.token) { axios.defaults.headers = { "Content-Type": "application/json", Authorization: `Token ${newProps.token}$` } axios.get(`http://localhost:8000/api/trade/?recieverUsername=${newProps.currentUsername}`) .then(res => { var array = res.data; var arrayLength = array.length; for (var i = 0; i < arrayLength; i++) { //console.log("HERE"); var itemid = array[i].instigatorProductID; axios.get(`http://localhost:8000/api/articles/${itemid}`) .then(res … -
i want to track number of views for a specific post for a specific user in django. Can anyone tell me how to achieve this?
ObjectViewed model is for tracking users view in post. I am trying to filter number of views for a specific post of the author models.py class ObjectViewed(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) ip_address = models.CharField(max_length=220, blank=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() # User id, Blog id, or any other models id content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s viewed by %s on %s' %(self.content_object, self.user, self.timestamp) views.py class PostDetailView(DetailView): model = Post template_name= 'edmin/post/postDetail.html' context_object_name='posts' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) post=Post.objects.filter(author=self.request.user) content_type = ContentType.objects.get_for_model(Post) print(content_type) context['obj_view'] = ObjectViewed.objects.filter(content_type=content_type, object_id=self.request.user.id) print(context['obj_view']) return context -
Bookmark system in django as in instagram
I wanna build this bookmarking system like in Instagram, I'm having problems writing the logic in views.py and displaying it. So what I want is to bookmark "Act" based on "act-id's" to Wishlist model if a user is authenticated and it would be better if we use Ajax for the post-call(when clicked on the bookmark icon) or open to new options really. Here's my current code... Please help me! if you need any extra bit of code just lemme know. models.py class Act(models.Model): label1 = models.CharField(max_length=50, blank=False) label2 = models.ImageField(blank=False, null=True) label3 = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) label4 = models.CharField(max_length=80) def __str__(self): return self.Name class Wishlist(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE,null=True) act_id = models.ForeignKey(Act, on_delete=models.DO_NOTHING) views.py def wishlist(request): urls.py urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login_req, name='login'), path("logout/", views.logout_req, name="logout"), path('home/', views.home, name='home'), path('wishlist/', views.wishlist, name='wishlist'), ] -
Django model that can create another model
I have a a lot of machines(more than 3000 machines) and want to create machine management asset system. I want to record parameter such as temperature(number), vibration(number), noise(number), color(string) etc.. of each machine and recorded them to Django. The problem is each machine has different parameter to be recorded. For example: machine A (3 parameter to be recorded): -Temperature at outlet -Temperature at inlet -Vibration Machine B (2 parameter to be recorded): -noise -color machine C..D....E... has different parameter. What I want is I can access the historical parameter of each machine. ex: get value of all parameter that belong to Machine B in January to February. (show noise and color data from January to February) class machine(models.Model): name = models.CharField(max_length=30, unique=True) class parameterNumber(models.Model): Machine = models.ForeignKey(machine, on_delete=models.CASCADE, related_name='machine') name = models.CharField(max_length=30, unique=True) recorded_at = models.DateTimeField(auto_now_add=True) value = models.FloatField() class parameterString(models.Model): Machine = models.ForeignKey(machine, on_delete=models.CASCADE, related_name='machine') name = models.CharField(max_length=30, unique=True) recorded_at = models.DateTimeField(auto_now_add=True) value = models.CharField(max_length=30, unique=True) What make me confuses is All machine and the parameter will be created by user. and in above scenario, I stored all of data with type of number in one table. And the parameter such us temperatures recorded each second. so it will … -
Can you tell me what does this error means?
I am trying to deploy my django docker application to Amazon EC2 , So first I pushed the image to DockerHub and then pulling it . I am using Amazon Linux Instance . These are the images I already pulled from DockerHub and I try to run shoaib9942/signals_api image -- I started the docker service and try to run it but it gives an error this is the error -- Also, when I run this command locally it also giving me the same error but when I run docker-compose up then everthing is working fine as it should be . Does this error has some obvious meaning ? -
How to make a table relate to one of multiple others
Im making a system with django and postgresql where each user needs to be assign to one table (that can be Corporation, Client or Vendor) so it will only have access to certain information. The idea is that when I save a user, the filled FK will be in accordance with the form with which it was created and the other FKs remain empty. There will be different forms for each type of user. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) surname = models.CharField(max_length=50) corporation_id = models.ForeignKey("corporations.Corporation", on_delete=models.CASCADE, default=None) client_id = models.ForeignKey("clients.Client", on_delete=models.CASCADE, default=None) vendor_id = models.ForeignKey("vendors.Vendor", on_delete=models.CASCADE, default=None) Is there an smart/correct way of doing this? Because i don't have certain of the accuracy of this logic. Maybe an Enum or create multiple user tables can be more efficient? English isn't my first language, so sorry if there are errors Thanks :) -
Count, add, and filter multiple m2m fields in query in Django
Model: class Vote(models.Model): thumbs_up = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='thumbs_up') thumbs_down = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='thumbs_down') View: qs = Vote.objects.all() percent_min = request.GET.get('min-rating') percent_max = request.GET.get('max-rating') qs = qs.annotate(percent=(Count('thumbs_up')/(Count('thumbs_down')+Count('thumbs_up'))) * 100).filter(percent__gte=percent_min) qs = qs.annotate(percent=(Count('thumbs_up')/(Count('thumbs_down')+Count('thumbs_up'))) * 100).filter(percent__lte=percent_max) I'm attempting to filter by min and max percentages based on user votes (up and down) but I can't seem to get it to work properly. Using the current code if I, for example, put a maximum percentage of 74% in then it filters out everything rated 100% and leaves the remaining. The opposite happens if I enter 74% as a minimum percentage, it filters everything except those rated 100%. Currently no 0 rated entries as I have to tackle the divide by 0 issue next. Any insights would be greatly appreciated. -
How to read from DOM and assign the value into form
I have a specific id defined both in the DOM and another endpoint The endpoint is https://www.example.com/info/data Data in the above endpoint is as shown below {"config":{"user_id":"12345"}} DOM contains the id as "user_id": "12345" I want to acquire the value of user_id from any of the above mentioned locations and assign the same to my form with the name userid <form> <input type="hidden" name="userid" value="valueforuserid" /> </form> My webapp is in django and I searched Django documentation for further information ,while searching I came across Acquiring CSRF Token from DOM.The documentation is mentioning a jquery form for fetching token as below {% csrf_token %} <script type="text/javascript"> // using jQuery const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); </script> Can I use this jquery to fetch the same and assign this to my form . If yes how can I do that ? I am not good with jquery and js. -
Writing a custom Django login required middleware in Django 3
I am new to Django but not new to the concept of middleware (i have a Laravel background). I am trying to write a custom middleware in Django which handles unauthenticated users redirect to login page, unless they are logged in they cannot see home page (for now because there is no profile page yet) and authenticated users to home page, if a user is logged in they can not see the login or register page. I have created a project called django_project with two apps blog and users and added them to the top of django_project/settings.py INSTALLED_APPS list. I checked Django middleware documentation where it says Middleware can live anywhere on your Python path. so in django_project I created a file called ApplicationMiddlewares.py added it to the last of the MIDDLEWARE list. In that file i imported settings, redirect, authenticate, login and logout then added the class reference template which is in the docs. Inside of the class i added process_view function. There i am trying to build some logic of handling users but it gives me a crash loading page, my logic was if not request.user.is_authenticated: return redirect('login') i also tried the other way if request.user.is_authenticated: return redirect('home') … -
session not storing on browser in Django
I'm trying to build an app using React TSX for the front-end side and Django for the back-end side. I want to store the session on the browser using the SESSION_ENGINE=django.contrib.sessions.backends.signed_cookies. So, I want to store the sessions in a similar way of how PHP or Apache stores its sessions. I have tried a lot of ways but I am still not able to store the sessions, I keep getting the output SESSION IS NOW SET from my code. Any help will be great. Thanks login.tsx import Cookies from "js-cookie"; import axios, { AxiosResponse, AxiosError } from "axios"; .......... .......... axios.request({ url: "login/", baseURL: "http://localhost:8000/", method: "POST", data: data, timeout: 15000, withCredentials: true, headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": Cookies.get("csrftoken") }, validateStatus: () => true }).then((res: AxiosResponse): void => { console.log(res.data); }); login.py from django.http import HttpResponse def get(req): req.session.modified = True if req.session.get("user_id", False): return HttpResponse("EXISTS: " + req.session.get("user_id")) else: req.session["user_id"] = "USER-ID" req.session.save() return HttpResponse("SESSION IS NOW SET") settings.py .......... .......... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_NAME = "sessioninfo" CORS_ORIGIN_WHITELIST = [ "http://localhost:5000" ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ["GET","POST"] CORS_ALLOW_HEADERS … -
Issue with STATIC FILES on Django
I cloned a project from github where they were using some "special configuration" for static files, using instead of '/static/', '/static_in_env/', I didn't understand very well why they were doing that, so I decided to change it to what appears on most docs, or tutorials wich is the following config. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets')] STATIC_ROOT = os.path.join (BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Just for giving some extra info: inside TEMPLATES, besides other things, I have: 'DIRS': [os.path.join(BASE_DIR, 'templates')], wich the site seems to read okay(ish), since the problem I have is it renders the templates but without the css I also have inside INSTALLED_APPS 'django.contrib.staticfiles' On the left, (on vscode) I have a folder named static wich looks a bit darker than the rest (wich I don't know what it means) I'm on a venv created with python 3, when I run python --version it tells me I'm on python 3.6.9 wich seems ok to me. I also already ran python manage.py collectstatic previously having copied manually all the static files into assets also, so the collectstatic command puts them wherever they should be for the program to read them, … -
Django form field size
Right now my filter form text field size is very large I'm trying to make the form textfield size smaller.How can I make them smaller I tried giving an id to my form and tried changing the size using css , but it didn't work. filter.py import django_filters from django_filters import DateFilter from .models import Order class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name="date_created", lookup_expr='gte') end_date = DateFilter(field_name="date_created", lookup_expr='lte',) class Meta: model = Order fields = ['status'] order_list.html <form class="filter-form" method="GET" action=""> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> -
Django:How to get daily consumption data for a selected month with the difference between start and end of the values for the each date
Am new to Django. I have a table energydata_model(EnergyDataModel(Django Model name)) in mysql with the following data.Every hour one record will update for each meter in database. I want to calculate every day consumption for a month and display table in HTML template Id date_time_recorded eb_kwh metername 34440 2020-07-16 00:00:00 5515.475 EB INCOMER .... 34565 2020-07-16 12:00:00 5515.664 EB INCOMER ... 34673 2020-07-16 23:00:00 5516.842 EB INCOMER 34441 2020-07-16 00:00:01 3491.478 RAW POWER PANEL .... 34566 2020-07-16 12:00:01 3491.585 RAW POWER PANEL .... 34674 2020-07-16 23:00:01 3491.686 RAW POWER PANEL I want out put for selected meter and selected month like below. Example "EB INCOMER" metername date_time eb_kwh prev_ebkwh daily_consumption EB INCOMER 2020-07-01 00:00:00 5510.475 NA 0 EB INCOMER 2020-07-02 00:00:00 5515.475 5510.475 5 EB INCOMER 2020-07-03 00:00:00 5520.475 5515.475 10 How to write a query in Django to achieve this. -
Custom Permissions in django based on user field values
I have checked the documentation for writing custom permissions for django viewsets using Basepermissions but I am not sure where do I write those classes. Also, it will be great if you can add an example where I write a permission for a user using some filter on the user model. Thanks :) -
I've got some basic problem to display data in django to an html file
/monitor/views.py from django.shortcuts import render, redirect from .forms import RegisterForm from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from main.models import Humidity, Temperature from django.shortcuts import render from django.http import HttpResponse from django.utils import timezone from datetime import datetime, timedelta # Create your views here. def HomeView(response): return render(response, "monitor/monitor.html", {}) def GetData(request): data_temperature = Temperature.objects.all() data_humidity = Humidity.objects.all() return render(request, 'monitor/detail.html', {""}) In main/models.py class Humidity(models.Model): value = models.FloatField() date = models.DateTimeField() def __str__(self): return self.value class Temperature(models.Model): value = models.FloatField() isCelsius = models.BooleanField() def __str__(self): return self.value in monitor/monitor.html <javascript> let response_data =[]; series: response_data; // [{ // name: 'Tokyo', // value: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,6] // }, { // name: 'London', // value: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] // }] </javascript> Can you people leave some lines of code here, the structure of response data is in block which is slashed. I will vote 10 points. I'm really stucked here. -
django - show objects of a single user
I have a list of assets, created by different users. I'd like to show the assets for each user in a template. Right now, I have this (there's more code, but not relevant for this issue): models.py: from django.db import models from django.contrib.auth.models import User from tinymce import models as tinymce_models class Asset(models.Model): title = models.CharField(max_length=200) description = tinymce_models.HTMLField() dateadded = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) file = models.FileField(upload_to='images/', verbose_name='Image', null=True, blank=True) url = models.URLField(max_length=500, blank=True, default='') views.py from .models import Asset from django.contrib.auth.models import User def assets(request): assets = Asset.objects users = User.objects context = {'assets':assets, 'users':users} return render(request, 'assets/assets.html', context) But what should I put in my template? The following gives a list of all assets, but the second part should only show assets by 'bob'... . {% for asset in assets.all %} {% if asset.file %} {{ asset.dateadded_pretty }} - <a href="{% url 'detail' asset.id %}">{{ asset.title }}</a> <span style="font-size:11px"> ({{ asset.ext }} - {{ asset.size }})</span> {% else %} {{ asset.dateadded_pretty }} - <a href="{% url 'detail' asset.id %}">{{ asset.title }}</a> <span style="font-size:11px"> (external link)</span> {% endif %} <br> {% endfor %} <br><br><br> Assets by Bob: {% for asset in assets.all %} {% if asset.user == … -
django rest framework process
I'm starting out with Django Rest Framework but I am confused as to how the DRF works. URL -> ASSIGNED VIEWSET -> DATABASE -> DJANGO ORM -> MODEL -> VIEW -> output but where does serializer get executed? I know that it turns DATABASE objects into JSON but I don't know when serializer gets called. -
Why doesn't the dropdown menu in Django-summernote work?
So I have a Django application, am using django-summernote as editor. Everything works fine in the editor, except for the dropdown menu. No matter how many times I click the downward arrow, nothing changes. Let me show you the codes : settings.py SUMMERNOTE_CONFIG = { 'iframe': True, 'lang' : 'ko-KR', 'summernote': { 'width': '100%', 'height': '450px', 'placeholder':'위대한 글은 위대한 첫 문장에서 시작됩니다!', 'toolbar': [ ['style', ['style',]], ['font', ['fontsize', 'bold', 'italic', 'strikethrough']], # 'fontname', 'clear', ... ['color', ['forecolor', ]], # 'backcolor' ['para', ['ul', 'ol', 'height']], ['insert', ['link']], ['misc', ['fullscreen', 'print', 'help', ]], # 'codeview', 'picture' ... ], }, 'js': ( '/static/summernote-ext-print.js', ), 'js_for_inplace': ( '/static/summernote-ext-print.js', ), 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'css_for_inplace': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'codemirror': { 'theme': 'base16-dark', 'mode': 'htmlmixed', 'lineNumbers': 'true', }, 'lazy': False, } BOOTSTRAP4 = { 'include_jquery': True, } SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' # I'm not really sure what brought me these settings below... Might be related to django-summernote? STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'djangobower.finders.BowerFinder' ] BOWER_COMPONENTS_ROOT = '/PROJECT_ROOT/components/' BOWER_INSTALLED_APPS = ( 'jquery', 'jquery-ui', 'bootstrap' ) # All the STATIC and MEDIA settings are fine. template ... {% autoescape off %} <div class="row"> <div class="col col-12 input-content"> {{form.media}} {{form.contents|as_crispy_field|safe}} </div> </div> {% endautoescape %} ... … -
de-authorize app on facebook with django-allauth when use deletes account
using django-allauth... Is there a way to automagically de-authorize your app from a users Facebook, when that user deletes their account from your app? Say a user has their Facebook profile linked to your app for Facebook Login, as well as email login, and then they want to completely delete their account on your app. user.delete() Is it necessary to also de-authorize your app on their profile? Or should that be considered a step they need to take on their own? I have deleted accounts on apps, but still see them on my app list in my Facebook profile.. so I'm not sure if this SHOULD be a best practice. I want to make sure my users feel that I'm respecting their decision to disassociate from my application. Is it possible to automate this with django-allauth, or must one specifically call the Graph API DELETE endpoint manually? -
Can I create a sitemap.xml from pythonanywhere?
I just finished and deployed my first Django app with pythonanywhere, but I did not know that a sitemap was required. I really wouldn't like doing all the steps in my IDE and then start the deployment process again. Is there a way to implement it at this stage? Sounds intuitive to create the sitemap.XML from https://www.xml-sitemaps.com/ and add it as a new view. Would that work for my app to become indexed in the search engines? -
How to display html table code in script?
I have a simple html bootstrap which I can display the html blo code returned by a django view.py render function the following code: <h2 class="mb-4" style="text-align:center"></h2> {{table|safe}} and it works perfectly. But I need to print several tables in a for loop, so I looked for a script mode. In this case it returns the html code as a string. The code below: <script> const tabela = {{table|safe}}; document.write(tabela); </script> -
How to connect django and nginx with uwsgi?
i'm building web server with django and nginx, uwsgi. I'm using macbook pro mid 14 , mojave when i input port number, django works. but without port number, it won't work. i don't know what is wrong with my code. uwsgi --http-socket 0.0.0.0:8091 --wsgi-file test.py if i use this line, it works. but uwsgi --socket projectname.sock --wsgi-file test.py like this, it won't work. i'm trying to solve this error couple times. but it won't work this is projectname_nginx.conf upstream django { #server 127.0.0.1:8001; server unix:/Users/myname/Desktop/projectnae/name/projectname.sock; } server { listen 8999; server_name localhost; charset utf-8; client_max_body_size 75M; location /media { alias /Users/myname/Desktop/projectnae/name/media; } location /static { alias //Users/myname/Desktop/projectnae/name/static } location / { uwsgi_pass django; include /Users/myname/Desktop/projectname/fido/uwsgi_params; } } and this is projectname_uwsgi.ini [uwsgi] chdir = /Users/myname/Desktop/projectname/name/ module = projectname.wsgi home = /Users/junbeomkwak/Desktop/venv/ master = true process = 10 socket = /Users/myname/Desktop/projectnae/name/projectname.sock; vacuum = true -
Is there a way to filter many-to-many filters in Django using fields from the intermediate table?
I have 3 models in Django. Group, Membership and User. class Group(models.Model): name = models.CharField(max_length=32) permissions = JSONField(max_length=4096, default=list) class Membership(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='memberships') group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='memberships') expires_at = models.DateTimeField(null=True) valid = models.BooleanField(default=True) class User(models.Model): groups = models.ManyToManyField(Group, through=Membership) last_seen = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now=True) The user model has the groups attribute but I was wondering if there was a way to filter the many-to-many field based on if the membership has expired. Thank you!