Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I serialize list of booleans in django rest framework serializer?
I'm using Django Rest Framework and I want my data to be stored like this: 'days': [True, True, False, True, False, False, False] as one of the returned fields. I would like to have a seriaizer: class HistorySerializer(serializers.Serializer): days = serializers.BooleanField(many=True) , but serializers.BooleanField doesn't have 'many' argument. I've tried doing this: class DaysListField(serializers.ListField): day = serializers.BooleanField() class HistorySerializer(serializers.Serializer): days = DaysListField() , but it produces: 'days': [{'day': True}, {'day': True}, {'day': False}, {'day': False}, {'day': False}, {'day': False}, {'day': False}]. I also tried doing this: class HistorySerializer(serializers.Serializer): days = serializers.SerializerMethodField() def get_days(self, obj) -> List[bool]: return obj.days but Swagger produces incorrect output of the days type, it says it should be boolean instead of [boolean]. What is the best way to process this list correctly? -
How to run mulitible django python scripts from .py file in VS Code Terminal?
is there a possible way to start my django project with one single call of an .py file in the VS Code Terminal? I need to call the following scipts all the time to run my project : pipenv shell python manage.py runserver python manage.py sass-compiler --watch And I want theme to be all called when I run an start.py script. Thank you -
I cannot register a user using Django-Rest-Framework
I can't add a new user using Django Rest Framework. Here is my code from models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) password = models.CharField(max_length=15, default= None) first_name = models.CharField(max_length=100, validators=[name_validator]) last_name = models.CharField(max_length=100, validators=[name_validator]) email = models.CharField(max_length=100, validators=[mail_validator]) created_at = models.DateTimeField(auto_now_add=True) As you can see I am using models.OneToOneField cause I want to extend the default user to add some more fields. Bellow is my serializers.py file: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile permissions_classes = [ permissions.AllowAny ] fields = '__all__' The viewset is the following: class UserViewset(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer When I go to my endpoints and try to add a new user, I cannot put anything in the "user" field: Click for image I am a beginner and it would be of great help. Everything that I find I don't understand. -
How to search in PostgresSQL and display the values
I am creating a simple Hospital Management system using Python, Django and PostgresSQL as my school project, I have added a page where the user can add/edit/delete/view the records and I want to add a search option. The above topics(add/delete/edit/view) are discussed clearly in the textbook except search.Reading documentation from both Django and PostgreSQL didn't help me much. I am attaching the views.py and the output page of my program and ready to upload further scripts if required. Kindly instruct how to search in PostgreSQL and display the results. from django.shortcuts import render, redirect from Doctor.forms import Doctorform from .models import Doctor # Create your views here. def doctor_list(request): context = {'doctor_list':Doctor.objects.all()} return render(request, 'Doctor/doctor_list.html', context) def doctor_form(request, id=0): if request.method == "GET": if id==0: form = Doctorform() else: doctor = Doctor.objects.get(pk=id) form = Doctorform(instance=doctor) return render(request, 'Doctor/doctor_form.html', {'form':form}) else: if id == 0: form = Doctorform(request.POST) else: doctor = Doctor.objects.get(pk=id) form = Doctorform(request.POST,instance= doctor) if form.is_valid(): form.save() return redirect('/doctors/Doclist') def doctor_delete(request, id): doctor = Doctor.objects.get(pk=id) doctor.delete() return redirect('/doctors/Doclist') Sample Page of my program -
Is there a way to assign question id to inline formset automatically?
Inline formset generates answer field to the number of questions in my model, but I have to specify url for questions (question_id) or assign question manually like question = Question.objects.get(id=1) to do the work. I want to do this in one view which (question_id) in url is not working for me. The second way is also not useful. So, what I want is that when inline formset generating answer fields, it also gives each answer field an id. models.py class Question(models.Model): question = models.CharField(max_length=200) class Question_Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def index(request): question = Question.objects.get(pk=1) QuestionFormset = inlineformset_factory(Question, Question_Answer, fields=('answer',), can_delete=False,extra=0 ) if request.method == "POST": formset = QuestionFormset(request.POST, instance=question) if formset.is_valid(): formset.save() else: formset = QuestionFormset(instance=question) context = {'formset': formset} return render(request, 'index.html', context) -
AttributeError: 'WSGIRequest' object has no attribute 'get' while making a get request
I am trying to make a get request to stackoverflow API but I am facing a WSGI error while making the requests through POSTMAN. Here is the code snippet: Views: def search(requests): query = requests.GET["query"] response = requests.get('https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + query + '&site=stackoverflow') api_Data = response.json() return JsonResponse({"message": api_Data}) URLs: urlpatterns = [ path('search/', views.search, name='search'), ] I have tried I keep getting 'WSGIRequest' object has no attribute 'Get' on django but it did not work. -
Django how do you build it into a model check that if User read articles or not?
First, I have a user model and a article model in Django And each user can write/read any article What i need to want a list of articles that each user has not read. want to check the list of people who have read about a certain article and the list of people who have not read it. How can i build or modify a model? my models are here Cheers class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=20, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() class article(models.Model): title = models.CharField(max_length=255, blank=False) content = models.TextField(max_length=1000, blank=False) created_by = models.ForeignKey( User, on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) -
Same code to add email attachment.Different execution time
Code: print(time.strftime("%Y-%m-%d-%H%M%S", time.localtime(time.time()))) att2 = MIMEText(open('C:/Users/olay_Czz/Desktop/test.rar', 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="test.rar"' msg.attach(att2) print('add-ok') print(time.strftime("%Y-%m-%d-%H%M%S", time.localtime(time.time()))) Runtime in Django(compiler:Pycharm): 2020-12-30-175140 add-ok 2020-12-30-175218 Runtime in Script(compiler:sublimetext): 2020-12-30-180242 add-ok 2020-12-30-180242 Why is the execution time gap so wide -
fetching refresh token with django-microsoft-auth
after going through the module code and extensive googling I am still to find a "simplistic" (ie. by not rewriting the whole module) way of acquiring refresh token for azure ad auth. Any suggestions would be appreciated, replacing this module with something different is also something I am looking into atm. -
Delete all task related to User
I am creating a todo app. I want to delete all task related to a particular user from Tasklist table after login but i got an error ' deleteAll() missing 1 required positional argument: 'id' ". How can i delete all task. Thanks in advance. Model.py from django.contrib.auth.models import User from django.db import models class TaskList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=100, null=False, blank=False) complete = models.BooleanField(default=False) taskCreate = models.DateTimeField(auto_now=True) Views.py def deleteAll(request, id): TaskList.objects.filter(id=request.user.tasklist_set.filter(id)).delete() return redirect('todolist') Html {% extends 'home.html' %} {% block content %} {%if user.is_authenticated%} <h2>Welcome {{ user.get_username| title }}</h2> <button type="submit"><a href="{% url 'logout' %}">Logout</a></button> <form method="post"> {% csrf_token %} <label for="task"> <input name="task" placeholder="add today's task" id="task" required> <button type="submit">add</button> </label> </form> <form method="get" > {% csrf_token %} <div> {% for todo in task %} {% if todo.complete %} <li class="list-group-item todo-completed"><h6>{{ todo.task|linebreaks}} </h6></li> {% else %} <a href="{% url 'complete' todo.id%}"> <h6 class="list">{{ todo.task|linebreaks}}</h6></a> {% endif %} {% endfor %} <button><a href="{% url 'delete' %}"> Delete All </a></button> <button><a href="{% url 'deleteComplete' %}"> Delete Completed </a></button> </div> </form> {% endif %} {% endblock %} -
Django Rest Framework custom token authentication
I want a custom authentication which will authenticate the token in my model.I have a model called User_Auth where there is a field called 'secret_token'. I want the Django Rest Framework to Authenticate token through that model. I had followed the docs on django rest framework website but didnt work for me. Please help me to solve this issue. models.py class User_Auth(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User_Master, on_delete=models.CASCADE) secret_token = models.CharField(max_length=2000, null=True, blank=True) authentication.py class UserAuthentication(authentication.TokenAuthentication): def authenticate(self, request): key = request.META.get('Authorization') if not secret_token: return None try: ua = User_Auth.objects.get(secret_token=secret_token) except ua.DoesNotExist: raise exceptions.AuthenticationFailed('Unauthorized') return (ua, None) views.py class User(viewsets.ModelViewSet): authentication_classes = (UserAuthentication,) permission_classes = (IsAuthenticated,) I am passing the token through the Header. Authorization: 'Token a7c14fc808b58533e4d1651cd2375c3b41a38ef5d120254a1cb4bbd90b3be1534215516b023818e4' Still its returning { "detail": "Authentication credentials were not provided." } Please help me. -
Django: show 'Password Reset Done' page only after redirect (avoiding direct access by URL)
I am using Django's standard built-in PasswordResetDoneView and PasswordResetCompleteView to deal with the password reset workflow. I want to make my URL path password-reset/done/ to be available only after redirect, i.e.: If a customer requests password reset → redirect to password-reset/done/. If a customer enters the URL address password-reset/done/ in their browser → redirect to 404. This is only an issue of aesthetics, but I want to figure out if there is any other way to deal with that, except for using request.session. -
the import sentence got errors:from oauth2client.contrib.django_util.models import CredentialsField in models.py
I use ubuntu in AWS for deploy a django project. when I run the"python3 manage.py runserver" cmd, error occurs: from oauth2client.contrib.django_util.models import CredentialsField File "/usr/local/lib/python3.6/dist-packages/oauth2client/contrib/django_util/__init__.py", line 233, in <module> from django.core import urlresolvers ImportError: cannot import name 'urlresolvers' I use Django 3.0.11. How to solve my problem? -
Django allows model object with empty fields to be saved
Below is the model named 'Dataset' containing three fields name, desc and data_file. class Dataset(models.Model): name = models.CharField(max_length=256) desc = models.TextField() data_file = models.FileField(upload_to='datasets/') I created a model object with python command. >>> d = Dataset() >>> d.save() >>> d.name, d.desc, d.data_file ('', '', <FieldFile: None>) Django allowed this object to be saved. Even when blank = False is the default for every field. How can I may sure that dataset objects cannot be created with these three fields empty ? Below is the sqlite3 schema: CREATE TABLE IF NOT EXISTS "datasets_dataset"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(256) NOT NULL, "data_file" varchar(100) NOT NULL, "desc" text NOT NULL ); -
JSONDecodeError in json.loads(request.body)
I am getting JSONDecodeError in data=json.loads(request.body) cart.js: function updateUserOrder(productId, action) { console.log('User is authenticated') var url = '/update_item/' fetch(url, { method: 'POST', headers: { "Content-Type": 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId': productId, 'action': action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('Data: ', data) location.reload() }); } In views.py: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] I am getting this error. JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0) Request Method: GET Request URL: http://127.0.0.1:8000/update_item/ Django Version: 3.1.3 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Python version: Python 3.8.6 Django version: 3.1.3 I tried following other posts in stackoverflow and tried using cherrypy and various other ways for json.loads(request.body). Please resolve this error. -
Django - ask user for menuitem choices on each menu item
I am developing a simple restaurant app in django and mysql and after days of googling and research, i wasn't able to find a suitable answere for this particular problem, here is my django Model class MenuItem(models.Model): menu_category = models.ForeignKey(MenuCategory, to_field='slug', on_delete=models.CASCADE) name = models.CharField(max_length=30) image = models.ImageField(upload_to='uploads/menu/') slug = models.SlugField(null=True, blank=True, unique=True) price = models.DecimalField(max_digits=9, decimal_places=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is the problem: for example i have a menuItem "MEXICAN BURGER" i would like to ask the user their choice of meat.. ie either chicken or beef, or their choice of bread, white or brown, or i might be having a MenuItem "OMELETTE COMBO" and i would like to ask the user the type of omellete they'd like to have eg ('spanish omelete', 'spinach and mushroom omelete') or i might be having a MenuItem "ESPRESSO" and i would like them to choose between ('single', 'double') one menuitem can have multitple choices related to it, ie burger item can have choice of bread as well as choice of meat -
Can I create a session login by django?
basically, I want to allow an anonymous user to login to the website and not create a profile, but can save the session if wants, and revisit anytime -
Setting an Authorization Header in Django without the use of a client
Is there a way possible to set a header in the server and not from the client? Probably an example will be me trying to set an Authorization Header with a token to the server and not from the client because the client can't access that token as it's made with a httponly cookie. Tried something in a Django view. request.META['HTTP_AUTHORIZATION'] = f'Token {....}' And it works in the sense that I can see that key and value in the header but for some reasons it seems not to work as it should be like using a client will this logic will make the request an authenticated one, but doing this from the server doesn't seem to do that.. It's like it's tricking me to believe it works by showing me the object in the header, but there is no functionality of it. -
Exclude a QuerySet from a pre-existing filtered QuerySet based on a One-to-One relationship
I have a Django application with three models: class Strategy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... class Version(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE) ... class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) version = models.OneToOneField(Version, on_delete=models.CASCADE) ... On the Tool model's corresponding ToolForm, I filter the QuerySet for the 'version' field, so that the User only sees the strategy versions they submitted: def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['version'].queryset = Version.objects.filter(strategy__user=user.id) I now want to filter this QuerySet further to exclude Versions which already have Tools. The Version to Tool relationship is One-to-One, and I only want the User to see Versions which still require Tools to be submitted. I have tried numerous approaches, but I keep coming back to versions of: Version.objects.filter(strategy__user=user.id).exclude(Tool.objects.filter(version__strategy__user=user.id).values('version_id')) Version.objects.filter(strategy__user=user.id).exclude(Tool.objects.filter(version__strategy__user=user.id).values_list('version_id')) Respectively, the responses I get are: 'dict' object has no attribute 'split' 'tuple' object has no attribute 'split' What am I missing? How can I exclude Versions from my ToolForm 'version' field that already have the One-to-One relationship established? -
Django makemigrations is creating migrations for model with managed = False
While Django documentation https://docs.djangoproject.com/en/3.1/ref/models/options/#managed mentions the use of managed = False field in meta is used to not create migrations I am still getting migrations when I call makemigrations. This is the meta of the model: class FieldOpsBooking(models.Model): . . class Meta: managed = False db_table = 'field_ops_booking' And I am getting this after makemigrations python manage.py makemigrations Migrations for 'user_analysis': user_analysis/migrations/0001_initial.py - Create model FieldOpsBooking - Create model RewardManagementLeads Migrations for 'od_engagement': od_engagement/migrations/0001_initial.py - Create model NormalisedTonnage And it creates 0001_initial.py file with all migrations to apply as well. Any help is appreciated -
How to update Django model fields in MySQL database
I created a model for posts in Django and I'm trying to update one of the fields in the database (MySQL). I have the following block of code: model.py class Post (models.Model): title = models.CharField() preamble = models.CharField() body = models.TextField () createdAt = models.DateTimeField(auto_now_add=True, blank=True) I want to add another field called author author=models.ForeignKey(User, on_delete=models.CASCADE Also, I want to change the name of one of the fields from preamble to introduction Whenever I run the command python manage.py makemigrations and then python manage.py migrate, I get an error which terminates the migration process. it's telling me that the field preamble which I have in my database is not recognized. Is it possible to update preamble to introduction? -
Django search the wrong directory for index template
Hi I'm new at Django and i have 2 app named home and blog. my home project urls.py is urlpatterns = [ path('',include('home.urls')), path('blog/',include('blog.urls')), path('admin/', admin.site.urls), ] blog apps urls.py is app_name= 'blog' urlpatterns =[ path('',views.index, name = 'index'), path('<int:post_id>/',views.postpage, name ='postpage') ] home apps urls.py is app_name= 'home' urlpatterns = [ path('', views.index, name='index'), ] and when i try to render index.html in home app, django search in blog app however it must search in home app. more detail my home views.py is def index(request): return render(request,'home/index.html') and page return TemplateDoesNotExist at / django.template.loaders.app_directories.Loader: /home/caglarbingol/Documents/Projects/caglarbingol/blog/templates/home/index.html (Source does not exist) two app have both index.html page in dir blog/templates/blog/index.html and home/templates/home/index.html what am i doing wrong? -
GETTING AN ERROR "THE SITE CAN'T BE REACHED " AFTER DEPLOYING DJANGO PROJECT ON APP ENGINE
I am following the documentation for deploying Django project on Google App Engine. And after following all the instructions and deploying the sample code provided by google cloud with command "gcloud app deploy" on Google cloud SDK I am getting an error "This site can't be reached". Please resolve my issue I really need that. -
uploading csv file into Django model
I'm working on a Django app and need to import a CSV file into the Django model. What's the proper way to get around this? I was planning to use pandas to read the CSV and then saving into models with bulk_create. But not sure if there will be any performance issues as the dataset can get bigger. Any help would be appreciated. -
how can i apply ajax to an online ide made in django?
github link:https://github.com/SkvProgrammer/online-ide-django Please help me applying ajax to this django app