Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django csrf_protect decorator not working
I am using Django to build a web app. I am using Vue JS for the frontend. My problem is when ever I use csrf_protect its showing 403 error My views: @csrf_protect def SignUpView(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') new_user = authenticate(username = username, password = password) login(request, new_user) return redirect('/') else: form = SignUpForm() return render(request, 'Accounts/SignUp.html', {'form':form}) @csrf_protect def validateUsername(request): username = request.GET.get('username', None) usernameRegEx = r'^[a-zA-Z0-9@+-_.@]*$' usernameRegExResult = { 'valid' : bool(re.search(usernameRegEx, username, re.M|re.I)), 'is_taken' : User.objects.filter(username=username).exists() } return JsonResponse(usernameRegExResult) I read the Django docs which says I can use csrf_protect decorator above my view but in my case its not working. Somebody please help. -
How can I make sure that the data is from the login user in Django?
I'm trying to save the data I've received from Arduino in the DB. We have succeeded in receiving and storing temperature and humidity data, but failed to link this data with logged-in users. Can you help me? Here is my code. views.py from .models import arduino from .serializers import arduinoSerializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.generics import CreateAPIView class arduinoToAndroidViewSet (ViewSet) : def dataSend (self, request) : user = self.request.user queryset = arduino.objects.filter(name = user) serializer = arduinoSerializers(queryset, many=True) return Response(serializer.data) class arduinoToDatabaseViewSet (CreateAPIView) : serializer_class = arduinoSerializers def get_queryset(self) : user = self.request.user return arduino.objects.filter(name = user) def dataReceive(self, request) : queryset = get_queryset() serializer = arduinoSerializers(queryset, many=True) if serializer.is_valid() : serializer.save() return Response(serializer.data) serializers.py from rest_framework import serializers from .models import arduino class arduinoSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username', read_only=True) class Meta : model = arduino fields = ('name', 'temp', 'humi') [![enter image description here][1]][1] If you post it like this, [![enter image description here][2]][2] I want you to know that this is root's data. [1]: https://i.stack.imgur.com/tHWXa.png [2]: https://i.stack.imgur.com/JNRiP.png -
Does the UserCreationForm from the django.contrib.auth.forms in django not work anymore?
I was trying to register a new user through the frontend with the help of django but i saw quite a few tutorials use UserCreationForm but for my case it does't seem to work. views.py def registerUser(request) : form = RegisterForm() context = {'form':form} if request.method == 'POST' : form = RegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'User Created succesfully') print('user Created') return redirect('users:login') else : print('Not valid') return render(request, 'register.html', context) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] My is_valid() function is giving me that the request.POST isn't valid. -
why my django profile update function not wokring?
I am only trying to test the default user profile update through UserChangeForm. Just the email field. So below are the code snippet. views.py @login_required(login_url="/login/") def editUserProfile(request): if request.method == "POST": form = UserProfileUpdateForm(request.POST, instance=request.user) if form.is_valid(): form = UserProfileUpdateForm(request.POST) form.save() return redirect('thank_you') else: messages.error(request, f'Please correct the error below.') else: form = UserProfileUpdateForm(instance=request.user) return render(request, "authenticate\\editProfilePage.html", {'form': form}) forms.py class UserProfileUpdateForm(UserChangeForm): email = forms.EmailField() class Meta: model = User fields = ('email', ) HTML <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">Update Profile</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action="{% url 'editUserProfile' %}"> {% csrf_token %} <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{form.email}} </div> <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="update" value="update"> </div> </form> </div> {{form.errors}} <script> /* Because i didnt set placeholder values in forms.py they will be set here using vanilla Javascript //We start indexing at one because CSRF_token is considered and input field */ //Query All input fields var form_fields = document.getElementsByTagName('input') form_fields[4].placeholder='email'; for (var field in form_fields){ form_fields[field].className += ' form-control' } </script> </body> In the user profile page, I could see the update button, and when I click on it I … -
How to get common objects from 2 querysets in Django?
I have 2 querysets of same model (obtained from different functions). Now I want to see common elements in them on the basis of some fields like: first_name, last_name, date_of_birth, abc_field(boolean field) They will have different primary keys, and unique ids. The only difference in them should be that abc_field should be True in one object and False in another object. How do I achieve this? I read online about annotate(Count()), but I think this would make the code look a bit naive, with all those Count() on every field. -
How to exclude a specific instance from a nested serializer, but include it in the underling model
Is there a way to exclude a specific instance from a nested serializer, but include it in the underlying model? Consider the following code: models.py class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ForeignKey(Author, related_name="books") serializers.py class BookSerializer(serializer.ModelSerializer): class Meta: model = Book fields = ["title"] class AuthorSerializer(serializer.ModelSerializer): class Meta: model = Author fields = ["name", "books"] books = BookSerializer(many=True) def update(self, instance, validated_data): books_validated_data = validated_data.pop("books") author = self.update(instance, validated_data) for book_validated_data in books_validated_data: # this might not be valid code, but you get the idea Book.objects.update_or_create(author=author, **book_validated_data) return author Now, suppose that every author must have the book "Hamlet". But, I don't want to include that book in the serializer output or input. >> shakespeare = Author(name="Shakespeare").save() >> hamlet = Book(author=shakespeare, title="Hamlet").save() >> othello = Book(author=shakespeare, title="Othello").save() When I serialize that I ought to return something like: { "name": "Shakespeare", "books": [{"title": "Othello"}] } Notice that "Hamlet" is not there. But when I POST something like this to the serializer: { "name": "Shakespeare", "books": [{"title": "Othello"}, {"title": "King Lear"}] } I don't want the code to wind up removing the existing "Hamlet" (even though it's not specified in the JSON above). Any ideas? -
Is there a django admin widget that allows the admin to sort model objects by fields values?
I am building an app in Django. I found there is a very easy way to integrate a widget into django admin that allows the admin to filter model objects by fields values. That is achieved by including the line list_filter = ['field_to_filter_by_its_values'] into the class mymodelAdmin(ImportExportModelAdmin) in admin.py, as shown below class target_area_history_dataAdmin(ImportExportModelAdmin): resource_class = target_area_history_dataResource list_filter = ['Target_area_input_data__Name'] admin.site.register(target_area_history_data, target_area_history_dataAdmin) Now, instead of integrate a widget to filter my model objects by that field, is there a way to integrate a widget to sort my model objects by that field? Note: I am using Django Import-Export in my model. -
Django/Django-axes, how to get number of attempts?
I just installed django-axes, it works properly and users get logged out after 10 attempts as in my settings. However, I want to display as well how many more tries the user has before he is logged out. How do I do this? I read the docs that there is a get_failures() thing in the api, but how do I import it? -
How do I save a custom user class attribute in Django?
I am fairly new at using Django, so pardon if anything in unclear. Basically, I have created a custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class AccountManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError('A username is required for you to sign up') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): user = self.create_user( password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) password = models.CharField(max_length=999) points = 0 date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' # Cannot be included in required fields REQUIRED_FIELDS = ['password'] objects = AccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin @staticmethod def has_module_perms(app_label): return True Under class Account(AbstractBaseUser), I have defined an attribute points. I want to make it such that whenever the user redirects, the user gets some points. from django.shortcuts import render, redirect def home_page_view(request): return render(request, "home_page.html", {}) def free_points(request): request.user.points += 10 request.user.save() return render(request, "add_points_test.html", {}) To check whether the points has been added, I … -
How can i solve problem with decimalfield?
def cnt_cash(request): orders = OrderItem.objects.filter(created__day=datetime.today().day) total_cash = 0 for i in orders: if int(i.length) > 0: total_cash += i.price * i.quantity * int(i.length) * int(i.width) elif int(i.weight) > 0: total_cash += i.price * i.quantity * int(i.weight) else: total_cash += i.price * i.quantity cashBox = CashBox.objects.filter(created__day=datetime.today().day) if cashBox: cashBox.update(total_cash=total_cash) else: cash = CashBox() cash.total_cash = total_cash cash.save() return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] Hi, i want to calculate total cash and add it to the today's cashbox, but this error is popping up -
Django: user.save() not saving updates to extended from
I am making a bank transaction system and I want the user to withdraw and deposit the amount into their account. I made the balance field in an extended form as the default UserCreationForm does not have a balance field. See the code below: views.py @login_required(redirect_field_name='login-page') def dashboard(request): if request.method == 'POST': withdrawAmount = request.POST.get('withdraw') depositAmount = request.POST.get('deposit') print(withdrawAmount, depositAmount) user = User.objects.get(username=request.user.username) print(user) if withdrawAmount == None and depositAmount == None: return redirect('dashboard') messages.info(request, "Amount empty!") elif depositAmount == None: user.account.balance = user.account.balance - int(withdrawAmount) user.save() elif withdrawAmount == None: pass customer = User.objects.all() return render(request, 'bankapp/dashboard.html', {'customer': customer}) models.py from django.db import models from django.contrib.auth.forms import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField() def __str__(self): return self.user.username forms.py from django import forms from django.contrib import messages from django.contrib.auth.forms import UserCreationForm, User from .models import Account class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=128, help_text='Input valid email') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') class AccountForm(forms.ModelForm): class Meta: model = Account fields = ('balance',) The code works perfectly and gives no errors but the balance does not get updated in the database. Any help would be greatly appreciated! -
How to add a countdown timer as a user field in django?
I want for every user on an application that they have a field with a certain time, which gets used up when using the website. So if you have an account with 10 hours, there is a field that counts down those 10 hours. Is there any existing way how to do this and have it continuously update? Right now I have a custom model with a time_left field: class User(AbstractBaseUser, PermissionsMixin): """ Custom user class which overrides the default user class. """ email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) time_left = models.TimeField(default=datetime.time(0, 0)) And then I have a context processor to display the time_left: def time_left(request): time = datetime.time(0, 0) if request.user.is_authenticated: user = User.objects.get(email=request.user.email) time = user.time_left print(time) return {'time_left': time} Edit: Thinking about it, the only way to update the time left on the page itself is probably like JQuery and AJAX. Am I correct in this assumption? Still need to update the number in the backend though. -
How to preserve the test data generated by pytest-django fixtures
I have been looking for a way to preserve the database records generated by pytest fixtures because the fixture data should be very useful not only for the pytest but also for the acceptance test. For example, I have pytest fixtures something like below: @pytest.fixture def employee(company): return Employee.objects.create( **{ 'company': company, 'name': 'MyName', 'email': 'example@example.com', } ) However, after the pytest finishes, I get the following result. (Although I get 1 as a response during pytest process.) user@56c27685fc50:~$ manage.py shell_plus # Shell Plus Model Imports from project.apps.core.models.common import Employee Python 3.8.1 (default, Feb 2 2020, 08:37:37) Type 'copyright', 'credits' or 'license' for more information IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: Employee.objects.count() Out[1]: 0 I would appreciate if you could share some idea to preserve the fixture data. Thank you so much in advance. -
InterfaceError at line of amodel.save()
I get a InterfaceError at the line res.save() in the method results of views.py. I think, that problem due to using standard SQL db, but now i use nosql and update my settings.py to use a NoSQL db for my app result After doing migrations file 'db.djongo' was not created. results/models.py from django.db import models from django import forms from inputData.models import Input from inputData.forms import CustomInputUserCreationForm as uform from django.contrib.postgres.fields import JSONField # Create your models here. class Results(models.Model): generator = models.OneToOneField(Input, on_delete = models.CASCADE, primary_key = True) path = models.FilePathField() pvalues = JSONField() results/views.py from django.shortcuts import render from django.http import Http404 from .models import Results from inputData.models import Input from . import parse_res from diehard.settings import BASE_DIR import os # Create your views here. def result(req, res_id): try: inp = Input.objects.get(pk = res_id) path = os.path.join(BASE_DIR, 'uploads\\' + str(res_id) + '\\t.txt') p_values = parse_res.main(path) res = Results(generator = inp, path = path, pvalues = p_values) g = dir(res) res.save() except Results.DoesNotExist: raise Http404 return render(req, 'result.html', {'res': res}) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', #new 'inputData', #new 'results', #new 'tags', #new ] #--------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
How to use an image as an input after uploading it with in my django app
I have a django app that upload an image to pass it to an OCR model. The first step of my OCR is the preprocess step for that it need to open the image with the cv2.imread() function. For uploading the image I used "ImageField". When I upload the image I get the error: attributeerror 'imagefield' object has no attribute 'copy' As far as what I understand it that I need to change the object type of the ImageField. Is this the problem? If it is how to correct it? Django Model: class Facture(models.Model): Client = models.ForeignKey(Client, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) STATUS = (('Non Validé', 'Non Validé'),('Validé', 'Validé'),) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Non Validé') note = models.CharField(max_length=1000, null=True) Img = models.ImageField(upload_to='images/') Django View: if request.method == 'POST': form = FactureForm(request.POST, request.FILES) if form.is_valid(): facture=Facture() facture.Img = form.cleaned_data["Img"] facture.note = form.cleaned_data["note"] img = cv2.imread(facture.Img) blob,rW,rH = preprocess(img) res=EASTmodel(blob) sent=tesseract (res,rH,rW) print(sent) client=Client.objects.filter(user=request.user).first() facture.Client=client facture.save() The preprocess function: def preprocess(img): #Saving a original image and shape image = img.copy() (origH, origW) = image.shape[:2] # set the new height and width to default 320 by using args #dictionary. (newW, newH) = (3200, 3200) #Calculate the ratio between original and … -
Setting Environment Variable in Virtualenv Windows
I am trying to set the environment variable in virtualenv. I have tried almost every approach from SO.In my settings.py i have declared SECRET_KEY=os.environ['SECRET_KEY'] I have declared all my environment variable at the end of venv\Scripts\activate I tried set,SET,setx,export i also tried to put the environment variable in json but none of these are working. Whenever i try to run python manage.py runserver it is giving me error django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I dont know what i am missing or what is going wrong? -
Highlight to download
I have been developing a website using Django web framework and I got an idea which goes as follows: For example, let's say that I have released my product on the website that I have been developing. In all the websites, there is an exclusive Download button to download the product. But I want something like this: There will be a sentence description about the product which contains a WORD (NOT A LINK) "download". When a user HIGHLIGHTS the word download and highlights the operating system (platform) the webpage should split open like a lid saying "Your download will begin shortly." and the product downloads. No buttons are to be included. For example if below is the product description: This my product. Something here something there blah blah blah...... You can download it for Windows x64, Windows x86, MacOS and Linux.. And if the user highlights the word download by dragging the mouse over the word and selecting it (blue color over the word) and THEN Windows x64 then it has to split open the webpage saying "Your download will begin shortly" and should actually download it. (The purpose of saying "and then" above is that since the download and … -
Django - Form is not saving to Db
I'm using for authentication extended AbstractUser and ModelForm. When I write on HTML page only {{ form }} everything works fine, the form is submitting, but in the following case I've added some stylings, but now nothing works. Please, help me find the reason. HTML: <form method='POST'> {% csrf_token %} <div class="sign-up-user"> <div class="sign-up-user-container"> <div class="sign-up-user-left"> <label for="">{{form.username.label}}</label> {{form.username}}<br> <label for="">{{form.password.label}}</label> {{form.password}}<br> <label for="">{{form.branch.label}}</label><br> {{form.branch}}<br> <label for="">{{form.license_number.label}}</label> {{form.license_number}}<br> <label for="">{{form.fin_number.label}}</label> {{form.fin_number}}<br> <label for="">{{form.voen_number.label}}</label> {{form.voen_number}}<br> </div> </div> <input type="submit" value="Register User" class="sign-up-btn"> </div> </form> -
url.py settings.py with external storage with dropbox
I would like to use dropbox as external storage. I have been working on this for a week and I think identified the problem. url.py has: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py contains : STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_FILE_STORAGE = "storages.backends.dropbox.DropBoxStorage" DROPBOX_OAUTH2_TOKEN = #mytoken I obtain the error: ApiError('d5b8d0d14e950566defb5ca736ebda9a', GetTemporaryLinkError('path', LookupError('not_found', None))) because it can't find the static there: <img src="{% static 'logo.png' %}" height = 300></img> How do I configure STATIC_ROOT and STATIC_URL (and MEDIA_ROOT/MEDIA_URL) in order to link to dropbox url? I'm expecting something like : STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) Thank you in advance. -
Error in reading expression matrix txt file by scanpy
I am trying to read expression matrix file in python using scanpy. The code is : adata.var = sc.read_csv('EXP0001_PCG_beforeQC.txt') But I am facing this error: Traceback (most recent call last): File "", line 1, in File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 48, in read_csv return read_text(filename, delimiter, first_column_names, dtype) File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 322, in read_text return _read_text(f, delimiter, first_column_names, dtype) File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 352, in _read_text raise ValueError(f"Did not find delimiter {delimiter!r} in first line.") ValueError: Did not find delimiter ',' in first line. adata.var = sc.read_csv('/home/sidrah19220/rna/auxfile/EXP0001_PCG_beforeQC.txt') Traceback (most recent call last): File "", line 1, in File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 48, in read_csv return read_text(filename, delimiter, first_column_names, dtype) File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 322, in read_text return _read_text(f, delimiter, first_column_names, dtype) File "/home/sidrah19220/anaconda3/envs/scenic_protocol/lib/python3.6/site-packages/anndata/_io/read.py", line 352, in _read_text raise ValueError(f"Did not find delimiter {delimiter!r} in first line.") ValueError: Did not find delimiter ',' in first line. Please suggest solution. -
Django - save model only works sometimes on AWS only
Mi main problem is that I have the following function (here includes the debugging I made for AWS by sending me emails with the information I need): def decrease_blocked_amount(inv_camp, amount): """ Decreases the blocked amount on an investment campaign :param inv_camp: An InvestmentCampaign object :param amount: An int representing the amount to decrease """ mail_admins(message="init - inv_camp=%s, amount=%s" % (inv_camp.blocked_amount, amount), subject="test") inv_camp.blocked_amount -= amount inv_camp.save() time.sleep(2) mail_admins(message="saved - inv_camp=%s, amount=%s" % (inv_camp.blocked_amount, amount), subject="test") time.sleep(2) inv_camp_test = InvestmentCampaign.objects.get(id=inv_camp.id) mail_admins(message="from database - inv_camp=%s" % inv_camp_test.blocked_amount, subject="test") As you can see this is a simple function that just decreases the blocked_amount on an inv_camp object. This function is called from a webhook that Stripe sends to my application when a PaymentIntent is cancelled. I have plenty of saves on my application and of course all of them work well, but in this case I really don't know what to do because: Testing locally it works always (100%) fine. Testing on AWS, just this save is not working when I cancel a payment on stripe and then create a new one. The webhook that receives the cancelled payment information executes the function, I get the 3 emails on the function and then … -
how to display comments with ajax submit call on the same post detail page
I am trying to display user comments after they click on the comment submit button. I added an ajax call on my comment section. However when i click on the submit button after writing a comment, Page is not refreshing but it is not displaying the new comment right away. Only after i refresh the page my new comment is available. I want to display new comment on the page right after clicking the submit button without reloading the page. I am unable to figure out what is going wrong here, my codes are as follow: at the end of base.html <script> $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), datatype: 'json', success: function(response) { $('.main-comment-section').html(response['form']); }, error: function(rs, e) { console.log(rs.responseText); }, }); }); My comment_section.html <h1>New comment</h1> <form method="post" class="comment-form" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" class="save btn btn-outline-success"> </form> {{ comments.count }} Comments</h3> <!-- comments --> {% for comment in comments %} <article class="media comment"> <img class="rounded-circle article-img" src="{{ comment.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-profile' comment.author.username %}">{{ comment.author.first_name }} {{ comment.author.last_name }}</a> <small class="text-muted">{{ comment.created_date }}</small> </div> <p class="article-content" "mr-4">{{ comment.content | linebreaks }}</p> … -
render details in django email
I'm using Django celery to send emails when the manufacturing date is none. I'm successfully sending emails, however in the email, I also want to include the order ID of that particular order that has no manufacturing date, how can I do that? @shared_task def check_for_orders(): orders = Order.objects.all() for order in orders: if order.manu_date is None: send_mail('Manufacturing Reminder', ' {{order.id}} manufacturing date is none ', 'dummyguy1680@gmail.com', ['dummyguy1680@gmail.com']) return None -
Django: Error 404 while trying to upload images on ImageField forms
I created a model with an ImageField and setup the media storage of Django to store files on Google Cloud. Everything seems to work fine locally, and I can create a new object from the cPanel and upload an image that successfully goes to Google Cloud bucket. The problem showed up when I uploaded the project to my webserver. When I try to create an object there, it throws an 404 error page not found on POST Request. It only happens when I try to create objects for this model. Is it possible that something in the webserver host, blocks the POST requests that contain a file? Thinks I've checked: Django version 3.0.6 Pillow version 7.2.0 Python version > 3.5 Webserver successfully speaks with Google Cloud Bucket -
Is there a way to authenticate ACTIVEMQ consumer using django rest framework application?
I am working on an IoT project. The application is divided into 3 parts UI, Backend, and Message Broker. I am using Django as a backend application that does all user authentication, authorization tasks. For real-time communication between sensors and the UI Dashboard, I am willing to use ActiveMQ. Now, I want every consumer (UI application) to be authenticated before establishing connection to the ActiveMQ. Is there any way or plugin for ActiveMQ to achieve this? I am using JWT token to authenticate User for UI application. And, want to share the same token for consumer authentication.