Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create new objects in django rest framework?
Here i am trying to create some categories but the problem is when i enter the category-create url it displays the only content option but no any fields of my category model.How can i do that?I am only getting this content text field but this is not in my category model field.How can i display all my model fields into my create form? models.py class Category(models.Model): name = models.CharField(max_length=191, blank=False, null=False) description = models.TextField(blank=True, null=True) urls.py path('create',views.create,name='category-create'), views.py @api_view(['POST']) @permission_classes((permissions.IsAdminUser,)) def create(request): if request.method == 'POST': serializer = CategorySerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serialzers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' -
Two get requests in one django APIView
I have an APIView for a X object. I want to have a get request get_X (receives id of the X object) and a get request get_multiple_X (gets all X objects). The current solution is: we have two APIView: one called XView (contains get_X), the second called XListView (contains get_multiple_X). Is there a way to make both requests in the same APIView? I want to have only one APIView (XView). What is the best practice in this case? -
how to get data from database and display it in the form in order to update the content
i have an update function that allow user to update the inserted record using django. i tried to filter the object based on the id. then once i return the id i assume i am able to get all fields. the problem is that when i go to update page the form is empty and no data are return. views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.filter(pk =pk) print( "db entry : ",dbEntry) return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form enctype="multipart/form-data"> <div id='left-column-Input' class="formInput" include="select()"> <div class="forminputs"> <input type="text" id="fname" name="fname" autocomplete="off" required /> <label for="fname" class="label-name"> <span class="content-name" name="fname">{{dbEntry.suspect_name}}</span> </label></div> <div class="home-Button"> <button id="save" name="save" type="submit">Edit</button> <button id="clear" name="clear" type="submit">Clear</button> </div> </div> -
Deleted content from Django app deployed on Heroku appears again
I deployed my Django application on Heroku. Everything works well, except one think as I mentioned above: This is a blog site, and for testing I added just one article. After 10-15 minutes it appears again on my page. What is the reason, I can't get. -
Divide queryset result by months [duplicate]
This question already has an answer here: How to query as GROUP BY in django? 9 answers I have this users stats models.py: class UserStat(TimeStampedModel): company = models.ForeignKey(Company) account_status = models.CharField(max_length=50, choices=users_constants.USER_STATUS_CHOICES) month = models.DateField() count = models.IntegerField(default=0) How to iterate over data and get data divided by months? [{ "label": month_name, "data": { "active": active_users_count, "inactive": inactive_users_count }, }] Here is an example result: [{ "label": "Jan", "data": { "active": 231, "inactive": 12 }, }, { "label": "Jul", "data": { "active": 123, "inactive": 4 }, }] -
How to prepopulate the model when app is ready via AppConfig
I am trying to prepopulate a model with some values when the app starts. I thought the most logical would be to implement it in def ready of AppConfig, but it does not work. from django.apps import AppConfig from django.db.models import signals from myapp.models import mytable class MyAppConfig(AppConfig): name = "MyApp" def ready(self): print(mytable.objects.all()) Above I just try to get the items that are already there, but it still fails. django.db.utils.OperationalError: no such table: myapp_mytable -
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.