Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Below code give me error like "The view home.views.edit didn't return an HttpResponse object. It returned None instead."
I'm trying to add an edit button to my project and gives me an error. This is my views.py file, i made display and delete function but both are working perfect. from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages def edit(request, list_id): if request.method == 'POST': item = List.objects.get(pk=list_id) form = ListForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Task Has Been Edited...!!!') return redirect('home') else: item = List.objects.get(pk=list_id) return render(request, 'home/edit.html', {'item': item}) This is my urls.py file from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), #home page path('delete/<list_id>', views.delete, name="delete"), #delete the task path('edit/<list_id>', views.edit, name="edit"), #edit page ] This is my edit.html in which i extend base.html file {% extends 'base.html' %} #extending base template {% block content %} {% if item %} <form class="form-inline" method="POST"> {% csrf_token %} <div class="form-group mx-sm-3 mb-2 mt-2"> <input type="search" name="item" class="form-control" placeholder="{{ item.task }}" size="130" value="{{ item.task }}"> </div> <button type="submit" class="btn btn-primary mb-1">Edit</button> </form> {% endif %} {% endblock %} when i hit edit button, which gives me the following error: ValueError at /edit/3 The view home.views.edit didn't return an HttpResponse object. It … -
Using template folder from one app to another in Django
I am trying to use the template from my app to my server page. I created a page which have a button to change that page into pdf format. This is an image to find where my template page is in. And in the coding I tried to add html file in the line 28 This is the error which is showing when i select the "view pdf" url/button class ViewPDF(View): def get(self,request, *args, **kwargs): pdf = render_to_pdf('templates/pdft.html') return HttpResponse(pdf, content_type='application/pdf') In this coding how do i need to add the pdft.html template in the 3rd line? -
how to override 'get_queryset()' in Django
I'm going to use the generic view in django. I defined the serializer_class and override the get_queryset() method, but there is an error telling me to override the get_queryset() method. I wonder how my override method is wrong, and what I have to do to solve the error. Here is my codes. views.py from .models import arduino from .serializers import arduinoToAndroidSerializers, arduinoToDatabaseSerializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.generics import ListCreateAPIView class arduinoToAndroidViewSet (ViewSet) : def dataSend (self, request) : user = self.request.user queryset = arduino.objects.filter(name=user) serializer = arduinoToAndroidSerializers(queryset, many=True) return Response(serializer.data) class arduinoToDatabaseViewSet (ListCreateAPIView) : serializer_class = arduinoToDatabaseSerializers def dataReceive (self, request) : user = self.request.user queryset = arduino.objects.filter(queryset, name=user) serializer = arduinoToDatabaseSerializers(queryset, many=True) return Response(serializer.data) serializers.py class arduinoToAndroidSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username') class Meta : model = arduino fields = ('name', 'temp', 'humi') class arduinoToDatabaseSerializers (serializers.ModelSerializer) : class Meta : model = arduino fields = ('temp', 'humi') Besides this, if you see improvement point in my code, please give me tips -
JSON Response "This field may not be null." Django Rest Framework
I am trying to add data from a JSON response to my database. Here is what my models.py looks like class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False) question = models.CharField(max_length=100000, unique=False) options = models.ManyToManyField("Options") user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) answer = models.ForeignKey(Options, related_name="correct", on_delete=models.CASCADE, null = False) difficulty = models.CharField(max_length=5000) type = models.CharField(max_length=2000) Here is what my views.py looks like. @api_view(['POST']) def opendb(request): data = requests.get(url = request.data['url']).json() print(data) QuestionData = { "category": data.get('category'), "type": data.get('type'), "difficulty": data.get('difficulty'), "question": data.get('question'), "answer": data.get('correct_answer'), "options": data.get('incorrect_answers'), } serializer = QuestionSerializer(data=QuestionData) if serializer.is_valid(): serializer.save() return JsonResponse({ "data": serializer.data }, status=status.HTTP_200_OK) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is what happens when i send a url to this view { "question": [ "This field may not be null." ], "difficulty": [ "This field may not be null." ], "type": [ "This field may not be null." ], "category": [ "This field may not be null." ], "answer": [ "This field may not be null." ], "options": [ "This field may not be null." ] here is how the API i need to fill data from returns JSON { "response_code": 0, "results": [ { "category": "General Knowledge", "type": "multiple", "difficulty": "easy", "question": "What … -
Django models: Why do I get "IntegrityError UNIQUE constraint failed" when I save the model twice?
I have the following model class Bill(models.Model): value_to_pay = MoneyField(decimal_places=2, max_digits=14, null=False, blank=False, default=Money(0, DEFAULT_CURRENCY)) status = models.CharField(_('bill status'), max_length=100, blank=True, null=True, default=UNPAID) def set_status_to_paid(self): self.status = PAID return self.save() def save(self, *args, **kwargs): if not self.status == PAID and self.value_to_pay <= 0: self.set_status_to_paid() super().save(*args, **kwargs) It's seeing on save if the value to be paid is 0 in which case it sets the bill to "Paid". However if I create a bill with value_to_pay=0 I get django.db.utils.IntegrityError: UNIQUE constraint failed: bill.id. I found out that I don't get this error if I remove the save from the set_status function def set_status_to_paid(self): self.status = PAID # return self.save() Why does saving twice cause this error? -
How to execute some python statements after executing external shell commands
I'm developing a Django application and it uses FFMPEG. Basically it receives a video uploaded by the user and it uses FFMPEG to transcode it to 240p, 360p and 480p. Since this is server-side code, many users might upload at the same time. Also after transcoding, records are added into a database table. out="media/uploads/"+folder #This is the upload path where folder is the name of the video BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) command = "ffmpeg -i '"+os.path.join(BASE_DIR,out)+"/"+fname+"' -s 426x240 '"+os.path.join(BASE_DIR,out)+"/240p.mp4'" subprocess.call(command,shell=True) convert = Convert.objects.get_or_create(vid=rec,name="240p.mp4",video=str(out+'/240p.mp4')) command = "ffmpeg -i '"+os.path.join(BASE_DIR,out)+"/"+fname+"' -s 640x360 '"+os.path.join(BASE_DIR,out)+"/360p.mp4'" subprocess.call(command,shell=True) convert = Convert.objects.get_or_create(vid=rec,name="360p.mp4",video=str(out+'/360p.mp4')) command = "ffmpeg -i '"+os.path.join(BASE_DIR,out)+"/"+fname+"' -s 854x480 '"+os.path.join(BASE_DIR,out)+"/480p.mp4'" subprocess.call(command,shell=True) convert = Convert.objects.get_or_create(vid=rec,name="480p.mp4",video=str(out+'/480p.mp4')) As this code will be run on a server, multiple users might upload videos at the same time. I want this code to run without any problems in that scenario. Also the database operations must be executed only after the FFMPEG commands have been executed. What are the changes that must be done to this code? -
what is wrong in my code in nginx? and django?
i'm building my own server with django, uwsgi, nginx i got ssl at nginx. ex) https://example.com:9002 work. result is welcome to nginx! page. but can't django page. what is wrong with my code? i've been struggle this challenge 2 days. nginx.conf server { listen 443 ssl; listen [::]:443 ssl; ssl_certificate /etc/letsencrypt/live/www.fidochallenge486.tk/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.fidochallenge486.tk/privkey.pem; server_name fidochallenge486.tk; ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } location /.well-known { root /var/www/certbot/; } #error_page 404 /404.html; ... and this is site-available/fido_nginx.conf upstream django { server 127.0.0.1:8000; #server unix:///Users/junbeomkwak/Desktop/fido_virtual/fido_project/fido.sock; #server unix:///tmp/fido.sock; } server { listen 9002; server_name fidochallenge486.tk; charset utf-8; client_max_body_size 75M; location /media { alias /Users/junbeomkwak/Desktop/fido_virtual/fido_project/media/; } location /static { alias /Users/junbeomkwak/Desktop/fido_virtual/fido_project/staticfile; } location / { uwsgi_pass django; include /Users/junbeomkwak/Desktop/fido_virtual/fido_project/uwsgi_params; } } -
Modified objects.all() method in Django model manager is not working in Search view but working fine elsewhere
I have overridden model manager all() method to only return active items from the database. And I can see only active items coming through in normal list view. But when I use the same in Search view if I search something relevant it returns all the items irrespective of the active status. My ProductManager to override the custom manager methods look like - class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using = self._db) def all(self): print('all method') return self.get_queryset().active() def active(self): return self.get_queryset().filter(active = True) def featured(self): return self.get_queryset().filter(featured = True) def search(self, query): lookups = ( Q(title__icontains = query) | Q(description__icontains = query) | Q(tag__title__icontains = query) ) return self.filter(lookups).distinct() My custom queryset method: class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active = True) def featured(self): return self.filter(featured = True) Class based view for search class SearchListView(ListView): template_name = 'search/view.html' def get_queryset(self,*args,**kwargs): request = self.request qs = Product.objects.all() print('QUERY SET==========================') print(qs) ******************************************* Until this point it is working fine only the active items coming <ProductQuerySet [<Product: shirt>, <Product: A hat>, <Product: test product>, <Product: One more item>]> ******************************************* print('QUERY SET==========================') query = request.GET.get('q') #search query can be saved href #SearchQuery.objects.create(query=query) if query is not None: qs = Product.objects.search(query) return qs def get_context_data(self, … -
How can you query for a subclass's set in Django?
I defined Django models using multi-table inheritance to ensure that parent models could also be instantiated. For instance: from django.db import models class Location(models.Model): name = models.TextField() street = models.TextField() city = models.CharField(max_length=60) province = models.CharField(max_length=100) class Event(models.Model): title = models.CharField(max_length=100) description = models.TextField() start = models.DateTimeField() duration = models.DurationField() location = models.ForeignKey(Location, on_delete=models.CASCADE) class SignUpEvent(Event): attendees = models.ManyToManyField(User, related_name='user_signups') Not all events will need sign ups attached to them, so I decided to make SignUpEvent a child of the more general Event class. I want to be able to define a function in Location that returns a specific set of Users related to that location (get_related_users) by identifying each SignUpEvent linked to that location and cycling through the attendees, but because the ForeignKey is defined in Event, not SignUpEvent, there is no signupevent_set I can use in Location to access all related SignUpEvents. How would I go about doing this? -
display number of views for each post for a specific author
i want to print number of views for a specific post for e.g barack obama = 3 albert einstein = 1 elon musk = 0 but it print multiple values for each entries as you can see in the image. so how to achieve this. should i have to use dictionary or what ? [enter image description here][1] models.py class ObjectViewed(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) ip_address = models.CharField(max_length=220, blank=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Blog, or any other models object_id = models.PositiveIntegerField() # User id, Blog id, or any other models id content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) views.py class PostListView(ListView): model = Post template_name = 'edmin/post/postList.html' context_object_name = 'posts' ordering_by = ['-created'] def get_queryset(self): post=Post.objects.filter(author=self.request.user) return post def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) post=Post.objects.filter(author=self.request.user) c_type = ContentType.objects.get_for_model(Post) context['count_view'] = [ObjectViewed.objects.filter(content_type=c_type, object_id=p.id) for p in post ] print(context['count_view']) return context postList.html <table id="table_id" class="table display" border='2' align="center"> <thead> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Banner Title</th> <th scope="col">Created</th> <th scope="col">Number of Views</th> <th scope="col">Status</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody style="color:#000"> {% for post in posts %} {% if post.status == 'Draft' %} {% else %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a … -
Post method is not working in updateview django
I have a update view in django project. I need to override the post method because I am using multiple modelform. I have already override createview. And it is working fine. views.py: class EmployeeUpdateView(LoginRequiredMixin, UpdateView): """ Update a created a employee """ login_url = '/authentication/login/' template_name = 'employee/employee_update_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm education_form_class = EducationForm queryset = Employee.objects.all() #success_url = reverse_lazy('employee:employee-list') def get(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee_id = Employee.objects.get(id=id_) work_info = WorkExperience.objects.get(employee=employee_id) education_info = Education.objects.get(employee=employee_id) return render(request, self.template_name, { 'form': self.form_class(instance=employee_id), 'work_form': self.work_form_class(instance=work_info), 'education_form': self.education_form_class(instance=education_info) } ) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) work_form = self.work_form_class(request.POST, prefix='work_form') education_form = self.education_form_class(request.POST, prefix='education_form') # Check form validation if form.is_valid() and work_form.is_valid() and education_form.is_valid(): instance = form.save() work = work_form.save(commit=False) education = education_form.save(commit=False) work.employee = instance education.employee = instance work.update() education.update() return redirect('employee:employee-list') return render(request, self.template_name, { 'form': form, 'work_form': work_form, 'education_form': education_form } ) When I press update button of my form, error is giving showwing "This field already exist". It means when i update the form, it is posting data as a new form not as a update form. I think my post method is not working. Where is the error in my post … -
Carrousel only show the images for the first post and not on the others
I'm developing a app in django in which I need to show multiple post and each post has multiple images that I want to put in a carrousel, my problem is that only the first post show its images, the next ones can't show them inside the carrousel, but can be shown in other parts of the template. Here's the model.py class Product(models.Model): """Model definition for Rifa.""" user = models.ForeignKey('User', on_delete=models.CASCADE) nombre = models.CharField('nombre', max_length=50) fecha_inicio = models.DateTimeField('fecha inicio', auto_now=False, auto_now_add=False) fecha_termino = models.DateTimeField('fecha termino', auto_now=False, auto_now_add=False) descripcion = models.TextField() precio = models.IntegerField() class Meta: verbose_name = 'product' verbose_name_plural = 'products' def get_absolute_url(self): return reverse('product:product_detail', args=[str(self.id)]) def __str__(self): return self.nombre class PhotoProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) photo = models.ImageField(upload_to='images/') def __str__(self): return self.product.nombre Here's the views.py class ProductDetailView(generic.DetailView): model = Product queryset = Product.objects.all() template_name = 'product_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['photo_list'] = PhotoProduct.objects.all() return context Here´s the template <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for photo in photo_list %} {% if photo.product.pk == product.pk %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter0 }}" class="{% if forloop.counter0 == 0 %} active {% endif %}"></li> {% endif %} {% endfor %} </ol> <div class="carousel-inner"> {% for photo in photo_list %} … -
Using custom authentication backend with custom user model
Our service counts on firebase for user authentication so you can think of entities relevant to that are these three entities. Client (android/ios app) Server (django) Authentication service (firebase) The expected user flow is User do log-in in our client(app) via firebase. If authentication passes, client gets firebase_id_token from firebase. Client sends firebase_id_token to django(backend). Django verify given firebase_id_token using firebase Admin API. (going to make custom authentication backend) Once the given token(step#4) verified successfully, django returns token which should be passed when user want to hit api which requires user authentication. As you can see, there's no password at all as we're using firebase_id_token for all authentication processes. However, we still need user model which has username and password because we also use superuser for accessing admin page. I heard creating two types of user model is not a best practice so want to know what could be good solution for my current situation. Sorry for unsorted question and thanks in advance! Juram -
how to restrict pagination to certain pages in Django
I am a newbie in django following this example (https://www.youtube.com/watch?v=pyElWFn3XT4) ... everything seems to be working but the problem is with the pagination, as it is configured in base page and it is reflected on all the pages ... how can i restrict the pagination to certain pages ... Code <ul class="pagination"> <li class="page-item {% if not prev_page_url %} disabled {% endif %} "> <a class="page-link" href="{{ prev_page_url }}" tabindex="-1" aria-disabled="true">Previous</a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active" aria-current="page"> <a class="page-link" href=="?page={{n}}">{{n}}<span class="sr-only">(current)</span></a> </li> {% elif n > page.number|add:-3 and n < page.number|add:3 %} <li class="page_item"> <a class="page-link" href ="?page={{n}}">{{n}}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %} disabled {% endif %} "> <a class="page-link" href="{{next_page_url}}">Next</a> </li> </ul> but on this page or 2 other pages i don't want pagination to be displayed ( i.e. Next and Previous button displayed). Can some please help me on this .... -
Django can't find my template and look for a specific file name that don't exist
I have a templates folder inside the folder core, that is the core of my application, with a single file named home.html. But I'm getting the following error message in my browser: TemplateDoesNotExist at / core/post_list.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: core/post_list.html Exception Location: /home/shaiene-kun/Programação/Python/Virtual_Enviroment/lib/python3.8/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /home/shaiene-kun/Programação/Python/Virtual_Enviroment/bin/python Python Version: 3.8.2 Python Path: ['/home/shaiene-kun/Programação/Python/Django/python-studies/first_django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/shaiene-kun/Programação/Python/Virtual_Enviroment/lib/python3.8/site-packages'] Server time: Sun, 19 Jul 2020 03:31:58 +0000 But the thing that caught my eyes is this part: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/shaiene-kun/Programação/Python/Virtual_Enviroment/lib/python3.8/site-packages/django/contrib/admin/templates/core/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/shaiene-kun/Programação/Python/Virtual_Enviroment/lib/python3.8/site-packages/django/contrib/auth/templates/core/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/shaiene-kun/Programação/Python/Django/python-studies/first_django_project/core/templates/core/post_list.html (Source does not exist) I don't have no folder core inside my templates folder and I don't have a post_list.html file and nor do I create a reference for this file or path file nowhere in my code so why is it trying to find this? On the other hand I see no mention of the home.html file witch is the one I want to render. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Adding data into database from a JSON response using Django Rest Framework
I am trying to grab JSON data from an API that generates trivia questions. this is how it generates JSON responses { "response_code": 0, "results": [ { "category": "General Knowledge", "type": "multiple", "difficulty": "easy", "question": "In past times, what would a gentleman keep in his fob pocket?", "correct_answer": "Watch", "incorrect_answers": [ "Money", "Keys", "Notebook" ] } ] It can also generate more than one question. I need to take this data and insert it into my Question model. Here is what the model looks like class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) question = models.CharField(max_length=100000, unique=False, null=False) options = models.ManyToManyField("Options") user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) answer = models.ForeignKey(Options, related_name="correct", on_delete=models.CASCADE) difficulty = models.CharField(max_length=5000, null = True) type = models.CharField(max_length=2000, null = True) I am trying to use a view like this to add these values: @api_view(['POST']) @parser_classes([JSONParser]) def opendb(request): data = requests.get(url = request.data['url']).json() print(data) results = { "category": data['category'], "type": data['type'], "difficulty": data['difficulty'], "question": data['question'], "answer": data['correct_answer'], "option": data['incorrect_answers'] } Question = json.loads(data.content) Question.save(data) return JsonResponse( {"question": request.data }, status=status.HTTP_201_CREATED ) This however produces this error "category": data['category'], KeyError: 'category' What am i doing wrong here ? -
Django & Celery - Signalling Across Multiple Methods & Files
Problem I have a Django + Celery app, and am trying to get a lengthy method to run in a Celery Task. Goal I want to 1) Put an entire line of execution - that calls across multiple classes & files - into a Celery Task. The application should continue serving users in the meantime. 2) Signal back when the Celery Task is done so I can update the UI. Issue Despite scouring docs, examples, and help sites I can't get this working. I don't know which signals to use, how to register them, how to write the methods involved to receive those signals properly, and respond back when done. It isn't clear to me from the Celery documentation how to accomplish all of this: there are many, many signals and decorators available but little clarification on which ones are appropriate for this sequence of events. Help Requested Either A point in the direction of some resources that can help (better documentation, links to examples that fit my use case, etc...), or Some first-hand help with which signals are appropriate to use, where to use them, and why. This is my first post on StackOverflow, so thanks in advance for … -
Automating Settings.py Selection For Local and Prod
I have a two settings.py files: local.py and prod.py. As the names suggest, local.py is used for development and prod.py should be used when the server is deployed (which I am doing through EBS). Is there anyway to automate this, instead of swapping them in and out myself? How can I detect that I am running locally, vs. running on an EBS instance? Thanks! -
Django-allauth Prevent Re-send Verification Email Spam Clicking
I want to do something like Stackoverflow's post spam mechanism where a user is not allowed to submit the same form again until the timer expires. https://i.stack.imgur.com/4J3jr.png But I want to do this for django-allauth's /accounts/email/ Re-send verification button. Currently, a user could spam click that button over and over and it will spam that user's inbox with email. It would be nice to disable that button after clicking once then displaying a try again in X minutes message. Probably needs to happen on a user by user basis. https://github.com/pennersr/django-allauth/blob/master/allauth/templates/account/email.html#L35 What I have researched so far but not sure how to best implement it: from allauth.account.models import EmailConfirmation from datetime import datetime, timedelta from django import forms class TestForm(forms.Form): def clean(self): cleaned_data = super().clean() email_address = cleaned_data.get("email_address") most_recent_confirmation = EmailConfirmation.objects.filter(email_address=email_address).order_by("-sent").first() time_since_last_confirmation = datetime.now() - most_recent_confirmation.sent if time_since_last_confirmation.days < 1: raise forms.ValidationError( "Stop spamming. We already sent the email less than a day ago!" ) -
Why not makemigrations in Elastic Beanstalk Config File Django?
Go to aws's setup guide for deploying a django app to elastic beanstalk here and go to the "Add a database migration configuration file" section. You'll see that in the db-migrate.config file, they migrate the django app when it is deployed. I am wondering why they do not run makemigrations as well? Thanks! -
how adding new colum to permission table
i am django new bay, i do a lot search but no result. i need to add client_id to django permission model ( save and retrieve ), so when saving user permission client_id should saved with permission and when using has_perm it should check permission for current user for current client_id adding example : user.user_permissions.add(permiObject, request.session['ClientId']) in template if i check : {% if perms.app_name.perm_code %} this check should be for current ClientId -
Will the django built in password reset views work with a custom user that inherits from AbstractBaseUser?
I an going to build a custom django user and a custom log in and sign up views and I want to know if the I should build a custom password reset view as well. -
Corey Schafer Django (Part 3): HTML not formatting right
So I'm going through Corey Schafer's Django series, and I'm at the part where he is building the HTML template for the website and for some reason it isn't formatting correctly. I downloaded his repository and re-ran his code and still got the same error? The only difference that I can think of is that he is using Django 2.1 and I'm using Django 3.0 but that shouldn't be it. Here is how it looks: And here is the HTML code for the base.html file: {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> … -
Conditions Relying On Multiple Models In Template
Each Student has a StudentUnitData object holding data unique to that Student/Unit pair. class StudentUnitData(models.Model): student = models.ForeignKey(Student) unit = models.ForeignKey(Unit) passed = models.BooleanField(default=False) Each StudentUnitData has three Tests holding data on each of the three tests a Student will take in each Unit. class Test(models.Model): student_unit_data = models.ForeignKey(StudentUnitData) test_number = models.CharField(max_length=2, choices=TEST_NUMBER) completed = models.BooleanField(default=False) Now in my template I loop through and print each of a Students StudentUnitData. I want to set the div to one of three different colors. Blue if all the Tests are not completed for that StudentUnitData (signifies current, unfinished unit - loop would not continue to the following checks). If all Tests are completed it will continue to the next code block. Here it will check if StudentUnitData is passed or not, setting the color to green if True, red if False. {% for unit in student.student_unit_data.all %} # checking if all three tests have been completed {% for test in unit.test.all %} {% if ALL THREE OBJECTS NOT .completed == True %} <div class="panel-heading blue"> # skip the next code block and move on to the next unit {% endfor %} # else, all tests are completed {% if unit.passed == True … -
Exception thrown while calculating Exponential moving average using pandas
While calculating EWM using pandas I am getting below error. comass, span, halflife, and alpha are mutually exclusive Code: symbol = yf.Ticker(symbol_record.symbol) symbol_his_data = symbol.history(start=today, interval='30m') try: symbol_his_data['8_ewm'] = symbol_his_data.ewm(span=8, adjust=False).mean() except Exception as e: print('Exception occurred while calculating 8 ewm:{}'.format(e)) Not sure if it matters but I am using django-celery and threading. So at a time max 5 workers are working on max 5 different symbols.