Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Annotate Nested Span Relationships and Reuse It for Multiple Filter Conditions?
I am trying to exclude nested foreign key fields from Django query. I have a relationship model. class Relationship(news_models.TimeStampedModel, RelationshipStatus): from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_users') to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_users') status = models.CharField(max_length=10, choices=RelationshipStatus.RELATIONSHIP_STATUSES) I wrote like this: Post.objects.filter( ~Q(Q(creator__from_users__to_user=user) & Q(creator__from_users__status='BLOCK')) & ~Q(Q(creator__to_users__from_user=user) & Q(creator__to_users__status='BLOCK')) ) But it does not work because this query excludes all the users who blocked or got blocked by at least one irrelevant user. I want something like this: Post.objects.filter( ~Q(creator__from_users=Subquery(Q(to_user=user) & Q(status='BLOCK'))) & ~Q(creator__to_users=SubQuery(Q(from_user=user) & Q(status='BLOCK'))) ) Or Post.objects.annotate(creator_from_users=F('creator__from_users')).annotate(creator_to_users=F('creator__to_users')).filter( ~Q(Q(creator_from_users__to_user=user) & Q(creator_from_users__status='BLOCK')) & ~Q(Q(creator_to_users__from_user=user) & Q(creator_to_users__status='BLOCK'))) ) How should I annotate or save the value in the middle and reuse it to filter nested foreign fields? -
How to filter Django object to get top X number of objects with highest property value
So I have a class called Hero with 150 objects. Each object has a property Winrate. I want to get the top 12 heros based on winrate. class Hero(models.Model): hero_name = models.CharField(max_length=20, default = 'Dota 2 Hero') hero_id = models.IntegerField() def __str__(self): return str(self.hero_id) def get_winrate(self): wins = len(Match.objects.filter(heros_won = Hero.objects.get(hero_id = self.hero_id))) losses = len(Match.objects.filter(heros_lost = Hero.objects.get(hero_id = self.hero_id))) if wins + losses != 0: return round((wins / (wins + losses)),2) else: return 0 winrate = property(get_winrate) I tried alot of filters but couldn't get it to work. -
advantages of generic view method over apiView
I am working on a big project and when it comes to the views.py, I was adviced by a friend to use apiViews over generic view or modelViewset. I would like to know what advantage a view method could have over others that makes it better to use in a big project over other methods. the project in question would have things like users making video posts and updating it, following other users, collaborating e.t.c. -
Django - Static files not found on ubuntu
I currently stuck on handling static files with django on lubuntu, keep receiving error 404, file not found. I've tried multiple possibilities that I've googled, but none of them worked in my case. I have my static files under static folder in my main project's folder. settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] Could you give me advice what is the bast way to handle static files on ubuntu or if you see any solution in my case? -
get django inheriting templates from java
i'm new in django i want call the inheriting templates after click on image to new div i'm tried to add it but its not call its ok if used array text but django inheriting not work any help please // javascript <script type="text/javascript"> var djangoLink = {% include 'base/sceneForm.html' %}; function myFunction() { document.getElementById("Total").innerHTML= djangoLink ; } </script> // html <div id="Total"> </div> <img onclick="myFunction()"> -
Accessing .csv data from views file
I have a small Django app, and I'm trying to access data from a CSV file (static/blog/dat.csv, the static folder is at the same level as the templates folder and views.py; and everything is inside my blog app) so I can use it to plot a graph on the browser using Chart.js. Aside from not being able to do that, the app is working fine. I know I'm gonna need to pass some sort of context to the view function, but I don't know how I'd do that. Also, I have a couple of similar csv files, and using them as static files in my app seems simpler and easier than to add everything to a database to access them that way. # views.py from django.shortcuts import render from django.contrib.staticfiles.storage import staticfiles_storage import csv def rtest(request): url = staticfiles_storage.url('blog/dat.csv') with open(url, 'r') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: context += line return render(request, 'blog/r.html', context) # urls.py urlpatterns = [ # ... path('r-test/', views.rtest, name='blog-r-test'), ] Here is the error I'm getting: FileNotFoundError at /r-test/ [Errno 2] No such file or directory: '/static/book/dat.csv' I'm sure this is not the only error. I know that the way I'm … -
else (in an if else condition) not working
I have a javascript function that sends a XMLHttpRequest when a button is clicked, once the request is processed by the python code, I want the function to perform a task depending to the response of the python code. Specifically once the request is loaded request.onload calls a function that has an if else condition, however the else statement is not recognized and i get the error Uncaught SyntaxError: Unexpected token else Any clues about what that's happening? function clicked(param) { // Figure out how to get the name of the table to query const request = new XMLHttpRequest(); const id = param.id; const name = param.name request.open("POST", "/add_to_cart", true); const data = new FormData(); data.append("id", id); data.append("name", name); var csrftoken = getCookie('csrftoken'); request.setRequestHeader("X-CSRFToken", `${csrftoken}`); request.send(data); request.onload = () => { if (request.responseText === 0) { alert("Added to cart"); }; else { var array = document.getElementsByClassName("plus radius"); for (var i=0; i<array.length; i++) { array[i].style.display = "none"; }; alert("Added to cart, please choose your toppings"); }; }; return false }; -
Why am I receiving this Template error in my django tutorial?
I am currently working through the django polls tutorial and I keep receiving this error. I just can't seem to figure out how to fix it. I have tried watching multiple youtube tutorials, searched on stack for users having the same problem, and I can't seem to get anything to work.enter image description here -
how can I process to send generated pdf as attach mail in django?
for my homework, I need to send an attach file to e-mail. there I have some questions about attach file on django send mail: 1-is't possible to send it without save the PDF document in the DB? 2- how can I process to realise this function? In fact all helps consult didn't match. Definition of render_to_pdf utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None the generated function : views.py class GeneratePDF(View): context_object_name = 'services' template_name = 'pdf.html' def get(self, request, *args, **kwargs): template = get_template('configuration/pdf.html') f=Reservation.objects.all().filter(Q(valide=True, option__in=Option.objects.all().filter(Q(code_option='GTR', posseder_niveau__in=Posseder_Niveau.objects.all().filter(niveau_id = 1))))).order_by('date_du_jour_reserve') c = Plage_Horaire.objects.all() context = { "c":c, 'f':f, } html= template.render(context) pdf = render_to_pdf('configuration/pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") -
Django: Casting Abstract Models
I have an abstract Django model that I use to create two other models. How can I avoid duplicating code when dealing with the different examples below (for example, when creating a Boxed cereal and a Bowled cereal I would like to avoid duplicating the function twice. class Cereal(models.Model): name = models.CharField() class Meta: abstract = True class Boxed(Cereal): pass class Bowled(Cereal): pass func some_func_boxed(name): boxed = Boxed.objects.get(id=1) boxed.name = "Captain Crunch" boxed.save() func some_func_bowled(name): bowled = Bowled.objects.get(id=1) bowled.name = "Lucky Charms" bowled.save() -
How to use the value of a model in another value of the same django model
I have a model Group that has a field maximum_capacity and a member field, what i want to do is to use the value the user enters in the field maximum capacity to set the max_choices for the member field. I am using Django2.2 and the max_choices option came from the MutiSelectField package i installed. I have tried converting to int using int() but gives the same error. class Group(models.Model): number_of_group_members = ((i, i) for i in range(2, 100)) members_choices = [(member.email, member.first_name + member.last_name) for member in CustomUser.objects.all()] maximum_capacity = models.IntegerField(choices=number_of_group_members, default='Specify group limit') members = MultiSelectField(max_choices=(i for i in range(maximum_capacity)), unique=True, choices=members_choices) I keep getting the Error: members = MultiSelectField(max_choices=(i for i in range(maximum_capacity)), TypeError: 'IntegerField' object cannot be interpreted as an integer -
Django session is not unique
I have a simple Nomenclature model and items in it. I have two functions add to cart and view cart (shown below). I can select and add items to the cart. It works well locally. When I host in a live server using nginx and uwsgi. The session selection is not unique. If I select items in a browser and use another (different computer) browser I can see the same selection in another system browser. Also there is a delay in either add to cart or view cart. How can I troubleshoot it? How can I make unique sessions? I use Django 2.1, SQLite def add_cart(request): ''' This will add the profiles to the cart ''' if request.method == 'POST': selected_values = request.POST.getlist('name', None) if selected_values is not None: request.session['list_names'].extend(selected_values) profile_length = len(selected_values) message_profile = "Selected {} proteins added to the cart".format(profile_length) messages.success(request, message_profile) request.session.modified = True return render(request,'nomenclature/search_page.html') else: request.session['list_names'] = selected_values request.session.modified = True profile_length = len(selected_values) message_profile = "Selected {} proteins added to the cart".format(profile_length) messages.success(request, message_profile) return render(request,'nomenclature/search_page.html') def view_cart(request): selected_values = request.session.get('list_names') ''' This will show the cart page with list of profiles ''' context = { 'nomenclatures': Nomenclature.objects.all(), 'selected_groups': selected_values, } if selected_values is … -
500 Internal Server Error in production - Django
I'm very new in django and I am in deploying phase of a project. But after all setup, it shows 500 internal server error and the apache2 error log says ImportError: No module named 'backend' I tried to edit wsgi.py as I thik this is the one giving this error this is content of my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.dev') application = get_wsgi_application() the error log says ImportError: No module named 'backend' -
How to change url within get_queryset of django ListView
I'm trying to change the browser url in get_queryset() in a django ListView. Actually I'm trying to hide query params after i use them i found no solution. Please help me with the best method for this purpose I tried to redirect but queryset can't return a HTTPResponseRedirect. I also tried to use a javascript function but it's also not performing well on submit button. I'm recently start development with python and django. Thank you for your support My ListView's queryset: def get_queryset(self): query = self.request.GET.get('q') author_name = self.request.GET.get('a') btn_clicked = self.request.GET.get('m_btn') if btn_clicked: data_to_use = self.request.GET.get('m_paper') # here i tried to change the url using pop but not work self.request.GET._mutable = True self.request.GET.pop('m_paper') self.go_for_mindmap(data_to_use) if query: return Paper.objects.filter(title__icontains=query) if author_name: my_papers = Paper.objects.all() new_paper_list = [] for my_paper in my_papers: if author_name.casefold() in my_paper.get_author_fam().casefold(): new_paper_list.append(my_paper) return new_paper_list else: return Paper.objects.all() HTML Template <form action="#" method="GET" class="float-right"> <input type="hidden" value="{{ p.title }}" name="m_paper"> <!-- javascript function (onclick) also not working. --> <button type="submit" class="btn btn-success" value="Click" name="m_btn" onclick="myFunction();">Go</button> </form> I accept to the there is no more paramters in url -
Can PAM module authenticates users against Django login credentials?
I have a Django web application running on Server1 with around 9000 users. Now i would like to create a vsftpd server on Server2 and enable all the 9000 users to access their own home folders using credentials of web-app on Server1. I want to have a PAM authentication on server2 where users are validated against webapp on server1. If a user is deleted or updated his password on server1, FTP access has to be allowed/denied accordingly. i.e User Authentication server has to be my webapp only. Is django logins by default SSO compliant? Can i have LDAP server inside Django with the same users&passwords? -
Do I need to install NPM in server to host a website built with Django Rest API and Vue JS?
I am newbie to Django. I have created a website ( similer to Quora) using Vue JS that consume Django REST API, I have used the Vue through Vue CLI. Do I need to install NPM in Heroku server to host the Vue CLI ? I think the server may need large amount of space to host the NPM. Also running NPM may impact the server speed. Should I consider CDN link of Vue JS instead of hosting in server ? -
Navigation bar side by side in Django?
I'm trying to build a navigation bar for practice but running into an issue. I'm trying to get information from views.py to share on website through html but not working very well. It displays the content perfectly but it is not showing them in one line. I included a picture of the rendered website. HTML Code: <!doctype html> <html> <style> ul{ width : 100%; float : left; display: inline-block; list-style-type: none; background-color: blue; } </style> <head> <title>Coding for fun</title> </head> <body> <ul class="navBar"> {% for my_sub in my_test %} <li> {{ my_sub}} </li> {% endfor %} </ul> </body> </html> -
Should I use an internal API in a django project to communicate between apps?
I'm building/managing a django project, with multiple apps inside of it. One stores survey data, and another stores classifiers, that are used to add features to the survey data. For example, Is this survey answer sad? 0/1. This feature will get stored along with the survey data. We're trying to decide how and where in the app to actually perform this featurization, and I'm being recommended a number of approaches that don't make ANY sense to me, but I'm also not very familiar with django, or more-than-hobby-scale web development, so I wanted to get another opinion. The data app obviously needs access to the classifiers app, to be able to run the classifiers on the data, and then reinsert the featurized data, but how to get access to the classifiers has become contentious. The obvious approach, to me, is to just import them directly, a la # from inside the Survey App from ClassifierModels import Classifier cls = Classifier.where(name='Sad').first() # or whatever, I'm used to flask data = Survey.where(question='How do you feel?').first() labels = cls(data.responses) # etc. However, one of my engineers is saying that this is bad practice, because apps should not import one another's models. And that instead, … -
Django migrations for second model
Django doesn't respond to making the migrations to the model in the new app. I deleted the app then made a new one, but still doesn't respond. I deleted the old migration and makemigrations, Django only respond to the first model which I have done before this problem (venv) F:\My site>python manage.py makemigrations No changes detected (venv) F:\My site>python manage.py makemigrations blog No installed app with label 'blog'. -
Creating a lot of numbered URLs easily
I have a list of Hospitals on a web page and each Hospital has a link with it that should open a new page which shows all the reviews and feedbacks that people fill in the feedback form. The problem is that the list goes on for about 70-80 hospitals and creating a URL and a view for each one is a very tiring and long job. Also the number of hospitals may vary later on and then that new entry would require a new URL and view. I want to know if there's any easy way to create those 80 URLs without having to actually create even those 80 URLs (like maybe a loop or something). I'm very new to Django, Python and HTML so an easily understandable way is much appreciated. I'm using PyCharm community and Python 3 for this project. Thank you. -
Removing class name removes my HTML a tag without which I cannot perform AJAX
I'm learning from this tutorial: AJAX and Django Where I'm using the below code. <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Assume appropriate django template code here --> <a class="btn btn-primary btn-lg" id="like{{ post.id }}" href = "#" data-catid="{{ post.id }}">Like</a> <!-- Assume appropriate django template code here --> <script type="text/javascript"> $('.btn').click(function() { var id; id = $(this).attr("data-catid"); $.ajax({ type:"GET", url:"like", data:{ post_id: id }, success: function(data) { $( '#like' + id ).removeClass('btn btn-primary btn-lg'); $( '#like' + id ).addClass('btn btn-success btn-lg'); } }) }); </script> If I put the likebutton in class of like below, the like button doesn't show. I do not understand it as stackoverflow's run snippet shows a like button, but my browser (firefox latest) doesn't. <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Assume appropriate django template code here --> <a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" href = "#" data-catid="{{ post.id }}">Like</a> <!-- Assume appropriate django template code here --> <script type="text/javascript"> $('.likebutton').click(function() { var id; id = $(this).attr("data-catid"); $.ajax({ type:"GET", url:"like", data:{ post_id: id }, success: function(data) { $( '#like' + id ).removeClass('btn btn-primary btn-lg'); $( '#like' + id ).addClass('btn btn-success btn-lg'); } }) }); </script> Screenshots … -
How to access data(which is in html form) which has been passed to another html inside views.py?
While rendering the '/form/' in my py_upload function I am passing a parameter 'data' which contains the code of an html form(by form I mean some text boxes where I can enter some information and not the element of html) which I have obtained using selenium. This html is displayed in my /form/ url where it will be filled and I want to perform some operation on the filled form on pressing the submit button (inside my py_form function). How can I use the filled html code inside my py_form function? I tried replacing the 'data' element in my form.html with the html code inside 'data' and then I could access it but the problem is that the html code in 'data' is not constant so I can not hardcode that html in my form.html. Below are the files form.html and views.py <div class="container"> {% if data %} {{data | safe}} {% endif %} <form action="" method="post"> {% csrf_token %} <input type="submit" name="Submit" value=" </form> </div> def py_upload(request): if request.method == 'POST': #some selenium code to get some html data in 'data' return redirect ('/form/',{'data':data}) return render(request,'upload.html') def py_form(request): if request.method == 'POST': ##access the filled html data return redirect('/response/',{'flag': … -
How to set a field constant in a django model
I have a custom user model and a company model: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() company = models.ForeignKey( Company, null=True, blank=False, on_delete=models.SET_NULL) class Company(models.Model): company_name = models.CharField( default='', max_length=128, blank=True, null=True) In settings.py I also have a customer_name constant: CUSTOMER_NAME = os.environ.get('CUSTOMER_NAME') How can I add a condition in my user model so that if the user is_staff boolean is TRUE then the company_name is fixed to be the CUSTOMER_NAME constant? -
How to Make Background iamage URL Static
I want to make this URL static as like this <img src="{% static 'images/beach.svg' %}" > {% load static %} <div class="background_image" style="background-image:url(images/home_slider.jpg)"></div> What/How I can do? -
how to use custom model user in django-rest-framework-simple-jwt
simple-jwt currently issues token using superuser but, i wanna use my custom User Model. (i defined custom User model as below.) class User(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=10, unique=True, blank=False) password = models.CharField(max_length=128) def __repr__(self): return self.__class__ class UsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("name", "password") my question is that could i receive token using custom user model at simple-jwt? if simple-jwt uses custom User model, please tell me how to use custom User model.