Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running Django application in Docker with external configuration file
I have a Django application, I am running the application using the below command config=/path_to_config/config.json gunicorn --bind 127.0.0.1:8000 server.wsgi --daemon But how do i pass the configuration file in Dockerfile, to start the docker conatiner. ENV PYTHONUNBUFFERED 1 RUN mkdir /app_name WORKDIR /app_name COPY ./app_name . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD ["--config=config.json", "gunicorn", "--bind", "127.0.0.1:8000", "server.wsgi"] -
Invalid request error while creating customer in Stripe
I am working on a payment gateway using Stripe API. I had split the card element into three elements as: cardnumer, cvc and cardExpiry. I have created the token using only cardnumber element and I am trying to create the customer in stripe. I am getting an error as : Request req_vL0Z2mkBIrhu7N: Invalid object /home/nishant/Development/ecommerce/project/shop/views.py in order_view source = request.POST['stripeToken'] … ▶ Local vars /home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_resources/abstract/createable_api_resource.py in create response, api_key = requestor.request("post", url, params, headers) … ▶ Local vars /home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in request resp = self.interpret_response(rbody, rcode, rheaders) … ▶ Local vars /home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in interpret_response self.handle_error_response(rbody, rcode, resp.data, rheaders) … ▶ Local vars /home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in handle_error_response raise err … ▶ Local vars Here is my payment.html: var stripe = Stripe('pk_test_nnGYKgpxl7AmicqNbcoGIMqQ008d6IpXgw'); // Create an instance of Elements. var elements = stripe.elements(); var style = { base: { color: '#32325d', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; // Create an instance of the card Element. **var cardnumber = elements.create('cardNumber', { ** classes : { base : "form-control", focus : "green", invalid : "error", }, style : style }); ** var cvc = elements.create('cardCvc', { ** classes : { … -
Django + Faker + factory_boy - BinaryField fake data problem
I have the following model: class Data(models.Model): data = models.BinaryField() version = models.FloatField() processed_on = models.DateTimeField() case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='full_vectors') And I have the following factory class for it: import factory from faker import Factory import pytz from michaela.models import Data from myapp.models import Case faker = Factory.create() stub_bytes_data = bytes("Sample binary data", 'utf-8') class DataFactory(factory.DjangoModelFactory): class Meta: model = Data data = stub_bytes_data version = factory.LazyAttribute(lambda _: faker. random_digit_not_null() / 1.0) processed_on = factory.LazyAttribute(lambda _: faker.date_time(tzinfo=pytz.timezone(faker.timezone()))) case = factory.Iterator(Case.objects.all()) I invoke creation of the fake data as follows: def test_sometest(self): # Given self.data = DataFactory.create_batch(250) # When # do something # Then # do something However, when I run Django test regime, I get the following error: ====================================================================== ERROR: test_sometest (myapp.tests.test_sometest.MyTestSuite) ---------------------------------------------------------------------- Traceback (most recent call last): File "/quality_assistant/main_site/server_monitor/tasks/myapp/tests/test_sometest .py", line 75, in test_sometest self.data = Data.create_batch(250) File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 576, in create_batch return [cls.create(**kwargs) for _ in range(size)] File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 576, in <listcomp> return [cls.create(**kwargs) for _ in range(size)] File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 564, in create return cls._generate(enums.CREATE_STRATEGY, kwargs) File "/usr/local/lib/python3.7/site-packages/factory/django.py", line 141, in _generate return super(DjangoModelFactory, cls)._generate(strategy, params) File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 501, in _generate return step.build() File "/usr/local/lib/python3.7/site-packages/factory/builder.py", line 279, in build kwargs=kwargs, File "/usr/local/lib/python3.7/site-packages/factory/base.py", line … -
Django oscar with DjangoCMS
I want to build a website with djangoCMS and django-oscar. I want to create a page with a product list like on this website : https://www.oskarvopsea.ro/products. I do not want to show any prices, there also will not be orders, I just want to show my product list and categories. There is any solution for combining DjangoCMS and Django Oscar. I do not want to edit my products page with CMS because I have django-oscar Dashboard and I can trought it. Can I do that the Django Oscar page to use to CMS base.html? Could you suggest me any solution for this problem? -
Django queryset How to perform query which groups two models on different field and then perform operations on it?
I am working on an ECommerce Application in which I need to create a stock management table with filters. For this, I need a proper query inside the queryset so that django-filters can work appropriately. Here are my models: The product model through which contains many product variants and a product is owned by a seller. class Product(BaseClass): seller = models.ForeignKey( Seller, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=50, db_index=True) sizes = models.ManyToManyField(SubCategorySize, through='ProductVariant') (...) Model of product variant: class ProductVariant(BaseClass): """ Model class which stores the product variants on the basis of sizes and also keeps a track record of the quantity according the sizes. """ product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='variants', db_index = True ) size = models.ForeignKey( SubCategorySize, on_delete=models.CASCADE, related_name='products', help_text='Select a desired size for product', db_index = True, blank=True, null=True ) quantity = models.PositiveSmallIntegerField( default=0, help_text='Quantity should be positive.' ) Model of OrderItem(which is connected by a product variant): class OrderItem(BaseClass): (...) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product_variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE, related_name='order_items') quantity = models.PositiveIntegerField() status = models.CharField(max_length=120,choices= ORDER_ITEM_STATUS, default='Processing') price = models.DecimalField(max_digits=9,decimal_places=2) Now basically I need to perform a query which does the following operation: A query Gives me: Summation of all the quantities of product variants … -
Comment form only submit once using Ajax
i have implemented a comment form to every posts of users, i have 3 posts on homepage. The first post submit comment only ones, when submit a second comment it saved in database but it displayed an error "Undefined", while the other posts submits comments normally as i wanted. What is missing in my code that is causing such error for the first post of user? Views: def home(request): #Comment form homepage if request.method == 'POST': post_id = request.POST.get("post_comment") post_obj = Post.objects.get(pk=post_id) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.commented_image = post_obj comment.save() # return redirect('/') else: form = CommentForm() context = {'form':form} if request.is_ajax(): html = render_to_string('ajax_newfeeds_comments.html', context, request=request) return JsonResponse({'form': html}) return render(request,'home.html', context) Ajax: <script type="text/javascript"> //HomeFeeds Comment $(document).on('submit', '.feeds-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: "{% url 'site:home' %}", data: $(this).serialize(), dataType: 'json', success: function(response) { $('#newfeeds-form').html(response['form']); $('textarea').val(''); }, error: function(rs, e) { console.log(rs.resopnseText); }, }); }); </script> Template: <span class="md-form"> <form enctype="multipart/form-data" class="feeds-form form-inline md-form form-sm" method="POST" action="{% url 'site:home' %}"> {% csrf_token %} <input type="hidden" value={{post.id}} name="post_comment"> <textarea name="comment_post" class="textinput textInput animated fadeIn" placeholder="Add a comment..." required="" id="id_comment_post{{ post.id }}" onkeyup=""></textarea> <button type="submit" class="submit" id="submit1-{{post.id}}" disabled><i class="fas fa-paper-plane"></i></button> </form> … -
How to test get_success_url in ClassBasedView for Django?
I'm trying to test my success_url method and couldn't find a way to test it correctly and increase my code coverage. #views.py def get_success_url(self): if self.question.type in [ Question.MULTIPLE_TYPE, Question.SINGLE_TYPE ]: return reverse("question") else: return reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE}) This is what I have tried in my tests.py file. #tests.py from factories import QuestionFactory def test_get_success_url(self): self.client.force_login(user=self.user) question = QuestionFactory(owner=self.user) if question.type in [ Question.MULTIPLE_TYPE, Question.SINGLE_TYPE ]: response = self.client.get(reverse("question")) else: response = self.client.get( reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE}) ) self.assertEqual(response.status_code, 200) -
daphne.service restart takes a lot of time
In one of my applications, I am using django channel. To deploy the application in aws ec2 instance I used daphne service. But when I restart the daphne service. It takes a lot of time to process. After a long period of time it returns as follows: command: sudo systemctl restart daphne Response: Job for daphne.service failed because a fatal signal was delivered causing the control process to dump core. See "systemctl status daphne.service" and "journalctl -xe" for details. When I run journalctl -xe, I got the following console returns (log): May 12 06:04:10 ip-172-31-21-97 daphne[3380]: 2020-05-12 06:04:10,453 INFO Starting server at tcp:port=8001:interface=127.0.0.1 May 12 06:04:10 ip-172-31-21-97 daphne[3380]: 2020-05-12 06:04:10,454 INFO HTTP/2 support enabled May 12 06:04:10 ip-172-31-21-97 daphne[3380]: 2020-05-12 06:04:10,454 INFO Configuring endpoint tcp:port=8001:interface=127.0.0.1 May 12 06:04:10 ip-172-31-21-97 daphne[3380]: 2020-05-12 06:04:10,456 INFO Listening on TCP address 127.0.0.1:8001 May 12 06:04:30 ip-172-31-21-97 uwsgi[3366]: [pid: 3373|app: 0|req: 1/1] 160.13.155.48 () {44 vars in 936 bytes} [Tue May 12 06:04:30 2020] GET / => gener May 12 06:04:30 ip-172-31-21-97 uwsgi[3366]: announcing my loyalty to the Emperor... May 12 06:04:30 ip-172-31-21-97 uwsgi[3366]: Tue May 12 06:04:30 2020 - [emperor] vassal textextraction.ini is now loyal May 12 06:04:32 ip-172-31-21-97 uwsgi[3366]: [pid: 3370|app: 0|req: 1/2] … -
PIP command for Django Installation
I have installed python using Anaconda platform, The problem is that when I want to install Django through command prompt, it shows an error 'pip is not recognized as an internal or external command.' Please suggest a solution. Thanks in advance. :) -
Importing Data from Api and Creating the Objects but i want to review and save them Manually
Currently I'm requesting an APi with AdminModel and it's getting saved Directly in my Database I'm creating objects with MyMOdel.objects.create() It get's Directly saved in my Database and able to access the Models from Admin Area. But i want to Get the Data when the API is Requested but don't want to save in my database but want them to be displayed in my admin panel under the models so that a user can go check and then save it Manually. Please Help me out in this. If code Required then let me know -
How to add custom button django admin
I want to add a custom buttom along with input text field. When the button clicks triggered the input text field will get a generated string value. enter image description here In the picture you can see a button 'Preview Link' when it is clicked it will generate a link to input field. [This is my first question on StackOverflow, If anything wrong with my approach please correct me] -
allauth Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I am using allauth and have my login/logout functionality working properly on the site (I can login/logout/register successfully in Selenium functional tests aswell). My problem is when I try to do unit tests to check the correct templates are being used for any view with the @login_required decorator. For example: View: @login_required def profile(request): return render(request, 'users/profile.html') Unit test: class ProfileTest(TestCase): def test_uses_profile_template(self): # it makes no difference if this is commented out or not #class MockUser: # is_authenticated = True response = self.client.get('/users/profile') #response.user = MockUser() self.assertTemplateUsed(response, 'profile.html') My urls: path('accounts/', include('allauth.urls')), And the error msg: NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name My biggest confusion comes from the fact everything works fine in functional tests and when using the site normally. Thank you. -
Invalid Geojson Object Django-leaflet [django]
This is the geojson object I am trying to render on Django with django-leaflet and django-geojson. {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"model": "rent_app.apartment"}, "id": "APT", "geometry": {"type": "Point", "coordinates": [38.771353, 8.984487]}}, {"type": "Feature", "properties": {"model": "rent_app.apartment"}, "id": "APT2", "geometry": {"type": "Point", "coordinates": [38.773155, 8.98525]}}], "crs": {"type": "link", "properties": {"href": "http://spatialreference.org/ref/epsg/4326/", "type": "proj4"}}} I get Invalid GeoJSON object while trying to render the geojson. Any solution? -
Get associated model in Django from the parent model in view
I have the following model: models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=250, default='New York', blank=False, null=False) And in views.py I should fetch users and userprofiles so that I can get it in home.html: views.py from django.contrib.auth.models import User def home(request): users = User.objects.filter(is_staff=True).select_related('userprofile') context = { 'users': users } return render(request, 'users/home.html', context) home.html {% for user in users %} <p>{{ user.username }}</p> {% for profile in user.userprofile_set.all %} <p>{{ profile.city }}</p> {% endfor %} {% endfor %} But the profile.city values are not being displayed in the page. What am I doing wrong here? How can I rectify it? -
How to Auto-Complete both HTML and Django-HTML simultaneously in VSCode?
I've installed Django support in VSCode,and associate */templates/*.html with django-html as the extension demands. However, it can't auto-compete HTML Tags as I've done so. And if I just associate HTML with itself, then it can't intellisense Django Template code. So anyone can help me about auto-completing both?? -
How to call a django rest api with authentication, from a djano view
I have a django rest API which gives list of students to certain authentic users. It needs to be called from a django view. Currently I am using requests library with token authentication inside get_context_data as shown below: import requests def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) token,created = Token.objects.get_or_create(user=self.request.user) reverse_url = 'http://127.0.0.1:8000/api/students/' response = requests.get( reverse_url, headers={'Authorization': 'Token {}'.format(token)} ) context['object'] = response.json() return context Is this the right way of doing it Thanks -
Filepond with Django returns empty filelist
I am trying to use file pond with my Django but after the images are preview and it displays them as green and I see the POST request, after clicking submit n my form when I print request.files it returns an empty list. This is my Django view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user post.save() if request.FILES is not None: images = request.FILES.getlist('filepond') print(images) for i in images: image_instance = Images.objects.create(image=i,post=post) image_instance.save() data['form_is_valid'] = True data['post'] = render_to_string('home/posts/new_post.html',{'post':post},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form, } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) Andd this is my html with script: <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header text-center"> <h5 class="modal-title col-12 text-center">Create a Post <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </h5> </div> <div class="modal-body" style="height:400px;overflow-y: auto; margin:0;"> {{ form|crispy }} <div class="pt-3" style="margin-bottom: -100px !important;"> <input type="file" class="filepond" accept="image/*"> </div> </div> <div class="modal-footer col-12" style="margin-top: -20px;"> <button type="submit" class="btn btn-primary" style="border-radius: 20px; width: 100%;">Post</button> </div> </form> <script> $.fn.filepond.registerPlugin( FilePondPluginImagePreview, FilePondPluginImageCrop, FilePondPluginImageEdit, FilePondPluginImageEdit, FilePondPluginFileValidateType, ); $(function () { var csrf_token="{{ csrf_token }}"; $('.filepond').filepond({ allowMultiple: true, … -
Data Dissapearing in Django on validation
I am trying to create nested objects (documentregulation) when I create a Document object. To achieve this, I have overwritten the create method on the DocumentSerializer, as per Django Docs. However, when I attempt validated_data.pop('documentregulation_set'), it is empty, even when it is populated in the incoming request.data of my view. Is there something causing my incoming data to not be validated? How would I go about debugging this if so? // serializers.py class DocumentRegulationSerializer(serializers.ModelSerializer): class Meta: model = DocumentRegulation fields = ('regulation',) class DocumentSerializer(serializers.ModelSerializer): documentregulation_set = DocumentRegulationSerializer(many=True, required=False) class Meta: model = Document fields = ('documentregulation_set', 'id', 'name', 'file', 'text', 'uploaded_at') extra_kwargs = { 'id': {'read_only': True}, 'uploaded_at': {'read_only': True}, } def create(self, validated_data): documentregulation_set = validated_data.pop('documentregulation_set') # create document first document = Document.objects.create(**validated_data) # serialize associated regulations for documentregulation in documentregulation_set: # get ID of newly-created document, use for relation #documentregulation['regulation'] = documentregulation['id'] DocumentRegulation.objects.create(document=document, **documentregulation) return document //views.py class DocumentView(generics.ListCreateAPIView): def create(self, request): #pprint(self.request.FILES['profile_pic']) request.data['documentregulation_set'] = json.loads(request.data['documentregulation_set']) request.data['documentdomain_set'] = json.loads(request.data['documentdomain_set']) pprint(request.data) document = DocumentSerializer(data=request.data) if document.is_valid(): document.save() return Response(document.data, status=status.HTTP_201_CREATED) else: return Response(document.errors, status=status.HTTP_400_BAD_REQUEST) my incoming data (printed in request.data) looks like: {'documentregulation_set': [{'label': 'Regulation 1', 'regulation': 2, 'value': 2}, {'label': 'Regulation 2', 'regulation': 4, 'value': 4}], 'file': <InMemoryUploadedFile: … -
Share class instance between two clients (python)
I'm building a very simple multiplayer web game. It's tron lightcycles, but to turn, the user must solve an arithmetic problem. I've been working on a particular problem for 2-3 days because I didn't fully understand what was going on. Every time a game started, I would create an instance of a class called Flux in which to store game data. The problem was, since there are two players, two instances of Flux are created. I need only one, and I need to be able to share this instance with the opposing player. How? I'm using django 1.11.17, django-channels 1.x, python 3.6 I looked at this answer: Issue with setting value for Python class inherited from multiprocessing.Process Is the multiprocessing module a good fit for my case? -
How to to create edit functionality by using django form
I have two models child and parent models by which a child model is a foreign key of a parent model,then i pass a child id on a template that will edit parent records of a specific child. Here is my child model class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname'] here is my views.py file for editing parent records,but when i render this template there is no fields value that will help me to edit the record,it display an empty field with no value on it def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) if request.method=="POST": form=ParentForm(request.POST,instance=child) if form.is_valid(): form.save() return redirect('more_details',pk=pk) else: form=ParentForm(instance=child) context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) and here is my template file <div class="card-body"> <form action="" method="post" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </div> -
How to filter ManyToMany same objects multiple times with count
Let's say that we have Django models defined as follows: class Tags(models.Model): name = models.CharField(max_length=100, verbose_name = 'Tag name') customers = models.ManyToManyField(Customers, related_name='tags', verbose_name = 'Refs to Customer') class Customers(models.Model): name = models.CharField(max_length=100, verbose_name='Display Name') I want to filter customer who include all tags, exclude all tags. include_all_tags = [1,2] exclude_all_tags = [3, 4, 5] but the query below doesn't work: query = Customers.objects.all() query = query.filter(tags__id__in=include_all_tags).annotate(c=Count('tags', distinct=True)).filter(c=len(include_all_tags)) query = query.exclude(tags__id__in=exclude_all_tags).annotate(c=Count('tags', distinct=True)).filter(c=len(exclude_all_tags)) SQL Output is here, but ( COUNT ( "core_customertag"."tag_id" ) = 2 AND COUNT ( "core_customertag"."tag_id" ) = 3 ) is count for the same alias table ! SELECT "core_customers"."id", "core_customers"."name", COUNT ( "core_customertag"."tag_id" ) AS "c" FROM "core_customers" INNER JOIN "core_customertag" ON ( "core_customers"."id" = "core_customertag"."customer_id" ) WHERE ( "core_customertag"."tag_id" IN ( 1, 2 ) AND NOT ( "core_customers"."id" IN ( SELECT U1."customer_id" FROM "core_customertag" U1 WHERE U1."tag_id" IN ( 3, 4, 5 ) ) ) ) GROUP BY "core_customers"."id" HAVING ( COUNT ( "core_customertag"."tag_id" ) = 2 AND COUNT ( "core_customertag"."tag_id" ) = 3 ) Expected: SELECT "core_customers"."id", "core_customers"."name", COUNT ( T1."tag_id" ) AS "c1" COUNT ( T2."tag_id" ) AS "c2" FROM "core_customers" INNER JOIN "core_customertag" T1 ON ( "core_customers"."id" = "core_customertag"."customer_id" ) INNER JOIN "core_customertag" … -
Assert image uploaded correctly - Selenium
I'm using Selenium to test my website. I am making a functional test where it logs a new user in, goes to their profile, then asserts that it can successfully update their profile info. This includes name, email address and profile picture. I can check that the name and email are successfully updated, but don't know how to check that the image uploads correctly. I am able to upload the image successfully (I used time.sleep(10) to check - I just need an assertion for it. This is how im uploading the new image self.browser.find_element_by_css_selector('.clearablefileinput.form-control-file').send_keys(settings.MEDIA_ROOT+'\profile_pics\\testImg.jpg') Thank you. -
Upload image in DRF
It seems I have tried a thousand combinations, but I continually get 415 media type unsupported errors, or 400 errors stating The submitted data was not a file. Check the encoding type on the form, or 500 errors stating, Invalid boundary in multipart: %s' % boundary.decode(), depending on which content-type I set. I don't particularly care how I upload the file, I just want it uploaded! Thank you for any guidance! //ReactFrontend.jsx function uploadPhoto(file) { const formData = new FormData() formData.append('logo', upImg) fetch(`${SERVER_URL}/api/v1/accounts/organization/logo`, { // content-type header should not be specified! method: 'POST', body: formData, headers: { Authorization: `Token ${token}`, 'Content-Type': 'multipart/form-data' }, }) .then(response => response.json()) .then(data => { console.log(data) alert('success') // Do something with the successful response }) .catch(error => { alert('error') console.log(error) }) } //views.py class OrganizationLogo(APIView): authentication_classes = (TokenAuthentication,) parser_classes = [MultiPartParser] def post(self, request, format=None): organization = Organization.objects.get(id=request.user.organization_id) serializer = OrganizationSerializer(organization, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) //serializers.py class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('name', 'logo') //models.py class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20, unique=True]) logo = models.FileField(upload_to='files/organization_logos/', null=True, blank=True) -
Django Like button directing to This page isn’t working
I have tried another method to create a like button for posts, I have reached to the phase where button directs me to an error of This page isn’t working Not sure where the problem relies on. I am following a tutorial but the only difference is that the tutorial created a function for the post with context in the views while I created a class for the post. I don't know if this is the reason for some deviations and the error appearing Here is the Model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) likes = models.ManyToManyField(User, blank=True, related_name='liked') def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={'pk': self.pk}) @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) def __str__(self): return str(self.post) here is the views class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 5 def like_post(request): user = request.user if request.method == 'Post': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post.obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value … -
What is the best data schema for “like, dislike, inappropriate-content-report” in Django
I have a project for a forum. The forum has limitless posts and comments. I want to make “like, dislike, report inappropriate content” model. I am a meticulous person and I have 3 options. These 3 options are: 1- create three different models as follow: class Like(models.Model): ''' like comment ''' comment = models.OneToOneField(Comment, related_name="likes", on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='requirement_comment_likes') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.comment.comment)[:30] class DisLike(models.Model): ''' Dislike comment ''' comment = models.OneToOneField(Comment, related_name="dis_likes", on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='requirement_comment_dis_likes') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.comment.comment)[:30] Please look at this thread This is easy to implement. Thus, there will be 3 different tables to luck up in for posts “like, dislike, and inappropriate-content-report 2- create one model “table”. Doing so, There will be 3 columns inside that table. This will result in bigger table. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name='author') title = models.CharField(max_length=80, verbose_name="Название") body = models.TextField(verbose_name="Текст публикации") created = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания") modified = models.DateTimeField(auto_now=True, verbose_name="Дата обновления") description = models.CharField(max_length=400,verbose_name = "Описание") reading_time = models.PositiveSmallIntegerField(verbose_name="Время для чтения в минутах") likes = models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) users_reaction = models.ManyToManyField(User, blank=True, verbose_name='Реакция юзеров', related_name='react') Please note that in here they …