Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Incorrect type. Expected pk value, received str
I have 2 django models: Post and Comment: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=120) class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=120) post = models.ForeignKey(Post,on_delete=models.CASCADE) class PostCommentCreateView(APIView): queryset = Comment.objects.all() serializer_class = PostCommentCreateSerializer def get(self, request, format=None, *args, **kwargs): serializer = PostCommentCreateSerializer() return Response({'serializer':serializer.data}) def post(self, request, *args, **kwargs): post = int(self.kwargs['postid']) print(post) #1 comment_data = request.data data_ = [elem for elem in comment_data.values()] content = data_[0] csrf = data_[1] user = request.user.username new_comment = {'user':user,'content':content,'post':post, 'csrfmiddlewaretoken':csrf} commentdict = QueryDict('', mutable=True) commentdict.update(new_comment) serializer = PostCommentCreateSerializer(data=new_comment) if not serializer.is_valid(): return Response({'data':serializer.errors}) serializer.save() userimage = request.user.profile.image.url resp_data = { 'user':user, 'userimage':userimage, 'content':content } return Response({'data':resp_data}) class TrackCommentCreateSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['user','content','post'] When I try to post a comment with the post id, I get an error that a pk value is expected and not a string. Thank you for any suggestions -
Is there a way to run 1000 multiprocess, all running together
Due to a problem, I need to run 1000+ multiprocess, all running at the same time. Is that possible in Django and Python? -
Wagtail ReadOnlyPreviewPanel?
I would like to be able to dynamically update a readonly field. I'm using the ReadOnlyPanel as described in the following post: Wagtail: how to set calculated fields (@property) title in admin So when a user changes a certain value, for example in an InlinePanel, the read only field should update and the user can preview what the read only field will look like before publishing. Is this possible currently in Wagtail? -
How create appointment system in Django
Please I am currently working on Hospital Management System project but a bit stack for a while now. In my App, I want to set the patient to the appointment Model. Patients' details are shown in a table and what I want to do is when a row is clicked the patient is assign to the Appointment form and once the date and time are set, the data is saved in the appointment module. Thanks -
Django DateInput placholder
I am new to django and I have problem with showing my DateInput form. I want to use placholder in my DateInput, but its not working. Let me show you my code. forms.py class MyForm(forms.Form): my_date_field = forms.DateField(widget=forms.widgets.DateInput(attrs={"type":"date", 'placeholder': 'Select a date', 'required': 'required'}), label='Date') form.html <html lang="en"><head> <meta charset="UTF-8"> <title>Prva</title></head><body><form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button></form></body></html> I get this result And one more question, is there any way to make only year select DateInput. -
Django ms sql server 2014 Db configuration
Database connection between django and MicroSoft SQL server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Hospital', 'USER': 'root', 'PASSWORD':'upload', 'HOST':'192.168.1.4', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } I tried some methods. but it repeatedly showing below error. File "C:\Users\surendar\Desktop\pybatch\venv\lib\site-packages\django\db\utils.py", line 121, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Failed to run django app using docker containers
I'm trying to run a Django app on localhost:8000. I have a docker-compose.yml file that creates 3 containers (badgr-server_api, badgr-server_memcached and badgr-server_db_). When I run docker-compose up it says starting 2 of the containers and creating the 3rd (badgr-server_api) and I only see memchased and db running, see screenshot. I have tried deleting the badgr-server_api and running it again, I tried removing the image. I also ran docker-compose build again but I just can't get it to run. I hope someone can help please. [docker-compose up screenshot][1] After running docker, I also ran this command: docker-compose exec api python /badgr_server/manage.py migrate and get this result: File "/badgr_server/manage.py", line 13, in <module> File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 212, in get_connection_params isolation_level = options.pop('isolation_level', 'read committed') TypeError: pop() takes no arguments (2 given)``` This is my docker-compose.yml: ```# A dockerized badgr-server stack for development version: '3.3' services: # this container mirrors in the app code and runs the django dev server api: build: context: . dockerfile: .docker/Dockerfile.dev.api depends_on: - "db" - "memcached" command: /badgr_server/manage.py runserver 0.0.0.0:8000 volumes: - ./apps:/badgr_server/apps - ./manage.py:/badgr_server/manage.py - ./.docker/etc/settings_local.dev.py:/badgr_server/apps/mainsite/settings_local.py networks: - badgr ports: - "8000:8000" # this container runs memcached memcached: image: 'bitnami/memcached:latest' expose: - "11211" networks: - badgr # … -
Django - TemplateSyntaxError - Could not parse the remainder: ' + 1' from 'forloop.counter + 1'
I'm building a site which there's comments and stuff. And I want to users to see a icon for their comments and that should toggle two more buttons which are edit and delete. In order to do this I have to give different ids for each div that I want to be toggled. So here is my try: {% for comment in object.comment_set.all %} <!--Rest of the code--> {% if comment.author == request.user %} <div> <button class="btn btn-outline-secondary" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseComment{{ forloop.counter }} multiCollapseComment{{ forloop.counter + 1 }}"> <i class="fas fa-ellipsis-v"></i> </button> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseComment{{ forloop.counter }}"> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{%url 'posts:comment_edit' object.pk comment.pk%}">Edit</a> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseComment{{ forloop.counter + 1 }}"> <a class=" btn btn-outline-danger btn-sm mt-1 mb-1" href="{% url 'posts:comment_delete' object.pk comment.pk %}">Delete</a> </div> </div> </div> </div> {% endif %} <!--Code here too--> {% endfor %} But it gives me a TemplateSyntaxError that could not parse the remainder '+1'. But I just want to access to the counter + 1 value from template. I have thought about adding new template tag but I do not think that is related. I can't just pass some additional … -
Crispyform Django : is there any way to get multi field with CrispyForm?
Is possible to get multiple image upload field with CrispyForm? If I want to upload multiple Image? class CreateStoryForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreateStoryForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.field_class = 'mt-10' self.helper.layout = Layout( Field("title",css_class="single-input"), Field("image",css_class="single-input"), ) self.helper.add_input(Submit('submit','Add a story',css_class="single-input textinput textInput form-control")) class Meta: model = Story widgets = { 'title':forms.TextInput(attrs={'class':'','style':'list-style: none;','placeholder':'Lunch time'}), } fields = ('title','image',) -
Parsing/Converting Excel formatted Data to HTML Tags or Quill format in Python
I have a large excel file with a column of descriptions. In each row there is some text with in the standard Excel Format with bullets and carriage returns, like this: My first Line Second Line sub bullet 1 sub bullet 2 Sentence about something another bullet Another bullet Another sentence I need to convert these ~excel~ formatted rows into HTML tags with <p>, <ul>, <li>... It would be even better to convert them directly into the Quill Json format, but I'm will to settle for the HTML tags for the interim as that will get be half way there to the Quill format. How can I do this? -
How to use widgets in django-filter fields?
Wanted to set widgets "class":"form-control" to django-filter fields. filters.py from django_filters import FilterSet,DateFilter,CharFilter,DateFromToRangeFilter from django_filters.widgets import RangeWidget,CSVWidget,DateRangeWidget from django import forms from .models import Blog class BlogFilter(FilterSet): start_date = DateFilter(field_name="created_at",lookup_expr='gte',label='From date', widget=DateFromToRangeFilter(attrs={ 'placeholder':'YYYY/MM/DD', 'class':'form-control' }) ) end_date = DateFilter(field_name="created_at",lookup_expr='lte',label='To date') blog_name = CharFilter(field_name="blog_name",lookup_expr='icontains',label='Blog Name', widget=TextWidgets(attrs={ 'class':'form-control' }) ) class Meta: model = Blog fields = ('category','status','user') tried to write widget in meta class also but didn't work. Which widget to be used for CharFilter? (like we use forms.TextInput(attrs={'class':'form-control'} in django forms) Which widget to be used for DateFilter? -
Django channels integration into django project problem
I'm following this Django channels tutorial - https://channels.readthedocs.io/en/latest/ I got to the part where I'm trying to "Enable a channel layer" - https://channels.readthedocs.io/en/latest/tutorial/part_2.html#enable-a-channel-layer Then, I got that problem: [Errno 61] Connect call failed ('127.0.0.1', 6379) - enter image description here and chrome inspect shows: enter image description here -
How can I use atomic and roll back in django?
i want to save dict that are in list into model Django,but it is possible to happen error.if there is any error i want to roll back return all of dict that are saved in database. def test(): with transaction.atomic(): for i in list_pr: try: product_obj = Product.objects.get(pk=i) product_obj.avail=True product_obj.save() except Exception as e: exceptions.append({'id': i,'error': str(e)}) -
Django model virtual field
Just faced an issue with defining the virtual field for the django model. IE, the column which I will set by an initializer, but without saving into DB. I need this to support the some API, where I pass single column, but receive couple columns(don't ask why it was implemented this way). So, I have a model(simplified for the example): class RentalFee(TimeStampedModel): public = models.BooleanField(default=False) required = models.BooleanField(default=False) name = models.CharField(max_length=150, null=True, blank=True) #... etc but due creation, I should pass the status with some string value: rental_fee = BookingsyncRentalFee(status='test', name='aaa'). Now I receive error RentalFee() got an unexpected keyword argument 'status' So, how is it possible to add the virtual column to the django model? PS: I know that it is no need to do anything, if I will pass the new column by setter, ie: rental_fee = RentalFee(name='some name') rental_fee.status = 'public' It works as well. I m interesting how to do same using init. UPD: I have found not very elegant way with just overriding init method: class RentalFee(TimeStampedModel): public = models.BooleanField(default=False) required = models.BooleanField(default=False) name = models.CharField(max_length=150, null=True, blank=True) def __init__(self, *args, **kwargs): status = kwargs.pop('status', None) if status: self.status = status super().__init__(*args, **kwargs) And it … -
django check the data in the fields if exists in another objects
I have some wonders if i can make an object with django and this object contains special fields which no other object can have : In my situation i have passengers ,flight , chair classes and i need the passenger can have only one chair in flight and chair can only be booked by one passenger and all related to flight so i can book the chair to anyone in another flight. in model.py class Passenger(models.Model): passenger_first_name = models.CharField(max_length=150) passenger_last_name = models.CharField(max_length=150) passenger_flight = models.ForeignKey(Flight ,on_delete=models.CASCADE) passenger_chair = models.ForeignKey(Chair, on_delete=models.CASCADE class Flight(models.Model): flight_name = models.CharField(max_length=150) flight_from = models.CharField(max_length=50) flight_to = models.CharField(max_length=50) aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) flight_Date = models.DateTimeField() class Chair(models.Model): chair_types = ( ("Economy", "Economy"), ("Business", "Business")) chair_name = models.CharField(max_length=50) chair_type = models.CharField(choices=chair_types ,max_length=8) in view.py def AddPassengerForm(request): form = PassengerTicketForm(request.POST) if request.method == 'POST': if form.is_valid(): if Passenger.objects.filter( passenger_flight=form.cleaned_data["passenger_flight"]) and Passenger.objects.filter( passenger_first_name=form.cleaned_data["passenger_first_name"]) and Passenger.objects.filter( passenger_last_name=form.cleaned_data["passenger_last_name"]): print("passenger's chair already booked") elif Passenger.objects.filter( passenger_chair=form.cleaned_data["passenger_chair"]) and Passenger.objects.filter( passenger_flight=form.cleaned_data["passenger_flight"]): print("chair already booked") else: form = PassengerTicketForm(request.POST) print("thank you for uos") context = { "pax_ticket_form": form, } return render(request, 'index.html', context) this method works very well but i would like to know if there is cleaner or better method to do that. I appreciate … -
Pass additional attribute to django-filter
I'm using django-filter together with DRF. I have a favourite-model, which is linked to several other models through a GenericRelation. To filter for entries which have a favourite-flag, I've created a custom FavouriteFilter, which I add to the respective model. I would like to query for the content_type_id of the respective model in order to limit the results from Favourite. However, I don't know how I can pass down the model to the filter-method in the FavouriteFilter. Here's a code snippet to illustrate the issue: class ProjectFilter(BaseFilter): favourite_only = FavouriteFilter() class FavouriteFilter(django_filters.BooleanFilter): """ A custom filter which returns a users favourites of an element """ def __init__(self, *args, **kwargs): # gettext_lazy breaks the OpenAPI generation => use gettext instead kwargs['label'] = gettext("My favourites") super(FavouriteFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value == True: user = get_current_user() content_type = ContentType.objects.get_for_model(<model>) return qs.filter(pk__in=Favourite.objects .filter(owner_id=user) .filter(content_type_id=content_type) .values_list('object_id', flat=True) ) else: return qs In this example, the <model>-attribute is missing. How can I pass down this information from Project to the filter? -
ERROR in node_modules/stream-chat/dist/types/connection.d.ts
i follow this tutorial https://getstream.io/blog/realtime-chat-django-angular/ . I had been faced to an error while start the project by using npm-start command. I will show the error in below. enter image description here -
How to order messages based on the time its send like in normal chats?
Hey guys I am having trouble with ordering the messages based on the timestamp like in normal chats. How to do it? can anyone give me a proper solution? I have updated the question with the model manager I use. This is the model. class Chat(models.Model): first_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='first_user_chat', null=True) second_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='second_user_chat', null=True) timestamp = models.DateTimeField(auto_now_add=True) class ChatMessage(models.Model): chat = models.ForeignKey(Chat, blank=True, null=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sender', on_delete=models.CASCADE) message = models.TextField() # read = models.BooleanField(blank=False, null=True) timestamp = models.DateTimeField(auto_now_add=True) model manager class ChatManager(models.Manager): def by_user(self, user): qlookup = Q(first_user=user) | Q(second_user=user) qlookup2 = Q(first_user=user) & Q(second_user=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs # method to grab the thread for the 2 users def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None, None # looks based off of either username qlookup1 = Q(first_user__username=username) & Q(second_user__username=other_username) qlookup2 = Q(first_user__username=other_username) & Q(second_user__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ try: user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model(first_user=user, second_user=user2) obj.save() return obj, True except Klass.DoesNotExist: user2 = None return None, False views class ChatView(LoginRequiredMixin, … -
Forbidden (CSRF token missing or incorrect.): /data
I am trying to post data to a URL using the requests library, code below. data = {"a": 1, "b": 2} cookies = {'csrftoken': django.middleware.csrf.get_token(request)} app_url = "http://localhost:8000/data" headers = {"app_key": key} r = requests.post(app_url, data=json.dumps(data), headers=headers, cookies=cookies) I am getting Forbidden (CSRF token missing or incorrect.): /data [11/Sep/2020 14:45:22] "POST /data HTTP/1.1" 403 2513 I used the django-cors-headers package also and allowed CORS_ALLOWED_ORIGINS = [ "http://localhost:8000" ] Still, the forbidden error is there. I can make the view csrf_exempt but I don't want to compromise on security. Is there any other way? -
Interaction of python and java usingpy4j during deployment
Recently I have been working on a project to make a RESTapi using Django rest_framework. This framework requires some processing and objects which need to be done in java. I came across this library called Py4J which allows us to access Java objects, collections etc from a python environment. What I could understand was that To make JVM accessible to python I had to interact with another server localhost:25333. I have written a very basic code to test: Views.py from py4j.java_gateway import JavaGateway class TestClass(APIView): permission_classes = [AllowAny] authentication_classes = [] @staticmethod def post(request): gateway = JavaGateway() fn = gateway.entry_point.getFunc() response = Response() response.data = {"res": fn.print()} return response Func.java public class Func{ public String print() { return "Hello from java"; } } TestGateway.java import py4j.GatewayServer; public class TestGateway { private Func func; public TestGateway() { func = new Func(); } public Stack getFunc() { return func; } public static void main(String[] args) { GatewayServer gatewayServer = new GatewayServer(new TestGateway()); gatewayServer.start(); System.out.println("Gateway Server Started"); } } This code works as expected since every interaction is happening on the localhost. But I need to deploy both the java application and django rest api on Google AppEngine. How will the two codes … -
Merge equal fields in returned response independent of amount of objects Django Rest Framework
How can i merge equal fields and append different values to the fields in the returned response into one, independent of the amount of objects? When accessing the enpoint, i currently get the following response: [ { "colors": [ "Red", "Orange", ], "styles": [ "Rock" ], "application": [ "Wall" ], "material": [ "Mosaic" ] }, { "colors": [ "Yellow", ], "styles": [ "Mosaic" ], "application": [ "Wall" ], "material": [ "Ceramic" ] } ] While want to achieve something like the snippet bellow, where unique values are appended and equal fields are merged: [ { "colors": [ "Red", "Orange", "Yellow" ], "styles": [ "Rock" "Mosaic" ], "application": [ "Wall" ], "material": [ "Mosaic" "Ceramic" ] }, ] My serializer is structured like this: class ProductFiltersByCategorySerializer(serializers.ModelSerializer): """ A serializer to display available filters for a product lust """ colors = serializers.StringRelatedField(read_only=True, many=True) styles = serializers.StringRelatedField(read_only=True, many=True) application = serializers.StringRelatedField(read_only=True, many=True) material = serializers.StringRelatedField(read_only=True, many=True) class Meta: model = Product fields = ( 'colors', 'styles', 'application', 'material' ) My viewset is structured like this: class ProductFiltersByCategory(generics.ListAPIView): """ This viewset takes the category parameter from the url and returns related product filters """ serializer_class = ProductFiltersByCategorySerializer def get_queryset(self): category = self.kwargs['category'] return Product.objects.filter(category__parent__name__iexact=category).distinct() … -
rendering the correct width with css
I'll add some pics, to make everything clear.. this is how it should look and it looks like that but when the screen's width is less than 580px it looks as follows i'll share my html ans css and what i have tried.. my html: <div class="d-flex item"> <div class="image" style="background-image: url({{meal.image.url}});" data-aos="fade"> </div> <div class="text"> <a href="{% url 'meals:meal_detail' meal.slug %}"><h3>{{meal.name}}</h3></a> <p>{{ meal.description|truncatewords:15 }}</p> <p class="price">${{meal.price}}</p> </div> </div> <!-- .item --> if you don't use django forget that sintax used just imagine it's some random text, cz it is. my css: .bg-image, .half .image, .image-bg-fullwidth { background-size: cover; background-position: center center; background-repeat: no-repeat; background-attachment: scroll; } .half .text, .half .image { width: 100%; } @media (min-width: 992px) { .half .text, .half .image, .m { width: 50%; } } .half .text { padding: 7%; background: #000; } .half .text h2 { color: #fff; } @media (max-width: 991px) { .half .image { height: 250px; } } .image-bg-fullwidth { display: block; height: 300px; } .menus .item .image, .menus .item .text { width: 50%; } .menus .item .image { background-size: cover; background-position: center center; } .menus .item .text { padding: 40px; background: #000; } .menus .item .text h3 { color: #fff; font-size: 22px; … -
How to override user.save() method
I only want to override the save() method of the built-in User model. Is it possible to do it without creating a new model? -
How to add spaces between lines and align elements in the same column in InlineCheckboxes of crispy-form (Django)?
I have a form field which is CheckboxSelectMultiple and I use InlineCheckboxes from crispy-forms to make all those check boxes inline. Since I don't have the image of it I will use code snippet as an example. this is how I want the form looks like in html and I will use stars instead of boxes *name1 *name2 *name3 *name4 *name5 *name6 *name7 *name8 *name9 *name10 *name11 *name13 What can I do to add more spaces between each line and make it aligns vertically like shown above? here is my forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] widgets = {'student': forms.CheckboxSelectMultiple()} def __init__(self, class_pk, current_user, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) current_student = Class.objects.get(id=class_pk) self.helper = FormHelper(self) self.fields['student'].queryset = current_student.student.order_by('first_name') self.helper.layout = Layout( InlineCheckboxes('student') ) my current html. (it's not aligned perfectly as shown below!) <form method="POST" class="ml-auto mr-auto"> {% csrf_token %} <div style="text-align: justify;">{% crispy form form.helper %}</div> <button type="submit" class="btn btn-success btn-sm" style="font-size: 15px" > Check </button> </form> Thanks before hand! -
Django model works on local but not after deploy
I am making a simple personal website. I make a box to input user data (name, email, and message). I want this data is sent to my django admin. I have test it and it works in local. But when i deploy it, i didn't get any data whenever i submit from the box. Note : i do not use django form for some reason. I want to use my own custom form. this is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Feedback from .forms import FeedbackForm def index(request): if (request.method == "POST"): name = request.POST.get("Name") email = request.POST.get("Email") message = request.POST.get("Message") record = Feedback(name=name, email=email, message=message) record.save() return render(request, 'main.html') this is my models.py from django.db import models class Feedback(models.Model) : name = models.CharField(max_length=50) email = models.EmailField() message = models.CharField(max_length=200) def __str__(self): return self.name