Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Django settings references for cron.d on AWS EB Amazon Linux 2 platform
I updated AWS platform from "Python 3.6 running on 64bit Amazon Linux" to "Python 3.7 running on 64bit Amazon Linux 2" and I'm not able to execute crons because I don't know how to add reference for Django settings file there. Could you help me? On the old platform everything works fine with this ".ebextensions/cron.config" setup: files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | 3 * * * * root /usr/local/bin/script.sh > /home/ec2-user/script.log 2>&1 "/usr/local/bin/script.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date # actual script content source /opt/python/run/venv/bin/activate source /opt/python/current/env cd /opt/python/current/app/ python manage.py send_notification exit 0 I know that I have to make changes on Linux 2 platform and I have to run activate -script from different location and this is what I have now: files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | 3 * * * * root /usr/local/bin/script.sh > /home/ec2-user/script.log 2>&1 "/usr/local/bin/script.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date # actual script content source /var/app/venv/*/bin/activate cd /var/app/current/ python manage.py send_notification exit 0 I have also noticed that everything works fine when I try to do the same from .platform/hooks/predeploy and executing python from … -
MultiValueDictKeyError at /api/booking 'user' in django rest framework
I am trying to create a booking api using drf. But I am getting this error. To book any package, user has to login and select a specific package. Here is my Booking model: class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package') name = models.CharField(max_length=255) email = models.EmailField() phone = models.CharField(max_length=255) bookedfor = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) class BookingCreateAPIView(CreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def create(self, request, *args, **kwargs): booking_data = request.data new_booking = Booking.objects.create(user=booking_data["user"], package=booking_data["package"], name=booking_data["name"], email=booking_data["email"], phone=booking_data["phone"], bookedfor=booking_data["bookedfor"], created_at = booking_data["created_at"] ) new_booking.save() serializer = BookingSerializer(new_booking) return Response(serializer.data, status=status.HTTP_200_OK) class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] -
Creating Duplicate Orders when checking out product on my e-commerce site Python Django
I am working on an e-commerce website. I am checking out 1 of my products with a paypal code sandbox account. But, when I log into my admin site after processing the order I see it creates 2 orders to the same logged in user. 1 order has a transaction ID and the second transaction does not have an ID. I'm not sure why, I appreciate any help! thanks transaction with no ID // transaction WITH ID -
get field value into the Serializer
My English is little bad, am a beginner for django please help me to solve this issues Model code is...... class Plan(models.Model): floor_select = (('single', 'Single'), ('double', 'Double'), ('above', 'Above')) title = models.CharField(max_length=50, blank=False) code = models.CharField(max_length=30, blank=False) floor = models.CharField(choices=floor_select, max_length=10) room = models.IntegerField() plan_size = models.IntegerField() ground_size = models.IntegerField() first_size = models.IntegerField() image = models.FileField(blank=True, upload_to=os.path.join('plan_images')) details = models.CharField(max_length=500, blank=False) def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Plan, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to=os.path.join('plan_images')) def __str__(self): return self.post.title serializer is like .. class PlanDetailSerializers(serializers.ModelSerializer): floor = serializers.SerializerMethodField() images = serializers.SerializerMethodField() class Meta: model = Plan fields = ('__all__', 'images') def get_floor(self, obj): return obj.get_floor_display() def get_images(self, obj): return PlanImageSerializer.objects.get(id=Plan.objects.get(pk=obj.id)) class PlanImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = '__all__' i tried more but i got the same result i want the postimage field inside the plan field by the validation of id(post_id) is same as the Plan id.. -
Is there a way you can help me out here?
I'm new to coding and Django. I have no clue on how to solve this problem. plz help Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Raised by: django.views.static.serve -
Django Error : 'method' object is not subscriptable
I'm trying to create a simple form, but somehow everytime I push the enter button, this error shows up? so what did I do wrong? This is my views : @login_required def voted(response): user = Userdata.objects.get(id=response.user.id) # get the username if user.is_voted == True: return render(response, 'Main/voting.html', {'calon' : Voting.objects.order_by('id'), 'hasil' : 'You Have Voted'}) if response.method == 'POST': id = int(response.POST.get['idcalon']) calon2 = Voting.objects.get(id = id) # get user selection in html user.is_voted = True calon2.voters += 1 user.save() calon2.save() return render(response, 'Main/voting.html', {'calon' : Voting.objects.order_by('id')}) # balik ke sendiri This is the Html : <form method="POST"> {% if calon %} {% for para in calon %} <div class="custom-control custom-checkbox small" style="line-height: 1.5rem;"> <input type="radio" id="huey" name="idcalon" value="{{ forloop.counter }}" checked> <label for="huey">{{ para.name }}</label> </div> {% endfor %} {% else %} {% endif %} <div class="form-group"> <div class="col-sm-10">{% csrf_token %} <button type="submit" class="btn btn-primary">Vote Now</button></div> </div> </form> My guest is at the value in the HTML, but I personally don't know how to fix it. Thank you -
is there a way to put delete button on the left side
Is there a way to put the delete button on the left side? i try to use ordering but it doesnt work because delete is not part of the model -
Get developer belonging to a model
I am doing a query where I filter the developers that belong to the Project model, because I am going to make the activity model generate a list of only the developers that belong to the Project model This is project model: class Project(models.Model): name = models.CharField(max_length=50, unique=True) developer = models.ManyToManyField(Developer) state = models.BooleanField(default=False) task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) This is task model: class Task(models.Model): developer = models.ManyToManyField(Developer) type_task = models.ForeignKey(TypeTask, on_delete=models.CASCADE) task = models.CharField(max_length=50) activities = models.ManyToManyField(Activities, through='ActivitiesTasks') description = models.TextField() state = models.BooleanField(default=True) slug = models.SlugField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Example Task.objects.filter(developer=?).exists() -
Forbidden (CSRF token missing or incorrect.): /updatecart_index/
in my html i have this code where the user updating the quantity from the database,why i am encounter this kind of error Forbidden (CSRF token missing or incorrect.): /updatecart_index/ ? eventhought i have this in my form {% csrf_token %} <form method="POST" id="form" >{% csrf_token %} <input type="hidden" value="{{bought.id}}" name="itemID"> <input type="submit" value="-" id="down" formaction="/updatecart_index/" onclick="setQuantity('down');" > <input type="text" name="quantity" id="quantity" value="{{bought.quantity}}" onkeyup="multiplyBy()" style="width: 13%; text-align:left;" readonly> <input type="submit" value="+" id="up" formaction="/updatecart_index/" onclick="setQuantity('up');" > </form> <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ event.preventDefault(); var form_id = $('#form') $.ajax({ url: "{% url 'updatecart_index' %}", type: 'POST', data: form_id.serialize(), header: {'X-CSRFToken': '{% csrf_token %}'}, dataType: "json", success: function (response){ var success = response['success'] if(success){ alert("form submittend"); }else{ alert("got error"); } }, failure: function (error){ alert("Error occured while calling Django view") } }) }); }); </script> in views.py def updatecart_index(request): item = request.POST.get("itemID") print("dasdasd") quantity = request.POST.get("quantity") product = CustomerPurchaseOrderDetail.objects.get(id=item) print("aa", CustomerPurchaseOrderDetail.objects.get(id=item)) product.quantity = quantity product.save() data = {} data['success'] = True return HttpResponse(json.dumps(data), content_type="application/json") -
Django REST returning foreign key elements in nested form
I am new to Django. I've read a lot of documents here, but so far I've not found one that matches my code. When I request get object, [{"author": "Users object (2)", "place": "Places object (1)", "comment": "Hello World!", "created_date": "2020-11-11T02:15:34.729523Z", "rating": "0.00"}, {"author": "Users object (2)", "place": "Places object (1)", "comment": "Hello World!", "created_date": "2020-11-11T02:20:58.307842Z", "rating": "0.00"}] But I want it in nested form, such that instead of "Users object (2)", I could get the json of Users object with id=2, and instead of "Places object (1)", I could get the json of the place with id 1. How could I achieve this? Thank you! views.py import json from rest_framework.parsers import JSONParser from django.core import serializers from django.views import View from django.http import JsonResponse from .models import Places, Reviews from .serializers import PlaceSerializer, ReviewSerializer def process_reviews(request, x=0, y=0): if request.method == 'GET': place_id = list(Places.objects.filter(longtitude=x).filter(latitude=y).values("id"))[0]['id'] reviewset = Reviews.objects.filter(place_id=place_id) serializer = ReviewSerializer(reviewset, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': # NEED TO POST: # username, name, latitude. longtitude, comment, rating data = JSONParser().parse(request) target = Places.objects.filter(latitude = data['latitude']).filter(longtitude = data['longtitude']) if target.exists(): serializer = ReviewSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) else: # Place doesn't exist. … -
How to Integrate the https://jsonplaceholder.typicode.com/ into the django application?
Get posts from JSON placeholder. https://jsonplaceholder.typicode.com/posts Get posts details from JSON Placeholder. https://jsonplaceholder.typicode.com/posts/1 Get Comments from JSON Placeholder. https://jsonplaceholder.typicode.com/posts/1/comments -
Access image from cloud storage given the name inside of a model in Django-Python
I am in need of ideas/help. I am saving the image from my angular client into a cloud storage bucket and saving the name of the file in a django model in mysql. I am able to access the file if I create an url like the one below on a django template: {% for visitor in visitors%} <img src="https://storage.cloud.google.com/BUCKET_NAME/{{visitor.image_name}}"> {% endfor %} This works because I have added my organization to have permissions in the cloud bucket, so when I am signed in onto Gmail, it will let me output the picture. But once I am signed out, it will not output the picture. And since; this works on a Desktop computer for me, but not on a mobile device. What is another way I can access this picture from my cloud bucket? given my current model. Any help will be much appreciated. -
Reverse for 'post-detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$']
I am trying to create a Like button for my Django Blog Project, but currently facing an error due to using the slug in the URL. The error is: Reverse for 'post-detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$'] Here is the urls.py path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), My Question is how to fix this error and add Slug to the redirect template? Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @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) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res 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=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" … -
How can i use same logger in different python file/modules
I have a django project and struct like this: apps ---- app1 -------- app1_view.py ---- app2 -------- app2_view.py libs ---- public_lib.py app1_view.py LOGGER = logging.getLogger("app1") # Formater is '%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s'. # It will output on file ./logs/app1.log from libs.public_lib import * def main(): # Do somethings. LOGGER.info("This test log from app1.") pub_func() app2_view.py LOGGER = logging.getLogger("app2") # Formater is '%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s' too. # It will output on file ./logs/app2.log from libs.public_lib import * def main(): # Do somethings. LOGGER.info("This test log from app2.") pub_func() public_lib.py def pub_func(): # Do pub_func. PUBS_LOGGER.info("pub_func done.") I hope the logger output like this in ./logs/app1.log 2020-11-10 17:12:37,388 [app1.py:9] [INFO] This test log from app1. 2020-11-10 17:12:53,866 [public_lib.py:3] [INFO] pub_func done. And ./logs/app2.log 2020-11-10 17:13:37,388 [app2.py:9] [INFO] This test log from app1. 2020-11-10 17:13:53,866 [public_lib.py:3] [INFO] pub_func done. I'm used to calling it "The Vertical log". So that, How should i define the logger in public_lib.py -
SKLearn Feature Selection: AttributeError: 'numpy.float64' object has no attribute '_get_tags'
An error is raised when the .fit() method is called after the RFE execution. What might caused the error? df = pd.read_csv(project.base_file, encoding='ISO-8859-1') X = df.drop(['colun1', 'column2'] , axis=1) y = df[target_column] X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state = 0) sel = RFE(run_randomForest_classifier(X_train, X_test, y_train, y_test), n_features_to_select=15) ### THE NEXT LINE THROWS THE ERROR ### AttributeError: 'numpy.float64' object has no attribute '_get_tags' sel.fit(X_train, y_train) -
How to fix 'Manager' object has no attribute 'get_or_created'
I am trying to create a Like button for my Django Blog Project, I have followed a Tutorial step by step but currently facing an new error I haven't faced before: 'Manager' object has no attribute 'get_or_created' My Question is how to fix this error as it appears when I click on the Like button in the template? Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @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) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res 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_created(user=user,post_id=post_id)<------------- Error from here if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% … -
Django additional data not saving
I'm having an issue with my Django web app where I ask for data in a form which is saving correctly but it isn't saving the additional data from views. I am trying to save the user data of the person who posted this and the event id but it's not saving that info for some reason. @login_required def newrider(request, Event_id): events = get_object_or_404(Event, pk=Event_id) riders = rider.objects.filter(event=Event_id) if request.method == 'GET': return render(request, 'web/newrider.html', {'form': AddRiderForm()}) else: if request.user.is_authenticated: item = rider.objects.filter(number=request.POST['number'], event=Event_id).count() num = request.POST['number'] if item == 0: form = AddRiderForm(request.POST) form.user = request.user form.event = Event_id if form.is_valid(): form.save() return render(request, 'web/newrider.html', {'form': AddRiderForm()}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm(), 'error': 'That number is taken, try again with another number', 'item':item}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm(), 'error': 'That number is taken, try again with another number', 'item':Event_id}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm()}) -
Was I supposed to be able to create a question on the website using 'runserver'?
I'm following this Django tutorial. So far I haven't had an issue so far, but now I'm not really sure if I understood it correctly. We created a shortcut function to create questions, but I thought that it was meant to be user-side and when I use 'runserver', on the website there's no such option, only the previously created question. This is the code for the function: def create_question(question_text, days): """ Create a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) Did I get it wrong? This function is only admin-sided? It's on 'polls/test.py' and it's outside every class. -
My static files in aws s3 is not loaded in my Django blog
I am working on a small blog with Django. I've deployed it to pythonanywhere but the problem is that all my static files are not loading. When I tried inspecting the the page chrome, it shows that the links are from amazon. Even when I run the collectstatic command, the necessary folders are created in my s3 bucket and the files are copied to the folders. This is the config in my settings.py AWS_ACCESS_KEY_ID = "XXXXXXXXXXXXXXXXXXXXXX" AWS_SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" AWS_STORAGE_BUCKET_NAME = "XXXXXXXXXXXX" AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazon.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} STATICFILES_DIRS= [os.path.join(BASE_DIR, 'static'),] AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'myblog.storage_backends.MediaStorage' In the console tab of inspection page, I see www.majestylink.com/:9 GET https://majestylinkbucket.s3.amazon.com/static/css/bootstrap.min.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:11 GET https://majestylinkbucket.s3.amazon.com/static/css/music.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:13 GET https://majestylinkbucket.s3.amazon.com/static/css/poem.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:15 GET https://majestylinkbucket.s3.amazon.com/static/css/home.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:17 GET https://majestylinkbucket.s3.amazon.com/static/css/video.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:196 GET https://majestylinkbucket.s3.amazon.com/static/js/jquery-3.4.1.min.js net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:197 GET https://majestylinkbucket.s3.amazon.com/static/js/bootstrap.min.js net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:155 GET https://majestylinkbucket.s3.amazon.com/static/img/fb.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:159 GET https://majestylinkbucket.s3.amazon.com/static/img/wp.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:163 GET https://majestylinkbucket.s3.amazon.com/static/img/ig.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:167 GET https://majestylinkbucket.s3.amazon.com/static/img/yb.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:171 GET https://majestylinkbucket.s3.amazon.com/static/img/tt.png net::ERR_NAME_NOT_RESOLVED Please what am I not doing right? -
error en heroku at=error code=H10 desc="App crashed" method=GET path="/" host=djangoblog33.herokuapp.com
el error completo es: 2020-11-11T01:39:03.861407+00:00 app[api]: Initial release by user bastanterojo11@gmail.com 2020-11-11T01:39:03.861407+00:00 app[api]: Release v1 created by user bastanterojo11@gmail.com 2020-11-11T01:39:03.982182+00:00 app[api]: Release v2 created by user bastanterojo11@gmail.com 2020-11-11T01:39:03.982182+00:00 app[api]: Enable Logplex by user bastanterojo11@gmail.com 2020-11-11T01:45:17.000000+00:00 app[api]: Build started by user bastanterojo11@gmail.com 2020-11-11T01:45:54.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/2124a9f1-ff92-4431-8a1e-a2c39d0583e5/activity/builds/57d3eecd-80c1-49e6-bd0b-37268a6ae3df 2020-11-11T01:46:05.941459+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user bastanterojo11@gmail.com 2020-11-11T01:46:05.941459+00:00 app[api]: Release v3 created by user bastanterojo11@gmail.com 2020-11-11T01:48:10.000000+00:00 app[api]: Build started by user bastanterojo11@gmail.com 2020-11-11T01:49:02.116687+00:00 app[api]: Running release v4 commands by user bastanterojo11@gmail.com 2020-11-11T01:49:02.116687+00:00 app[api]: Attach DATABASE (@ref:postgresql-concave-13076) by user bastanterojo11@gmail.com 2020-11-11T01:49:02.130526+00:00 app[api]: Release v5 created by user bastanterojo11@gmail.com 2020-11-11T01:49:02.130526+00:00 app[api]: @ref:postgresql-concave-13076 completed provisioning, setting DATABASE_URL. by user bastanterojo11@gmail.com 2020-11-11T01:49:02.472811+00:00 app[api]: Deploy 54db32d8 by user bastanterojo11@gmail.com 2020-11-11T01:49:02.472811+00:00 app[api]: Release v6 created by user bastanterojo11@gmail.com 2020-11-11T01:49:02.485754+00:00 app[api]: Scaled to web@1:Free by user bastanterojo11@gmail.com 2020-11-11T01:49:07.944708+00:00 heroku[web.1]: Starting process with command `gunircorn django_blog.wsi` 2020-11-11T01:49:09.754226+00:00 app[web.1]: bash: gunircorn: command not found 2020-11-11T01:49:09.805462+00:00 heroku[web.1]: Process exited with status 127 2020-11-11T01:49:09.847279+00:00 heroku[web.1]: State changed from starting to crashed 2020-11-11T01:49:09.851178+00:00 heroku[web.1]: State changed from crashed to starting 2020-11-11T01:49:12.000000+00:00 app[api]: Build succeeded 2020-11-11T01:49:14.978188+00:00 heroku[web.1]: Starting process with command `gunircorn django_blog.wsi` 2020-11-11T01:49:18.067114+00:00 app[web.1]: bash: gunircorn: command not found 2020-11-11T01:49:18.116336+00:00 heroku[web.1]: Process exited with status 127 2020-11-11T01:49:18.157787+00:00 heroku[web.1]: State … -
Converting a Function to CBV for Django Project
I have created a blog project using a Class Based Viewand now I was trying to add the like button to the posts. So, I want to know how to convert the function used in the project to be included in the Class Based View. My question is how to convert the function used in the tutorial to fit in my project to be included in the Class Based View. (It is a learning process for me to also include Comments.) Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @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) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def … -
Django dynamic queryset
I have a view which can receive from none to four different filter lookups. Let's say it starts with Model.objects.all() and then if filter_option is not None and filter_option != '' the idea is to add that filter to the queryset. Making a lot of ifs is a solution but it's really ugly. This is what I'm trying but I'm not getting the expected behavior: class CourseList(ListView): model = Course paginate_by = 10 def get_queryset(self, queryset=None): q = self.request.GET.get('q') sort = self.request.GET.get('sort') level = self.request.GET.get('level') qs = Course.objects.all() if q is not None and q != '': qs.filter(Q(title__icontains=q) | Q(description__icontains=q)) if sort is not None and sort != '': qs.order_by(sort) if level is not None and level != '': sq.filter(level=level) return qs For each "if true" condition I want those options added to the queryset. But instead I'm just getting Course.objects.all() as result all the time. -
Download zip file from http api in react, Receiving error: "Unable to expand file.zip. It is an unsupported format"
Thanks in advance for taking a look. I am working on being able to download a zip file from react through a django api request. I am able to click on my pop up that downloads the zip file, but when I double click on the zip file to open, I get this error: "Unable to expand file_name.zip. It is an unsupported format" My response with the zip file seems to be passing correctly to the front end, so I am thinking it may be something wrong with the react code when making the "blob"? Thanks again. Django code: class DownloadZip(APIView): def post(self, request, format=None): # information to find file to create zip profile_name = request.data["profile"] profile_year = request.data["year"] # file path to create zips from path = str(Path(__file__).parent.resolve()) zip_dir = shutil.make_archive(profile_name + profile_year, "zip", path + "profile_name") s = io.StringIO(zip_dir) response = HttpResponse(s, content_type = "application/zip") zip_name = profile_name + profile_year + ".zip" response["Content-Disposition"] = f"attachment; filename={zip_name}" return response React code: downloadZip = async () => { const params = { profile: this.state.profileName, year: this.state.year, }; axios({ url: `${serverUrl}/download_zip`, method: "post", data: params }).then( (res) => { const url = window.URL.createObjectURL(new Blob([res.data],{type:'application/zip'})); const link = document.createElement('a'); link.href = url; … -
saving images on a local files with heroku
Hello i am new to django and I am almost done with my first web development but I have this Problem that I noticed. images are not getting saved on the File that is set for saving images on my local PC and therefor I was wondering if its a problem on my part or heroku dose not work like the localhost. I would be thankful for some explaining and thanks Here is some codes of my project: Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], ..... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' displaying the image on an html {% for topic in result %} <div class="card-mb3"> <div class="card-header" style="background-color:lightgrey"> <table class="table"> <tr> <th>Image</th> <th>Title of the topic</th> <th>Edit</th> <th>Delete</th> </tr> <div class="card-body" style="background-color:white"> <tr> <td> {% if topic.image %} <image src="{{topic.image.url}}" style="width:200px"> upload.html {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="file" name="document"> <button type="submit"> Upload image <i class="fas fa-upload"></i> </button> </form> {% endblock content %} views.py def upload(request): context = {} if request == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'learning_logs/upload.html', context) -
How do I update an object that was made with POST in a React front-end... in a Django backend?
I'm trying to follow a tutorial, these are the videos in the series I watched so far: Part 1 Part 2 (Handling Post Requests) Of course you don't want to watch the videos, so here's the project on GitHub: here My method for handling post requests is pretty much the same as his. It looks like this: class CustomForm extends React.Component { handleFormSubmit = async (event, requestType, profileID) => { const postObj = { user_name: event.target.elements.user_name.value, } if (requestType === "post") { await axios.post("http://127.0.0.1:8000/api/create/", postObj) .then(res => { if (res.status === 201) { this.props.history.push(`/`); } }) } else if (requestType === "put") { await axios.put(`http://127.0.0.1:8000/api/${profileID}/update/`, postObj) .then(res => { if (res.status === 200) { this.props.history.push(`/`); } }) } } So I have a question. What if I did it they way he did it, but instead of just posting to the server (posts happen on form submission)... I want to post to the server AND have my backend start asynchronously updating that posted object as soon as it's posted? How would I go about doing that (based off his / my code [kinda identical] ? The closest thing I can think of is using the views.py file to take in …