Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass a primary key in a Django Create View
I'm working with a class-based view in which I show a form whose information is associated with a model (called Tratamiento), that model has a foreign key to the model called Paciente. My problem is that when saving a treatment, the form shows all the available patients, being that the behavior I want is that from a form that lists all the patients, when I select one, this patient can add a treatment. That is to say, that in a new template (in this case, I am testing with a modal) the patient is fixed and that there is not a dropdown where all the patients are shown. This is the url: url(r'^tratamiento/$', views.TratamientoCreateView.as_view(), name='tratamiento'), This is my Tratamiento model: class Tratamiento(models.Model): class Meta: ordering = ['doctorDerivador'] doctorDerivador = models.ForeignKey(DoctorDerivador, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE) diagnostico = models.CharField(max_length=50, null = True, blank = True) fechaInicioTratamiento = models.DateField() motivoConsulta = models.CharField(max_length=100, null = True, blank = True) fechaFinTratamiento = models.DateField(null=True, blank=True) evaluacion = models.TextField(null=True, blank=True) This is my view: class TratamientoCreateView(BSModalCreateView): model = Tratamiento template_name = '../templates/tratamiento.html' form_class = TratamientoModelForm success_message = 'Success: Tratamiento dado de alta.' success_url = reverse_lazy('index') And this is what happens to me: Please could you tell … -
Why is python manage.py run server giving me an error
Jacob-Mac-mini:TachlisGeredt kovyjacob$ python manage.py runserver 0.0.0.0:8000 File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax this is the error I am getting, I have no idea why. What should I do? -
Django/Wagtail - most efficient way to refine page queryset by multiple parent pages
I have a list of category pages obtained as follows: category_ids = request.GET.getlist('category[]') category_pages = MyCategoryPage.objects.filter(pk__in=category_pks) What I'd like to do is refine a list of pages to include only those that are children of the categories specified above. I'm aware that you can do this for one object as follows: pages = MyModel.objects.child_of(category) But as far as I can tell there is no way to do child_of(filter_categories) for more than one parent. In normal Django, where I'd probably have a category ForeignKey on MyModel, I'd just do: pages = MyModel.objects.filter(category__in=filter_categories) But again I'm not sure that I can do that in Wagtail. I know I could probably loop through all the filter categories and append them to a list: pages = [] for category in filter_categories: pages.append(MyModel.objects.child_of(category)) ...but that doesn't seem very efficient and it would return a list rather than a queryset. I've searched the docs but can't find any more direct way of achieving this. -
Is it more efficent to assign a database query to a variable for a single view than to have multiple queries
If I want to count the number of people in a database several different ways, would it be more efficient to assign the initial People.get.all() to a variable (version A below) than to query it each time. Effectively, does Version A result in a single hit to the db, while Version B results in two? Version A: people_var = People.get.all() last_name_filter = people_var.filter(last_name=('John')).count() first_name_filter = people_var.filter(last_name=('John')).count() Version B: last_name_filter = People.filter(last_name=('John')).count() first_name_filter = People.filter(last_name=('John')).count() -
Many models in Foreign Key
Let's say I have a model, employee: Employee Name: CharField Email: EmailField Type: ForeignKey The problem is with the type field. I want the foreign key to be able to be several different types of models. For example, one for Software Developer, another for Janitor, and so on. I could do this by having a foreign key field for all types, and setting many to null, but this seems bad. Does this make sense? How can I achieve this? Thanks!! -
Why is Logout working as a GET Request and not a POST Request?
This is the html file <a class="nav-link" href="{% url 'logout' %}">Logout</a> <form action="{% url 'logout' %}" method="POST" id ="logout"> {% csrf_token %} <input type ="hidden"> </form> This code in view.py. def logout(request): if request.method == 'POST': print("post-request") auth.logout(request) return redirect('index') else: print(request.method) auth.logout(request) return redirect ('index') Why is the Logout a GET request and not a POST request ? I made some changes in projects based on the documentation and could not understand why you can be successfully logged out with a GET request. https://docs.djangoproject.com/en/3.0/topics/auth/default/ -
Django Roll-base permission and How to make group of user and assign them different permission
Hey everyone I'm make web app were many group of user are there like HR, owners, labor so I'm trying to make group ok user and assigned them differently permission but I'm not able to find out how can I make group and assigned them differently permission ,so can anyone just guid me ho I can achive my gole I use Django UserCrearionForm for creating user I also readu django- roll-base permission documentation stackover flow everything then main problem is am not able to assign permission to gropu /user -
Instance of 'ManyToManyField' has no 'all' member
I am trying to get the sum of the prices of the items. To do that i decided to create a method inside my Order class in my models.py def get_order_total(self): return sum([itemz.item.price for itemz in self.items.all()]) when i try to acces the method i get this error 'Instance of 'ManyToManyField' has no 'all' member'. my full Order class: class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL) items = models.ManyToManyField(OrderItem) Quantity = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True, null=True) total = models.CharField(max_length=100) status = models.CharField(max_length=200, null=True, choices=STATUS) def get_order_items(self): return self.items.all() def get_order_total(self): return sum([itemz.item.price for itemz in self.items.all()]) def __str__(self): return '{self.order_head}'.format(self=self) related models: class order_header(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) Seller = models.CharField(max_length=100, blank=False, default="Seller") Type = models.CharField(max_length=100, default="cash") Client = models.ForeignKey(customer, blank=True, null=True, on_delete=models.SET_NULL) Note = models.CharField(max_length=100, blank=True, default="Discount: ") Order_Id = models.IntegerField(primary_key=True, default=random, editable=False) def __str__(self): return 'Order Id: {self.Order_Id}'.format(self=self) class item(models.Model): name = models.CharField(max_length=100, blank=False) box_quantity = models.CharField(max_length=10) Quantity_in_box = models.CharField(max_length=10) code = models.CharField(max_length=15) price = models.CharField(max_length=100) expiry = models.CharField(max_length=100) supplier = models.ForeignKey(supplier, blank=False, null=True, on_delete=models.SET_NULL) warehouse = models.ForeignKey(warehouse, blank=False, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(category, blank=False, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): … -
Comments and reply working properly but in the template after reloading the page, the reply is showing as comment
Hey guys I am facing a weird situation where comments and reply function are working properly but in the template after reloading the page, the reply is showing as comment. when I submit the reply, it shows as a reply, but if I reload, it changes to a comment but in the admin it would still be a reply. So no error there. In the admin, all the comments and replies are being shown correctly, but the problem is with the template it seems. Please do help. Thanks views @login_required def comment_section(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, reply=None) if request.POST: comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs) else: comment = Comment.objects.create(post=post, user=request.user, content=content) comment.save() else: raise ValidationError('Something went wrong!') else: comment_form = CommentForm() context = { 'post':post, 'comment_form':comment_form, 'comments': comments, } if request.is_ajax(): html = render_to_string('posts/comment_section.html', context, request=request) return JsonResponse({'form': html}) comment-snippet.html <!-- Comment showing section --> <div class="main-comment-section"> <div class="container-fluid mt-2"> <div class="form-group row"> <!-- Comment Form --> <form class="comment-form" method="post" action="{% url 'posts:comment_section' post.slug %}"> {% csrf_token %} <div class="form-group"> <textarea class="rounded" … -
Django Session with Django Rest Framework and HTML on front
I am currently working on project where I am a project manager. My team are building back-end for web site and mobile app and we decided to use for this purpose (one back-end for multiple product) django rest framework. We don't have any front-end developer in our team only HTML template without js scripts which we plan to use for test some features. After implementing some features like log-in and sign-up developers said me that for testing built functionality via front-end (html) we need building front-end via any js framework because of troubles with django session while using HTML for front-end and django rest framework. Is it true or my team members have weak expertise -
Django - single model with fields from multiple databases
I'm trying to create a model that will be initiated from 2 different DBs (first is MySQL, second is mongoDB). For example: class My(models.Model): field_1 = models.CharField() # Should relate to MySQL field_2 = models.CharField() # Should relate to mongoDB class Meta: managed = False Is this possible in Django? P.S: I know about the Django database routers, but i didn't find if it possible to mix a single model with multiple databases -
Function based views to class based views
How would one change this function based view into a class based view? I am facing problem in displaying the vote count results using class based views. def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.method == 'POST': selected_option = request.POST['poll'] if selected_option == 'option1': poll.option_one_count += 1 elif selected_option == 'option2': poll.option_two_count += 1 elif selected_option == 'option3': poll.option_three_count += 1 else: return HttpResponse(400, 'Invalid form') poll.save() return redirect('results', poll.id) context = { 'poll' : poll } return render(request, 'poll/vote.html', context) -
Django WebScrap Beautiful Soup Extract _Field Value
So I'm almost finished with my script to pull data from this API but i cant seem to pull dads phone number. I believe whats happening is it goes to the first _field and sees mom and not dad and just skips. How do i get it to check the second _field value that is found. Below is code and sample xml data. Thanks def ImportStudentGuardian(request): print("Getting student guardian data from SIS for K-8 (Creation-Update)") #Pulls K-8 Guardians url = "blank" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') xml_string = ET.fromstring(encode_xml) print("Creating guardian records in database") soup = BeautifulSoup(encode_xml, 'lxml') for student in soup.findAll('student'): #XML Values psid = student.find("id").text try: #Gets Instance of Student psid_obj = Student.objects.get(studentpsid=psid) # If Mom Doesnt Exist Create if not StudentInformation.objects.filter(studentpsid=psid_obj,relation = 1): try: mother = student.find("contact").find("mother").text mom_cell = student.find("_extension_data").find("_table_extension").find("_field").find("value").text mom_name = student.find("_extension_data").find("_table_extension").find("_field").find("name").text if mom_name == "motherdayphone": m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = 1, guardian_cell = mom_cell) print("No record of Mom for this student, creating record with phone number") m.save() else: m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = 1) print("No record of Mom for this student, … -
Group By in Django ORM?
I have two models class ShareType(models.Model): code = models.CharField(max_length=10, null=False, blank=False) type = models.CharField(max_length=56, null=False, blank=False) class ShareAllocation(models.Model): session_key = models.CharField(max_length=40, null=True) share_type = models.ForeignKey(ShareType, on_delete=models.CASCADE, null=True) share_holder = models.ForeignKey(ShareHolder, on_delete=models.CASCADE, null=True) number_of_shares = models.IntegerField(null=False, blank=False) amount_paid = models.IntegerField(null=False, blank=False) amount_unpaid = models.IntegerField(null=False, blank=False) is_beneficial_owner = models.BooleanField(null=False, blank=False) new to the django ORM, my output needs to show ShareType.code Total Number Of Shares for this type Amount Paid Amount Unpaid is_beneficial_owner i am using this query, which is obviously incorrect. share_structure = ShareType.objects.annotate(Sum('shareallocation__number_of_shares')).\ filter(shareallocation__session_key=self.storage.request.session.session_key) -
How to use wordpress + django to build a website
I have a wordpress website ,and i want to add more functionality with django framework.Is it posible to build a hybrid website with Wordpress and Django..??? -
How to create a html file in django framework?
How to create multiple html files with dir and their file names using python's django framework. -
How to upgrade Mysql 5.5 to 5.6 without data loss on aws-ec2?
MySQL server (5.5) is running on aws-ec2 instance with following linux details NAME="Amazon Linux AMI" VERSION="2015.09" ID="amzn" ID_LIKE="rhel fedora" VERSION_ID="2015.09" PRETTY_NAME="Amazon Linux AMI 2015.09" ANSI_COLOR="0;33" CPE_NAME="cpe:/o:amazon:linux:2015.09:ga" HOME_URL="http://aws.amazon.com/amazon-linux-ami/" Since Django 2.2 doesn't support Mysql 5.5 https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-notes . I want to upgrade MSQL to 5.6 . We don't have backup server and we don't want new server . Creating sql dump , removing MySQL 5.5 then installing MySQL 5.6 and importing dump will it work ? Since server has 100 GB of data importing the dump will be a long process and we will have considerable amount of downtime .There can be some issue with data while importing dump in 5.6 . Is there a way to upgrade MySQL without data loss and less downtime ? -
API is not working in flutter_web(Enabled CORS)
I Made one POST API in Django rest framework. It working perfectly in Postman in also chrome and other browsers but it is not working in my flutter_web project. it is giving me XMLHttpRequest error. you can check my api from https://findweight.herokuapp.com/idealweight which takes raw data for example 5. -
ImportError: PILKit was unable to import the Python Imaging Library. Please confirm it`s installed and available on your current Python path
i have pillow installed as well. so how is this error coming up. ImportError: PILKit was unable to import the Python Imaging Library. Please confirm it`s installed and available on your current Python path . -
serializer.validated_data issue with overriden perform_create()
I am setting up a Django REST application where peopple can review restaurants. So far I have those models: class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() My serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = RestaurantId field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' My views: class RestaurantIdViewset(viewsets.ModelViewSet): queryset = models.RestaurantId.objects.all() serializer_class = serializers.RestaurantIdSerializer class RestaurantReviewViewset(viewsets.ModelViewSet): queryset = models.RestaurantReview.objects.all() serializer_class = serializers.RestaurantReviewSerializer permission_classes = [IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(review_author=self.request.user) class StarterPicsViewset(viewsets.ModelViewSet): queryset = models.StarterPics.objects.all() serializer_class = serializers.StarterPicsSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): if models.RestaurantReview.objects.filter(id=serializer.data["restaurant_review_id"], review_author=self.request.user).exists(): serializer.save(pics_author=self.request.user) I have set up permissions as well so only the review_author can update his reviews and pics_author can update his pictures. My permissions: class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.pics_author == request.user class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return … -
How to create multiple sessions in the pythan-based Django framework, which stores and saves data, so that people can answer a survey simultaneously?
I am doing a survey with Django and everything runs fine. The only problem I get is when multiple respondents answer the survey simultaneously. Then, the current session is being overwritten and some strange effects take place since I store the data in a session. How can I create a unique session for every respondent so that more than one can answer the survey at the same time? Thanks in advance! def home(request): user_id = random.randint(0,10000) initial={user_id:request.session.get(user_id, None)} form = SurveyForm(request.POST or None, initial=initial) if request.method == 'POST': # Save input data in session if form.is_valid(): request.session['age'] = form.cleaned_data['age'] request.session['gender'] = form.cleaned_data['gender'] request.session['education'] = form.cleaned_data['education'] return redirect('heat_tech_survey:InformationDCE') else: return render(request, 'heat_tech_survey/home.html', {'form': form}) else: return render(request, 'heat_tech_survey/home.html', {'form': form}) def RandomDCE(request): # Create independent Counters for every Choice Set, so people # can use the "Back-Button" in the Browser without increasing the counter # "count" for every website-reload in the function global count, C1, C2, C3, C4, C5, C6, C7, C8 # Randomize the order of Choice Sets for each respondent if count == 0: global number_list, number_list2, choiceblock number_list = [2, 3, 4, 5, 6, 7, 8, 9] number_list2 = [10, 11, 12, 13, 14, 15, 16, 17] random.shuffle(number_list) … -
Can i use django chat app to chat with friends
I have seen many tutorials about django real time chat app. So can that chat be used to chat with friends. The chat involves many things like channels, sockets, asgi and many more so can the django made chat app be used to chat with friends.... -
Which package to use for a notification system in Django
So I have to create a project that uses notifications (like Facebook). If a user has say 100 likes on his post, on his notifications page he should see a link like "100 likes on ur post". Upon clicking on this link, he should go to his post. So basically the number of likes were counted while he was offline and notified to him when he came online. After some googling, I found 2 promising packages, namely: Django notifications and Django channels and also Django messages and Django signals. My question is which should I use, and what is the difference between them and specific use cases? -
How to log out with django-rest-knox?
I am using django-rest-knox for token based authentication. I am able to log in, get user details, and logout using Postman and my react app in development server. However, in production, i am able to log in, but not able to get user details or log out using the token provided. The error message says Authentication credentials were not provided. in case of wrong token, it should return Invalid token. What am i missing here? All settings, urls, views, serializers are same in development server and in production server, except for the database password and host. -
Getting form field name from cleaned_data dictionary to add a form error
I'm not entirely sure how to phrase my question, so I'll just start with a simple example then introduce my code: I have 3 variables that each refer to a piece of data from a database. A = data_1 B = data_2 C = data_3 I put these 3 variables in a list so I can iterate through them and perform various tasks that need to be done. LIST = [A, B, C] Most of the time, I refer to either A, B, or C so I can access the data associated with that variable and everything is okay. What I'm trying to do, though, is sometimes I just want the variable itself without the data associated with it. In my specific case, the variable name is the name of a form field in my web application and it refers to the data stored in that specific field. Now to show my actual actual code (I may have included WAY more information than necessary. Skip down to "MY QUESTION" below to see what my actual question is and if you need to reference the models it's here): Models.py class ProjectName(models.Model): project_name = models.CharField(max_length=300) class Meta: ordering = ['project_name'] def __str__(self): …