Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found 404 error when trying to serve media files in Django
I want to display user uploaded images in my template. I can't seem to find what I'm doing wrong. Using Django 2.2 version. I tried what the documentation says (https://docs.djangoproject.com/en/2.2/howto/static-files/) but couldn't find any other solution after this one failed. This is from settings.py file. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is from my urls.py file in an app called 'signage' urlpatterns = [ path('screens/', views.screens_dashboard, name='screens_dashboard'), path('screens/new/', views.add_screen, name='add_screen'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is from my template <img class="img-fluid" src="{{ screen.picture.url }}" alt="First slide"> -
How do I develop the view.py file for the the models below? A list view of all the projects and a detailed view for each project is needed
I'm writing the code for the views.py file. How do I handle the many-to-many relation between the tables? The models.py file is pasted below. enter code here from django.db import models # Create your models here. class Developer(models.Model): name=models.CharField(max_length=150) image=models.ImageField() about=models.CharField(max_length=1500) smartcampus_contributor=models.BooleanField(default=False) def __str__(self): return self.name class Contributions(models.Model): contributor=models.ForeignKey(Developer,on_delete=models.CASCADE) description=models.CharField(max_length=1500) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return self.contributor.name+"-"+str(self.pk) class Project(models.Model): developer=models.ForeignKey(Developer,on_delete=models.CASCADE) project_name=models.CharField(max_length=250) github_link=models.URLField(max_length=250) description=models.CharField(max_length=1500) def __str__(self): return self.developer.name+"-"+str(self.pk) -
Custom select box field in form from model in django
Please help me to do custom Select Box in forms of Django. I want to query the data from the model, i have created In Model.py Title = models.CharField('Title', max_length=250, blank=True, null=True, help_text='Enter Title') in Admin.py class Meta: model = Book1 fields = ['Title'] Title = forms.ModelChoiceField(queryset=Book1.objects.values_list('Title', flat=True).distinct(), widget=forms.Select()) class Book1Admin(admin.ModelAdmin): form = Book1Form save_as = True admin.site.register(Book1, Book1Admin) But it did not display as a select box, only as a text field in the place of Tile field. Do I need to create custom select field for the QuerySet? -
Use https for uploaded file in Django
I have a model to stock json file: class JSONFile(models.Model): source = models.FileField(upload_to='json') When I upload a file directly in Django admin, then click on the url in the interface, I found that the url of this file uses the https scheme. For example: https://mydomain/api/media/json/file1.json But when I access the view's result by https://mydomain/api/jsonfiles/1/, it uses http: { "id": 1, "source": "http://mydomain/api/media/json/file1.json" } How could I fix that? Thank you! -
How do I schedule Django Custom Management Command with windows task scheduler?
Im unsure of how to set it up. It works perfectly in shell but I have no idea how to set it up. Any help is appreciated -
Process JSON with ajax without redirect
I have: {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), sucess: function(json) { console.log(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. What am I doing wrong? -
Why is my views.py variable not displaying in my template
I am trying to display the client ip address upon login if the user is the Admin. However, I am unable to display the 'ip' variable in the home.html template. I have a function in views.py that returns the desired variable. How can I call this function upon loading of the home.html page? There are no errors. templates\home.html {% if user.is_staff %} <p><a href="{% url 'admin:index' %}">Admin Panel</a></p> <p>{{ ip }}</p> {% else %} Hello {{ user.username }} <p><a href="{% url 'logout' %}">logout</a></p> {% endif %} views.py def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] return render_to_response('home.html', {"ip": ip}) else: ip = request.META.get('REMOTE_ADDR') return render_to_response('home.html', {"ip": ip}) I expect to display the 'ip' variable in my home.html template. -
How to fetch arrayfield data in django with postgres
I'm trying to fetch users list based on their language(from ArrayField). A single user can have multiple languages. When i passed single language{'Hindi'}, it fetches all the records except user with multiple languages, but if passed parameters {'Hindi','bangla','kannada'} then it gives me a specific record,how can i fetch the users list with hindi and other than hindi as well . I have tried with .all also but it didn't worked for me. Any help would be appreciated. models.py # DESCRIPTION: This function gets the drivers list by lang. @classmethod def get_driver_by_lang(cls, driver_lang): try: driver_details = cls.objects.filter(language = driver_lang) data = serializers.serialize("json", driver_details) data = json.loads(data) return data except : return False -
Create a Django project following MVC pattern?
I am learning Django after moving from J2EE (Java). I have a problem with Django project layout following MVC pattern. In J2EE: My project includes 3 main parts: Model: _ JavaBean (DTO): defines classes based on Database tabales. _ DAL: defines classes to manipulate java beans with database. Controller: _ Servlets View: _ JSP files Therefore, I have 3 packages(DTO,DAL,Controller) and a folder containing JSP files. I understand that Django uses MTV. However, there's a submodule of a Django project called "app" that contains "model" and "view" inside. This makes me confused when following project layout according to J2EE above. Hope to receive some advises from you guys. Thank you. -
last iteration result overriding (on web) the previous outputs
In reference to the previous question here are some adjustments i made and further added some functionalities. In Previous question the loop was iterating for multiple IPs and single command but now i want tje loop to iterate for multiple IPs and multiple commands & for that i added one more for loop. As in code everything is fine while writing the file but In HttpResponse the result of last output is overriding the previous outputs views.py from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse, HttpResponseRedirect import netmiko from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from paramiko.ssh_exception import SSHException from netmiko.ssh_exception import AuthenticationException import datetime, time, sys from django.urls import reverse # Create your views here. def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler ipInsert = request.POST.get('ip_address', '') #taking multiple IPS ipIns = ipInsert.split(',') #splitting IPs CSVs cmd = request.POST.get('command', '') #tking multiple Commands cmdlist = cmd.split(',') #splitting commands for ipIn in ipIns: #for eqch in IP in IP list for cmdSingle in cmdlist: #for eah command in Command list devices = { 'device_type':'cisco_ios', 'ip':ipIn, 'username':'mee', 'password':'12345', 'secret':'12345', } try: netconnect = ConnectHandler(**devices) except (AuthenticationException): re = 'Authentication … -
Django filter: Finding a best practice
I am finding a way to achieve a filter in a fewer code like, my current filter working fine below: if company == 1: unknownFood = food.filter( purchase__credit = 2 company__name__isnull=True ) elif company == 2: unknownFood = food.filter( purchase__credit = 2 company__name__isnull=False ) else: unknownFood = food.filter( purchase__credit = 2 ) Above code, appeared with few repeated line of code and I believe this is not a best practice. I am trying to achieve this with a fewer line code than above code. here you go: if company == 1: isNull = True elif company == 2: isNull = False else: pass unknownFood = food.filter( purchase__credit = 2 company__name__isnull=isNull ) if i do like above shortened way, it fires me an error, coz company__name__isnull is equeal to false or true and its third block gets neither true or false Can anyone suggest me the best way to achieve this? -
Django unit Testing client error: Too many redirects; While browser tests show expected redirect results
In a simple project that contains two type of users, such as students and teachers, the students are only allowed to view student's home page, while the teachers are allowed to only view teacher's home page. If a student accidentally/intentionally tries to access the teacher's home page url, the student needs to be redirected; and same goes for the teachers if they tried to access the students' home page. I currently have it set up using a user_passes_test decorator, that if one type of user tries to access the other type's home page, the user will be redirected to his/her own home page. (also tests for auth, see below) While just simply testing with the chrome browser, the expected results are shown; while using the Django test client in unit testing, the client object complains with an error of too many redirects, while, looking into its source code if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) I just cannot figure out where that exception comes from, please … -
How to blacklist a third party class in Python?
I would like to blacklist a single class from a third party package used in a Django project. So far I've exhausted the following options: Get it fixed upstream. I tried, but the project maintainers refused because it would break too many other projects. Remove the package altogether. The project relies heavily on lots of features of this package, and there is definitely not enough resources to reimplement it. Code review rule. We do perform code reviews, but it would be easy for an error to sneak by and then go unnoticed for a long time. Anyway, code reviews should not be about checking things which can be checked automatically. Fork or patch the package. This is messy and brittle, and either of these would be a last resort. I don't know whether Python, Django or flake8 have some way of explicitly blacklisting a class (or its methods), but any of those could be used. -
How to repair my login redirect in django
The urls in my django project started to fail. So in my templates I had to change {% url 'home' %} for {% url 'app1:home' %} and also my urls, so my urls works fine but not the redirect when log in or log out. I have LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' But now I get NoReverseMatch, reverse from home don't work. # my app1.urls.py from django.urls import path from .views import HomePageView, VentasPageView, AcercaPageView from .views import buscar app_name = 'app1' urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('ventas/', VentasPageView.as_view(), name='ventas'), path('buscar', buscar, name='buscar'), path('acerca/', AcercaPageView.as_view(), name='acerca') ] What should I do? Why is this happening? -
Liking of Posts on a Django Project
I am trying to create a forum website where people can post and these posts can get upvoted. The issue is that one user can upvote any post multiple number of times. How do I solve this so that a user can only vote once on a certain post? I have tried creating a ManyToManyField but can't seem to work properly around it. class Product(models.Model): title = models.CharField(max_length=200) body = models.TextField() url = models.TextField() votes_total = models.IntegerField(default=1) image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') pubdate = models.DateTimeField() voters = models.OneToManyField('PostVoter') class PostVoter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def upvote(request, product_id): if request.method == 'POST': product = get_object_or_404(Product, pk=product_id) postvoters = PostVoter.objects.all() if postvoters.filter(user=request.user).exists(): return redirect('home') else: product.votes_total += 1 PostVoter.objects.create(user=request.user) product.save() return redirect('/products/' + str(product.id)) I want to make this work so that multiple users can like a post and one user can like multiple posts but a user can like a certain post only once. -
How do best iterate over a queryset with a changing id?
I'm trying to increase the performance of a part of my application. The easiest way to handle the logic is the least friendly to the database. The more code I write, the more I feel I'm overcomplicating the situation. Poor Performing (for obvious reasons) ids = [1,2,3,4,5,6,7,9,10] for id in ids: results = MyTable.objects.filter(id=id) for item in results: doProcessing(item) My ids list can get large pretty easily, which of course results in a bunch of hits to the database. However, I know easily that list of results are only for the specified id. Trying to Improve (unsuccessfully) ids = [1,2,3,4,5,6,7,9,10] results = MyTable.objects.filter(id__i=ids) for item in results: doProcessing(item) That is the basic of what I'm trying to do. But obviously the iteration is going to give me all the results for all of the ids. I still need to be able to process all of the results that have the same id as a group. In the end I think I still need a list with the results for a given id. I then process that entire list, then move on to the next list. I just can't find a clean way of separating out those groups of results with … -
how to group total in djnago join 3 table
get the total cost per item by multiplying item_cost(table ITEM) and actual_cost(table INVENTORY) using this code: for abc in Inventory.objects.select_related('item_code_id'): zyx = abc.actual_stock * abc.item_code.item_cost group the zyx output by CLASSIFICATION class Classification(models.Model): catclass_code = models.CharField(max_length=100, primary_key=True) classification_code = models.CharField(max_length=2, default='00') classification_description = models.CharField(max_length=100) class Item(models.Model): item_code = models.IntegerField(primary_key=True) item_description = models.CharField(max_length=100) classification_description = models.ForeignKey(Classification, verbose_name='Classification', on_delete=models.CASCADE) item_cost = models.DecimalField(decimal_places=2, max_digits=15) item_retail = models.DecimalField(decimal_places=2, max_digits=15) item_billing_price = models.DecimalField(decimal_places=2, max_digits=15) class Inventory(models.Model): item_code = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='header', primary_key=True) actual_stock = models.IntegerField(_('Actual Stocks'), default=0) def inv_summ(request): a = 0 for abc in Inventory.objects.select_related('item_code_id'): zyx = abc.actual_stock * abc.item_code.item_cost a += zyx return render(request, 'officesupplies/inv-summary.html', {'invdate': invdate, }) my sql code work just fine i just don't know how to convert this code in django view 'select classification_description,sum((item_cost) * actual_stock) from inventory left join item on inventory.item_code_id=item.item_code left join classification on item.classification_description_id=classification.catclass_code group by catclass_code' thank you in advance -
Django OperationalError Unknown Column
I'm trying to create a CRUD using Django Rest Framework and a MySQL database. I use sqlclient as connector for the MySQL connection. The problem is when I want to do request, it always throws me the next error. django.db.utils.OperationalError: (1054, "Unknown column 'author_id' in 'post'") I don't have declared author_id variable in nowhere neither in my code or in the database, I don't know why django is saying that the author_id column is required. The model that I'm using is this: class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateField(default = timezone.now) author = models.ForeignKey("auth.User", db_column='author', on_delete = models.CASCADE) class Meta: managed = True db_table = 'post' The serializer looks like this: class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ['post_id', 'title', 'text', 'created_date'] And the view set like this: class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() permission_classes = [ #permissions.IsAuthenticatedOrReadOnly #Permission for unauthorized GET requests IsGetOrIsAuthenticated # Custom permission for unauthorized GET requests ] serializer_class = PostSerializer def perform_create(self, serializer): print(self.request.user.id) serializer.save(author=self.request.user.id) I really not understand why is creating author_id if is nowhere in the code or the database. Why is creating it? What I have to do to the app to work? -
How does Django detect test mode?
I'm running tests on Django (2.2) with Postgres. According to Django's docs, when running tests, it should create a throw away database named by prefixing the normal database name with test_. However this is not happening for me: the tests use the normal database! Here are the relevant settings: # Another module where I define these values from conf.vars import DB_HOST, DB_NAME, DB_PASSWORD, DB_USER DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': DB_HOST, 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, # I added the following to see if it makes a difference, but no. 'TEST': { 'NAME': 'test_' + DB_NAME, }, } } My manage.py file has the usual stuff including this line: execute_from_command_line(sys.argv) I'm guessing there is something I'm doing which is causing Django not to recognise it is in test mode, as the only alternative explanation is that this is a bug in Django and that seems unlikely as it's a pretty serious one. This also makes me wonder, how does Django know when it is in test mode? Trying to search for this only throws up people asking how to detect test mode for their own purposes. -
binary data on websocktes with additional information
I am trying to develop a chat application on django, for live communication I am using websockets. Messaging is working fine but I am in trouble with files, if any one attach multiples files then how to send and receive it with some additional data. I had set - chatSocket.binaryType = 'arraybuffer'; For simple messaging - chatSocket.send(JSON.stringify( {'id': next_id, 'message': message, 'karma' : karma.val(), 'cert': cert.attr('data'), } )); if someone try to send multiple images then - let files = document.getElementById("attach_img").files; // files.item = '092' console.log('files send requested',files); chatSocket.send(files, { binary: true }); In my consumers.py async def receive(self, bytes_data=None, text_data=None): print('recieved',bytes_data, text_data) It is printing - recieved None [object FileList] but when I change my files as - let files = document.getElementById("attach_img").files['0']; then received bytes_data will be something like- b'\xff\xd8\xff\xe0\x00\x10JFIF\..... I want to send the images + id + cert to server. I search a lot on internet but unable to get the solution how I can send files with additional information over websockets. -
Django-REST: The database driver doesn't support modern datatime types
I'm trying to make a rest API with Django Rest on Debian, but when I run the command "python3 manage.py migrate" throws this exception Error: The database driver doesn't support modern datatime types.") django.core.exceptions.ImproperlyConfigured: The database driver doesn't support modern datatime types. Already installed: msodbcsql17 is already the newest version (17.3.1.1-1). freetds-bin is already the newest version (0.91-6.1+b4). freetds-dev is already the newest version (0.91-6.1+b4). tdsodbc is already the newest version (0.91-6.1+b4). unixodbc-dev is already the newest version (2.3.7). unixodbc is already the newest version (2.3.7). file:odbc.ini [MYSERVER] Description = Django SQLServer Driver = FreeTDS Trace = Yes TraceFile = /tmp/sql.log Database = DjangoDB Servername = MYSERVER UserName = sa Password = ******* Port = 1433 Protocol = 8.0 file:odbcinst.ini [FreeTDS] Description=FreeTDS Driver for Linux & MSSQL on Win32 Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup =/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so UsageCount=1 [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.3.so.1.1 UsageCount=1 file:freetds.conf [global] # TDS protocol version tds version = 8.0 [MYSERVER] host = localhost port = 1433 tds version = 8.0 -
Nginx "502 Bad Gateway" when using uWSGI Emperor with multiple django projects on CentOS6
I set up a Django website on a CentOS 6 server using Nginx and uWSGI, and I would like to expand this to include more unique Django sites on the same IP. I have been trying uWSGI Emperor, but it has been fighting me along the way. Both sites now give "502 Bad Gateway" errors, and I'm stuck on how to best setup uWSGI emperor to work with it all. The CentOS 6 server has python 2 installed, but I'm using rh-python36 for all the Django sites and uWSGI. I tried following this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-centos-7 , though the uwsgi didn't work for some reason. I've mostly been trying to mess with the .config and .ini files for nginx and uwsgi, though I'm not confident what I've added has helped. The virtualenv location for both sites: /root/Env/mysite1_env /root/Env/mysite2_env Nginx: /etc/nginx/conf.d/mysite1.conf (mysite2.conf is similiar) server { listen 80; server_name mysite1.net www.mysite1.net; root /home/serveruser/svr/sites/mysite1; access_log /home/serveruser/svr/sites/mysite1/logs/access.log; error_log /home/serveruser/svr/sites/mysite1/logs/error.log; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } # Django admin media location /media { alias /home/serveruser/svr/sites/mysite1/media; } # ag_jobs static media location /static { autoindex on; alias /home/serveruser/svr/sites/mysite1/static; } # Non-media requests to django server location / { uwsgi_pass unix:/home/serveruser/svr/sites/mysite1/mysite1.sock; include … -
Django Login Redirection Not Working -- User Not authenticated
The code redirects but runs the condition suite that redirects to index.html-- indicating the user was not authenticated( user is None) I'm trying to create a sign in/ login page. My registration form works but the login page runs in a way that indicates that the user was not successfully authenticated Note: This is the code in my views.py file from django.shortcuts import render, redirect from django.utils.safestring import mark_safe from django.contrib.auth.models import User, auth from django.contrib import messages import json def index(request): return render(request, 'chat/index.html', {}) def enter_chat_room(request): return render(request, 'chat/chat_room.html') def login(request): if request.method == 'POST': username = request.POST['userlogin'] password = request.POST['loginpassword'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('enter_chatroom') else: # messages.info('Invalid') return redirect('index') else: return render(request, 'chat/index.html') I want the user to enter the chatroom once he/she has been authenticated -
how to make an update function in django
i have an update function that allow user to update a form with pre-populated data using django the problem once the user try to enter to the update page the system display the below error : local variable 'form' referenced before assignment views.py def update(request,pk): instance = get_object_or_404(suspect,pk=pk) if request.method == "POST": form = suspectForm(request.POST or None,instance=instance) if form.is_valid(): instance = form.save(commit = false) instance.user = request.user instance.save() return redirect('result',pk = instance.pk) else: form = suspectForm(instance = instance) return render(request,'blog/update.html',{'form':form}) update.html {% extends "testbootstarp.html" %} {% load static %} {% block content %} <div class="offset-3 col-md-6"> <form method="post"> <div class="form-group">{% csrf_token %} {% for field in form %} <div class="field"> <label>{{field.label_tag}}</label> {{field}} {% for error in field.errors %} <p class="help is-danger">{{error}}</p> {% endfor %} </div> {% endfor %} </div> <button type="submit">edit</button> </form> </div> {% endblock content %} -
How To Fix Miscased Procfile in Heroku
Heroku will not reload my corrected Procfile I have ran git status which shows me the Procfile and I realized that I spelled Procfile with a lower case p. I saw the error and updated the file name in my project but when I saved and ran git status again it stills shows it lower case. Of course now its not showing the site on Heroku. Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: procfile remote: -----> Discovering process types remote: remote: ~ Mis-cased procfile detected; ignoring. remote: ~ Rename it to Procfile to have it honored. remote: remote: Procfile declares types -> (none) Total newbie on my first project. Should I delete the project on Heroku and just start all over fresh or can I just do a git init and then just push everything up again to Heroku?