Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build control panel for kivy application in django?
Hi i want to build admin panel in Django for my kivy application. I am using: Python 3.7 Pycharm Kivy Mongodb -
Why does 'Git add *' leave some files unstaged?
I initialized a new git repo in my Django project. All files( including the files in subdirectories and pipfile) are staged when I run git add * except the .__atomic-writegxd2tirf file. Why is this one excluded? -
HttpResponse - how to get the values from context (Django)
I have a function defined like this in my views.py: def homePageView(request): (some code here...) return render(request, 'index.html' {'mytuple': mytuple}) The function itself is working perfectly, however I need the mytuple value to be accessible from another function. So, my other function looks something like this: def value_checker(request): value_check = homePageView(request.POST.get(['mytuple'], False)) return render(request,'dynamic.html', {'value_check': value_check}) Unfortunately is not working and I'm getting an error: TypeError at /value unhashable type: 'list' I've looked at the Django documentation of HttpResponse but honestly I can't seem to figure out how to access this tuple. What am I doing incorrectly here? -
Django - how to delete objects in the database?
So, I'm having problems deleting objects in django project's database. I have a model in my models.py file that looks like this. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) I want to be able to delete information in this model. In my project, I have this model's information displayed in a table that looks like this table/html My goal is to click the "drop" button and have that line of info deleted. I've been following some tutorials and advice on making a delete function for my views.py and I can't get it to work. It seems pretty simple but I'm not sure where I'm going wrong. Here's my views.py and urls.py def delete_player(request, id): player = Myteam.objects.get(id=id) #print(player.id) player.delete() return redirect('index') path('delete_player/<int:id>', views.delete_player, name="delete_player") here's my html... <form action="" method="POST"> {% csrf_token %} <table style="border: 1px solid black;"> <tr> <td style="border: 1px solid black;">QB</td> … -
[Django Beginner]: Proper way to import a model from another app when using forms?
I have a model, inventory.Location. This is in the inventory app. I'm creating a form in another app and make reference to inventory.Location. Specifically, I'm populating a choice field with all Locations (with minor criteria). This works well until I attempt to make any migrations, at which point Django throws an error: django.db.utils.OperationalError: no such column: inventory_location.contact contact is just a field, removing contact just causes the same error to occur only with another field. It seems Django doesn't like creating an instance for LocationForm as it ties back to the inventory.Location model. If I comment out the contents of 'LocationForm' and re-run the migration attempt it works perfectly fine. Removing any previous migrations and/or re-building the DB from scratch doesn't seem to have any influence, it's specifically the LocationForm class contents. Is there a best practice way I should be handling this? Everything works; I just have to comment out the contents of LocationForm, run migrations, then uncomment. I'm clearly approaching this the wrong way. from django import forms from inventory.models import Location def get_locations(): location_list = [] locations = Location.objects.all() for location in locations: if location.primary_ip: site_list.append( (location.name, location.name) ) return location_list class LocationForm(forms.Form): location = forms.ChoiceField( widget=forms.Select(), … -
Not requiring Authentication Credentials in Authenticated Views Django Rest Framework
I have some views with IsAuthenticated Decorator. When I try to access those views with postman without the Token it's not giving me an error. But it should give me an error by saying authentication credentials are not provided. What is the reason for that. @permission_classes((IsAuthenticated,)) @api_view(['POST']) def CreateSubject(request,pk): author = TeacherProfile.objects.get(user_id=pk) serializer = SubjectSerializer(data=request.data) if serializer.is_valid(): serializer.save(author=author) return Response(serializer.data) From this view, I can create a subject but it should require the user token to be inside headers. But as I guess decorator is not working. Im using a custom user model class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12,null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # def has_perm(self, perm, obj=None): # return self.is_admin def has_module_perms(self, app_label): return True -
Ignore filter in Django None value
Is there anybody know how can I ignore filtering when the value is none just like the sample below. municipality = request.POST.get('municipality) if request.POST.get(municipality) else None bene = Person.objects.filter(province=province, municipality=municipality) If the municipality value is none the filtering should ignore municipality in bene query and it should only filter the province, just I need help this time thanks -
django new posts made are going on the bottom when they should go up top
I am currently building an app that allows users to post comments on a web page. Every time someone makes a new comment it goes to the very bottom. How do you make all new comments made appear up top? -
Django rest framework serializer require all or none
Is there a way to make a list of fields be an all or none required? Maybe something like this where if any of fields 'A' to 'D' is included in data all of them should be required but if none of them is included in data it should be fine: class BookSerializer(serializers.ModelSerializer): fieldA = serializers.CharField() fieldB = serializers.CharField() fieldC = serializers.CharField() fieldD = serializers.CharField() # other fields class Meta: require_together = ( ('fieldA', 'fieldB', 'fieldC', 'fieldD'), ) -
Django + Apache, Saving uploaded files on different storage server
I have a application server where I have configured my Apache and Django which will host my application. This is running fine. Now the requirement is to serve the uploaded files directly to different storage server or you can say on a remote server. And after uploading my application should able to retrieve them also from the remote server. My application is on x.x.x.50 My storage is x.x.x.60 How can i do that with minimal changes in my application server. I have tried changing MEDIA ROOT path in Apache but I don't know how exactly i should do that to work it smoothly. -
Django: Trying to create a Meeting Room API with Reservations
So I got these tasks: Creating meeting room Get meeting room reservations and the possibility to filter by employee Create reservation (Reservation has title, from and to dates, employees) First of all I have created a meeting room, this is the model: class MeetingRooms(models.Model): public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) creator = models.ForeignKey(Employees, on_delete=models.CASCADE) reservations = models.ManyToManyField(MeetingRoomsReservations, blank=True) secret_key = models.CharField(max_length=128, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "MeetingRooms" def __str__(self): return str(self.id) So as the task says I need to create some kind of reservations, so basically I was thinking that I could create reservations object and make it ManyToManyField, so it could serve many reservations for different users, imagine the meeting could have like 10 people. Then I have created MeetingRoomsReservations model to handle all the reservations: class MeetingRoomsReservations(models.Model): statusTypes = [ (0, "Valid"), (1, "Cancelled") ] receiver = models.ForeignKey(Employees, on_delete=models.CASCADE) meeting_room = models.ForeignKey('MeetingRooms', on_delete=models.CASCADE, default=None) title = models.CharField(max_length=150, blank=False, null=False) status = models.IntegerField(choices=statusTypes, null=False, blank=False, default=0) date_from = models.DateTimeField() date_to = models.DateTimeField() class Meta: db_table = "MeetingRoomsReservations" def __str__(self): return str(self.id) As far as I understand the logic, the MeetingRoomsReservations will handle all the reservations that were registered for the MeetingRoom. MeetingRoom > … -
Condition inside objects filter Django
Im been wondering if it is possible to put condition inside query just like this sample = Person.objects.filter(province=province, municipality=municipality, if barangay!=None: then barangay ="value") Im been having a problem same with this link but I don't know how I can ignore empty value in query. Is there any expert can help me please -
Changing Value of an Attribute in a Model when a post takes place
I have made a blog where a user can like or unlike, so everything is working fine now but I have tried to add a Like Model to view more details related to each like that takes place by which user and when. In the Like Model I have added a value for each model and choices are Like and 'Unlike' I have tried in the views to use get_or_create but it cause an error TypeError: Field 'id' expected a number but got <built-in function id>. and I tried to add the value incase a like and unlike is made it returned AttributeError: 'str' object has no attribute 'save' I am going to show the view with my trials commented First here is the post model: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the like model: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) liked = False current_likes … -
Django tests stopped running
My Django tests have randomly stopped running and I cannot figure out why. The error that I'm getting is: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I found this question and I've run the command: export DJANGO_SETTINGS_MODULE=mysite.settings (with my relevant settings) and it didn't solve the issue. I've also tried adding this to the top of my tests file but it didn't do anything: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") Here is the full print out of the error I'm getting: /Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/bin/python /Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py Traceback (most recent call last): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py", line 90, in <module> from repcdocs.tasks import print_slack_users File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/repcdocs/tasks.py", line 10, in <module> from django.contrib.auth.models import User File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before … -
Django Multiple Choice Quiz - conditionally change background using python / html
New to django, python, and html here. I'm creating a MULTIPLE CHOICE QUIZ and want the background to conditionally change based on the user's selected answer. I'm trying to use the "IF" function through html. Stylesheet using classes via CSS are working just fine. I made several print calls just to see if my python logic was working and it does (see code below). I think it's something i'm doing wrong from the html side. Side note - all questions and answers are saved in Django database. So for example: The correct answer to question 1 is "Apple". If the user selected "Apple", the webpage should result "Correct! Good job.". For any other answer selected, should result "Wrong!! The correct answer is Apple." My problem for many many many days/hours is that as of now every choice I select results in "Wrong, you are Incorrect" as the resulted background. Even when the correct answer is chosen by the user. Thanks in advance for all of your help! Please see code below. views.py def vote(request, question_id, *args, **kwargs): question = get_object_or_404(Question, pk=question_id) ### temporarily PRINTED call from database to see if python logic works, It works. ID 1 prints out "Apple". … -
Service backend failed to build
Getting the following error while trying to build docker image: ERROR: Service 'backend' failed to build : The command '/bin/sh -c apk add — update — no-cache postgresql-client' returned a non-zero code: 3 How can I resolve this? -
How to convert Function-based generic view with object_list return type to class-based
In Django 1.4 how can I convert a function-based generic view to a class-based view when the return type is an object_list? I'm new to Django and inherited a project I must upgrade from 1.4 to 1.5+ and I can't find an example dealing with this specific situation. I tried changing def parts_list(request) to various permutations of class PartsList(ListView) based on related examples, but nothing worked and I feel like I'm in the weeds on which direction to take with this. Here's the deprecation warning signaling the needed change: /home/administrator/partsdb/vrt1/local/lib/python2.7/site-packages/django/views/generic/list_detail.py:10: DeprecationWarning: Function-based generic views have been deprecated; use class-based views instead. Relevant code snippets urls.py part_info_dict = {'queryset': Part.objects.all() } (r'^parts/(?P<object_id>[\d]+[\w-]*)/$', 'django.views.generic.list_detail.object_detail', part_info_dict), views.py from django.views.generic.list_detail import object_list # This view is a wrapper to call object_list with a different query set than the default. def parts_list(request): prefix = request.GET.get('type', False) value = request.GET.get('filter', False) extra_context = {} qs = Part.objects.all() if prefix: if prefix == '00': qs = Part.objects.all() else: qs = Part.objects.filter(part_number__startswith=prefix) extra_context['type'] = prefix if value: qs = Part.objects.filter(Q(part_number__icontains=value) | Q(description__icontains=value)) extra_context['filter'] = value return object_list(request, queryset=qs, paginate_by=settings.PAGINATE_BY, extra_context=extra_context) -
Django deployed on GKE cannot be accessed by LoadBalancer
Basically I have this django app which has the pods and loadbalancer services running successfully in GKE. But I cannt access the app through the external Ip in loadbalance with the port. Firstly here is my pods and loadbalancer status: Justins-MacBook-Pro-166:Django-RealEstate qingyuan$ kubectl get svc polls NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE polls LoadBalancer 10.108.2.157 104.155.130.204 8000:30575/TCP 3m24s Justins-MacBook-Pro-166:Django-RealEstate qingyuan$ kubectl get pods NAME READY STATUS RESTARTS AGE polls-db68f9d76-8mgrw 2/2 Running 0 3m43s polls-db68f9d76-k85rw 2/2 Running 0 3m43s polls-db68f9d76-qjsbt 2/2 Running 0 3m43s And here is my dockerfile: FROM gcr.io/google_appengine/python LABEL maintainer qm28@georgetown.edu # Create a virtualenv for the application dependencies. RUN virtualenv -p python3 /env ENV PATH /env/bin:$PATH #Prevents Python from writing pyc files to disc (equivalent to python -B option)# ENV PYTHONDONTWRITEBYTECODE 1 # So the logs can always write to container logs and not get buffered at first place ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD requirements.txt /app/requirements.txt RUN /env/bin/pip install --upgrade pip && /env/bin/pip install -r /app/requirements.txt ADD . /app CMD gunicorn realestate.wsgi:application --bind 0.0.0.0:8000 here is my yml file: apiVersion: apps/v1 kind: Deployment metadata: name: polls labels: app: polls spec: replicas: 3 # selector: when deployment create the pods, it will actually created by the kubernetes … -
Django : serving static files with Nginx and docker
I am using 2 containers : one for django, one for Nginx, and I try to serve static files. Here are the port forwardings : I made a schema of the configuration : The containers are on the same server, and django is listening on port 9000 while Nginx n port 8080. Nginx can ping django, both through normal network and through docker's bridge network. I configured on the right the Nginx to listen on port 8080 and redirect non-static / media file to django (I am a first-time user of Nginx, adapting https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) . (I created my own dockerfile). I know django is working because I can see it on my browser, the same for Nginx (the "not found" is ok for me : the server is running, and I am aksing for random-non-existing media). The issue comes when trying to fetch an answer from django going throught Nginx : the redirection doesn't work. It looks like Nginx can not find django. What do I / Could I do wrong ? -
django object has no attribute status_code
I am learning to develop and trying to develop a screen in django 1.1 and I am getting this error below. I already took a look at some stacks I already looked at httpresponse, however, I was not successful could someone help me and explain what could be wrong? I'm getting this error on the console: Internal Server Error: /gerencia-margem/list Traceback (most recent call last): File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/middleware/locale.py", line 38, in process_response if (response.status_code == 404 and not language_from_path and AttributeError: 'HistoricoComissao' object has no attribute 'status_code' [18/Nov/2020 13:30:06] "GET /gerencia-margem/list HTTP/1.1" 500 77145 This is models, # -*- coding: utf-8 -*- from django.db import models class HistoricoComissao(models.Model): class Meta: verbose_name = u'Historico Comissão' verbose_name_plural = u'Historico Comissões' pednum = models.CharField(max_length=40, blank=True) margem = models.DecimalField(decimal_places=4, max_digits=15, null=True, blank=True) data = models.DateTimeField() historico = models.TextField((u'Historico HTML'), blank=True) status = models.PositiveSmallIntegerField(choices=[(1, 'Em Aberto'), (3, 'Pendente'), (4, 'Finalizado'),]) def __unicode__(self): return str(self.pednum) this is the views from django.views import View from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from ..models import HistoricoComissao def listview(request): template_name = 'comissao/margenslist.html' comissoes = HistoricoComissao.objects.all context = { 'comissoes': comissoes } return render(request,template_name,context) this … -
convert timezone pytz string to offset in python/django
I am using django/python How do I convert pytz timezone string such as 'Asia/Kuala_Lumpur' to offset information ('+0800' or '80'). I am not able to find the exact function here:https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/ I would like to use it in moment.js like this: Format date in a specific timezone so the question is: 'Asia/Kuala_Lumpur' --> convert to ---> '+0800' -
How can I make a relation beetween serializers in Django Rest?
A simple E-commerce app has 3 models: class Order(models.Model): """Order model.""" id = models.AutoField(primary_key=True) date_time = models.DateTimeField() @classmethod def get_total(self, obj): """Get total method. Calculate the total price of the order. """ details = OrderDetail.objects.filter(order=obj) return sum([i.price * i.cuantity for i in details]) class OrderDetail(models.Model): """Order Detail model. Primary key will be created automatically and inevitably. """ order = models.ForeignKey('sales.Order', related_name='details', on_delete=models.CASCADE) cuantity = models.IntegerField() price = models.FloatField(null=True) product = models.ForeignKey('products.Product', on_delete=models.CASCADE) @classmethod def get_product_price(cls, obj): """Get product price, and put it on the order detail price. """ obj.price = obj.product.price obj.save() return obj.price class Product(models.Model): """Product model.""" id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=25) price = models.FloatField() Product objects are already been created in one endpoint, but I need to create a new order with its order details, all in one endpoint. For that I have to use a ModelViewSet and ModelSerializer. I've tried this way: class DetailSerializer(serializers.ModelSerializer): """Order Detail model serializer.""" product_id = serializers.CharField() product = ProductSerializer(read_only=True) price = serializers.SerializerMethodField() class Meta: model = OrderDetail fields = ['cuantity', 'price', 'product_id', 'product'] read_only_fields = ['price'] def get_product(self): """Get the product from his id.""" return Product.objects.get(id=self.product_id) def get_price(self, obj): """Get the price for every detail.""" return OrderDetail.get_product_price(obj) class OrderDetailedSerializer(serializers.ModelSerializer): """Order … -
how to set selected value of a select tag from database in django
I'm trying to make an edit screen. What I want to do is render the data stored as default values of the select tag. Forms.py class EditGroupForm(ModelForm): class Meta: model = Group fields = ["current_year", "career", "commission", "subject", "contacts"] widgets = { 'name': TextInput(attrs={ "placeholder" : "", "class": "form-control" }), 'subject': Select(attrs={ "class": "form-control" }), 'contacts': SelectMultiple(attrs={ "class": "form-control" }) } Views.py def edit_group(request, id): if request.method == "GET": form = EditGroupForm() group = Group.objects.get(id=id) form.name = group.name return render(request, "edit-group.html", {'form': form, 'group':group}) edit-group.html <div class="card-header"> <h5>Edit group: {{form.name}}</h5> </div> <form> {% csrf_token %} <div class="form-group"> <label for="inputSubject">Subject</label> <div class="input-group mb-3"> {{ form.subject }} </div> </div> <div class="form-group"> <label for="inputContactList">Contacts</label> <div class="input-group mb-3"> {{ form.contacts }} </div> </div> <button type="submit" class="btn btn-primary shadow-2 mb-4 float-right">Save</button> <a class="btn btn-secondary float-right" href="/groups" role="button">Cancel</a> </form> Right now, there is no default selected value. How can I do this? -
drf serializer don't find value because of is_html_input() function
I'm tiring to post many files with nested data and I got an error of "this field is required", after debugging I found that the serializer searching for field using regex ( in this line ), this is because of is_html_input() which returns true but the data was well decoded I can retrieve it with data.get('field_name') instead -
Django: Access query_params in ModelViewSet method 'get_numbers_fruit'
I have FruitViewSet(viewsets.ModelViewSet): My view is accessing my viewset with: FruitViewSet.get_numbers_fruit() However, if I run print(self.request.query_params) inside my method, I receive the error: 'WSGIRequest' object has no attribute 'query_params' I have read that this is inaccessible on the first go round, but I can't figure out how to prevent it so as to allow access no the second.