Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image not being uploaded after posting (DJANGO)
I am working on a project on DJANGO which I need to upload a image of a book on the post created by the user which then will be displayed on the post itself ,but when I click on the post button nothing happens and I am not redirected anywhere,if i create the post on the admin page everything works fine, I have tried everything so far but nothing has solved this problem, bellow I will be posting my code for reference, thank you ! views.py: class BookCreateView(LoginRequiredMixin, CreateView): #sets up form to create new post /post/new model = Book fields=['Title','Author','Publisher','isbn','book_img','course', 'schools','content'] def form_valid(self, form): form.instance.author = self.request.user #get users name to put on the post return super().form_valid(form) models.py class Book(models.Model): Title = models.CharField(max_length=30, default='not declared') Author = models.CharField(max_length=30) Publisher = models.CharField(max_length=30) Year = models.DateTimeField(default=timezone.now) classes = models.ManyToManyField(Class) schools = models.ManyToManyField(School) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) book_img = models.ImageField(upload_to='books_image',default='default.jpg',blank=True, null=True) isbn = models.IntegerField(default=000) content = models.TextField(max_length=50, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #deleted post if user is deleted class Meta: db_table = '5- Books' def __str__(self): return self.Title def save(self, **kwargs): super().save() img = Image.open(self.book_img.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) … -
Django - Why do I need to specify the user.backend when logging in with a custom backend?
The code works as is, I'm just hoping somebody can provide an explanation here. I set up a custom backend for my app. Code below: from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model class AuthenticationBackend(BaseBackend): def authenticate(self, request, username=None, password=None, email=None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None And here is the view: def login_view(request): form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) print(request.user) return redirect('tasks') context = { 'form': form } return render(request, 'users/login/index.html', context) Along with the form (Note much of the login functionality was abstracted to the form) class LoginForm(forms.Form): email = forms.CharField(max_length=255, required=True, widget=forms.TextInput(attrs={'class': 'form_input'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form_input'}), required=True) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') user = authenticate(email=email, password=password) if not user or not user.is_active: raise forms.ValidationError("Sorry, that login was invalid. Please try again.") return self.cleaned_data def login(self, request): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') user = authenticate(email=email, password=password) return user In the login_view code, I had an issue. Before adding the "user.backend = ..." line, the system would login the user successfully, however upon redirecting to the 'tasks' view, the … -
Multiple select2 elements on one page not working
I want to have multiple select2 on one page. The app has several posts and each post will have a select element. I am hiding the element until the user clicks on a button which then shows select. The problem is that only one select2 works. Here's my HTML: <button onclick="change_tags({{ file.id }})" class="btn btn-info btn-sm change-tags-btn">Change Tags</button> <select class="custom-select js-example-basic-multiple change-tags-select form-control " id="change-tags" name="usertags1" multiple="multiple"> {% for tag in userTags %} <option value="{{ tag }}" id="{{ tag }}" data-id="{{ tag.color }}" class="options">{{ tag }}</option> {% endfor %} </select> JQuery: $('.change-tags-btn').click(function(){ setTimeout(function(){ $('#change-tags').select2() },1000); }); -
How to set a default to a forms.ChoiceField()?
I am trying to set a default selection for payment choices to be Stripe, but I keep getting an errorTypeError: __init__() got an unexpected keyword argument 'default' Here is the forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES, default='Stripe') -
In Django, when the web app has to send an email it throws same Authentication error after some days of being fixed
It happened three times already. In these three times to fix it I had to do these steps: Go to the allow less secure apps google page and enable it Go to the allow access to your account google page and press the blue button Those two steps, are the ones that I have to do everytime the process of sending the email fails. I do those steps, the error gets fixed, some days pass, and the error shows up again. I don't know what to do. I'll accept the answer of course! Thank you very much beforehand :) -
How to use vue development mode with Django
I don't know how to run development mode with Django. I'm running webpack and when I finish all the Vuejs work I just bundle all to a folder where Django serves It as a static file. I know taht I've to run webpack with mode development but that doens't work, It gives me a cannot found error. I'd like to run Vuejs in development mode alongside with Django, how can I do that? I'll share to you my project structure, my package.json and webpack config. const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { entry: './frontend/Vue/main.js', output: { filename: 'build.js', path: path.resolve(__dirname, './static/js'), publicPath: '/static/js' }, module: { rules: [ { test: /\.(js)$/, exclude: /(node_modules)/, use: [ { loader: 'babel-loader' } ] }, { test: /\.(css|scss)/, use: [ 'style-loader' ] }, { test: /\.vue$/, exclude: /node_modules/, loader: 'vue-loader' } ] }, devServer: { // contentBase: ponerle la ruta del index de django contentBase: path.join(__dirname, 'templates'), watchContentBase: true, historyApiFallback: true, noInfo: true }, plugins: [ new VueLoaderPlugin() ] } package.json { "name": "TuDistribuidora", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --mode development --port 9000 --open", "build": "webpack … -
How to authenticate with django-grahql-jwt in a graphene-django Using GraphQLTestCase?
I am about writing test for my Django project in graphql but I usually get errors while trying to authenticate my users using JWT. Here is my code. from django.test import TestCase import json from graphene_django.utils.testing import GraphQLTestCase from resume.graph.schema import schema from .models import Post from django.contrib.auth import get_user_model from graphql_jwt.shortcuts import get_token User = get_user_model() class PostTestCase(GraphQLTestCase): GRAPHQL_SCHEMA = schema def test_post_list(self): token = get_token(User.objects.get(pk=1)) headers = {"HTTP_AUTHORIZATION": f"JWT {token}"} response = self.query( ''' query { post{ user text } } ''', op_name = 'post', headers=headers, ) content = json.loads(response.content) self.assertResponseNoErrors(response) -
django: how to make a template downlaod
I have a form in my django app where user's data is pulled automatically as well as writeable fields for the users to fill in inside of the template. I built another html page that contains the shape of the pdf documents and I am trying (unsuccessfully) to get the data entered by the user in the template rendered in the pdf. I am only able to render the pdf but with none of the fields filled in. I am honestly over my head with this part of the project and I cannot figure out what is going on causing the bug. I hope that someone could help me out. here is my view where the user edits the pdf: def invoice_generator_assembly(request): challan_number = ChallanNumber.objects.get(id=1) works = Work.objects.all().order_by('code') hsc = HSCNumber.objects.all() company = MyCompany.objects.get(id=1) context = { 'works' : works, 'hsc' : hsc, 'challan_number': challan_number, 'a' : company, } return render(request, 'invoice_assembly.html', context) and here is what the view for the rendered pdf looks like: def generate_pdf_assembly(request): ''' Helper function to generate pdf in case of ajax request ''' context = request.GET.copy() context['works'] = json.loads(context['works']) #context['amount_in_words'] = num2words.number_to_words(round(float(context.get('grand_total')), 2)) + ' only' challan_number = context.get('challan_number') date = context.get('date') client_name = … -
Django unittest to show home url
I've been stuck on this for too long now. I am new to Django and testing. I want to incorporate it into an app I am working on, but need some help. What I am trying to do: write a unittest to test the homepage url. It is named coverletter-home in coverletter app -
django create view does not update database
class Product(models.Model): #store= models.ForeignKey(Store,related_name='item', on_delete=models.CASCADE) name= models.CharField(max_length=500) text=models.TextField() price = models.FloatField() stock= models.BooleanField() join_discount=models.BooleanField(default=True) image_1 = models.ImageField() image_2 = models.ImageField(blank=True,null=True) image_3 = models.ImageField(blank=True,null=True) image_4 = models.ImageField(blank=True,null=True) image_5 = models.ImageField(blank=True,null=True) order_in_store=models.IntegerField(validators=[MinValueValidator(1)]) def get_absolute_url(self): return reverse("core:Item" , pk={ 'pk': self.pk }) class CreateProduct(LoginRequiredMixin,generic.CreateView): model=models.Product fields=('name','text','price','stock','order_in_store','image_1','image_2','image_3','image_4','image_5','join_discount') template_name='core/item_create.html' permission_required = ('core.view_product', 'core.change_product','core.add_product') def form_valid(self, form,pk): logger.info('form_valid called') store=Store(pk=pk) self.object = form.save(commit=False) self.object.store =store self.object.save() return super(CreateProduct,self).form_valid(form) {% extends "core/base_store.html" %} {% block content %} {% load bootstrap3 %} <form method="POST",action=''> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Create"> {% endblock %} I have tried modelform view, also not working. The log info never poped so I guess the validation is never completed. -
How to decode this session data?
I have an old django application running and I'm trying to figure out how to parse a session object. Here is what I have thus far: >>> import base64 >>> x = base64.b64decode(session_data) >>> x '7489edf05bcdeae69f718ed7c809b32539646478:\x80\x02}q\x01(U\x12_auth_user_backendq\x02U)django.contrib.auth.backends.ModelBackendq\x03U\r_auth_user_idq\x04\x8a\x01\x01u.' From this, how would I get something like: { 'auth_user_backend': 'django.contrib.auth.backends.ModelBackend', 'auth_user_id': '...', } My current approach was to do a regex, but that seems possible like the worst solution. -
Vue.js and django MIME Type Issue
I'm deploying to heroku a vue.js app nested inside a django project. I followed this guide verbatim https://medium.com/@williamgnlee/simple-integrated-django-vue-js-web-application-configured-for-heroku-deployment-c4bd2b37aa70 Build to heroku succeeds, and the website loads -- the API portion for example is fully viewable. But I am not able to access the vue.js app because there is a MIME type issue. Error log: The resource from “https://heseltime.herokuapp.com/static/css/app.48175cc56e52e020bf178616c0977374.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). https://heseltime.herokuapp.com/ is the site in question. When I ssh into the heroku side I find the files in the right staticfiles location as per my settings.py from django # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' CORS_ORIGIN_ALLOW_ALL = False The html of the website is loaded as <!DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=viewport content="width=device-width,initial-scale=1"> <title>heseltime</title> <link href=/static/css/app.48175cc56e52e020bf178616c0977374.css rel=stylesheet> </head> <body> <div id=app></div> <script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script> <script type=text/javascript src=/static/js/vendor.7e9567d6dec21d8821f2.js></script> <script type=text/javascript src=/static/js/app.f5b30ee15ad2f9646708.js></script> </body> </html> This looks good to me (?) -- Could this be a CORSHeaders issue? -
Django scheduling a script using Schedule
Im trying to schedule a script that i have made to scrape data from a website. The function im trying to schedule is ment to add the data to the database and also check if it exits. This is the function and how i implemendet schedule. def scrapedata(): car_data = carscraper() for i in car_data: car = CarModel.objects.create( title = i[0], img_url = i[1], link = i[2], model_year = i[3], mileage = i[4], price = i[5], ) if CarModel.objects.filter(title=i[0]).exists() == False: car.save() schedule.every(20).seconds.do(scrapedata) while True: schedule.run_pending() time.sleep(1) The problem is that the sever never runs when i have this script. Ive placed the code i my views.py. so this code that i pasted is my views.py for my application. The error i get when trying doing this is: Watching for file changes with StatReloader Performing system checks... Im powershell. Ive just learned to use the schedule libarary so i must be doing somthing wrong. Any ideas? And if you know any better ways to do this feel free to comment, open for any sulutions. -
Django Nginx EC2 Ubuntu 18 site cannot reach site
I cannot access my django application on my public site. I am running Gunicorn with gunicorn --workers 3 --bind unix:/webapps/pcfnet/paulcflynn/pcfnet/pcfnet.sock pcfnet.wsgi:application and my NGINX file looks like so: server { listen 80; server_name paulcflynn.net; # to avoid any error while fetching fevicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /webapps/pcfnet/paulcflynn/pcfnet; } location / { include proxy_params; # communicate via socket file created by Gunicorn proxy_pass http://unix:/webapps/pcfnet/paulcflynn/pcfnet/pcfnet.sock; } } I am hosting an Ubuntu 18 instance on EC2 and cannot figure out why I am receiving this error. When I curl localhost I get a bad request error 400. Any idea what my configuration is missing? -
Check django_sessions to see if a user is logged in
Given an email, is it possible to check to see if that user has a currently logged in session? For example, something like: django_session.objects.filter(hashed_email='user@gmail.com') The above is in pseudocode, but the point is, given a user's email, can I check to see if they have an active session? Note, please do not suggest something like request.user.is_authenticated or any of the django-auth stuff, I only have a raw session for the task at hand. -
Prevent race conditions in sending data to endpoint and storing in database in Django REST API
I am writing a web application in Django REST API where I have an endpoint that accepts POST requests: https://website.com/api/receive-data with the following body: { 'value': 1, } And my code: # models.py class MyModelA(models.Model): status = models.BooleanField(default=False) class MyModelB(models.Model): value = models.IntegerField() model_a_pk = models.IntegerField() # views.py class ModelBRecordData(APIView): def post(self, request, format=None): serialzier = ModelBSerializer(data=request.data) if serializer.is_valid(): model_b = MyModelB.objects.create(value=value, model_a_pk=serializer.data.get('model_a_pk')) model_b.save() model_bs = MyModelB.objects.filter().count() if model_bs > 100000: model_a = MyModelA.objects.filter(pk=serializer.data.get('model_a_pk')).first() model_a.status = True model_a.save() The problem here is that I may be receiving 1000 endpoint requests at the same time. This will get this app into race conditions so more than a 100,000 records may be created while model_a is still being updated. How do I prevent this kind of race condition in an app like this? -
Django with Jinja2: template search path
I'm new to Jinja. Hope some one could answer this simple question. If Jinja encounters the following at the line of the template: {% extends "details.html" %} what are the paths it will search to locate details.html? Is there a environment variable or a variable in settings.py to set? -
Object of type AccessToken is not JSON serializable
So I am trying to send an email through my Django REST api, I am using Django_Rest_simplejwt for authentication, I am getting the following error when POSTing: TypeError at /auth/register/ Object of type AccessToken is not JSON serializable Request Method: POST Django Version: 3.1 Exception Type: TypeError Exception Value: Object of type AccessToken is not JSON serializable Exception Location: C:\ProgramData\Miniconda3\lib\json\encoder.py, line 179, in default Python Executable: C:\ProgramData\Miniconda3\python.exe Python Version: 3.7.6 Here is my code for sending an email for the user to confirm registration class CreateUserView(CreateAPIView): queryset = get_user_model() permission_classes = [AllowAny, ] serializer_class = UserSignUpSerializer def post(self, request): serializer = UserSignUpSerializer(data= request.data) data = {} if(serializer.is_valid()): account = serializer.save() data['response'] = "Successfully Registered A New User!" data['response'] = serializer.data user = MyUser.objects.get(email= serializer.data['email']) token = RefreshToken.for_user(user).access_token data['token'] = token #send email to the user upon registering #Note: that we used the function right away, because it is a staticmethod current_site = get_current_site(request).domain relativeLink = reverse("email-verify") #reverse gives us the path, when we give it the name attribute of the url absolute_url = "http://" + current_site + relativeLink + "?token = " + str(token) email_body = "Hi" + user.first_name + "\n" + "Please verify your email: \n" + absolute_url email_data … -
Best way to do complicated sitemaps in Django?
I have pretty complicated URLs for a Django website which are location-specific (by city and country) and based on detail pages (both static and dynamic). Is there a good package do collect all these pages? I probably have 1 million plus pages. How should I create this sitemap? Willing to spend some money too if there is product to do this. -
How to order a filtered django query set by a decimal field
I am trying to sort my query set by a "ranking value" which I have as a decimal field in my django model, however it seems the "order_by" function doesn't seem to work? my query set is always the same, with no ordering. I have tried the google but come up short, am i missing something here? Thanks in advance. -
Django - suing font awersome in unicode form
I want to use font awersome in my project in the way, that user can choose which icon he wants. I found django-fontawesome-5 but there is one problem - there is no access to icon's unicode and I need it for one javascript component (html doesn't work there, and unicode does). I was looking all over the internet, but I coundn't find anything that would allow me to add font-awersome icons, with their unicodes somhow stored. My question is do you know how to get this feature? -
Django upload fils - how to compress before saving to S3 Bucket?
Completely lost on how to compress my images before uploading them to an S3 bucket. I tried adding something like this to my save() method: def save(self, *args, **kwargs): # Opening the uploaded image (if it was uploaded) if self.receipt: im = Image.open(self.receipt) output = BytesIO() # Resize/modify the image im = im.convert('RGB') # after modifications, save it to the output im.save(output, format='JPEG', quality=80) output.seek(0) # change the imagefield value to be the newley modifed image value self.receipt = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.receipt.name.split('.')[0], 'image/jpeg', os.sys.getsizeof(output), None) super(Expense, self). Not a big fan of this approach as the save method is run whenever an Expense instance is updated/created. So if a receipt (the image file) is attached, and I update any other field on the instance, another image file will be added to my S3 bucket. I tried adding if self.receipt and self.pk is None so the save() method only runs on new instances - however, I also want to compress files if they are added to an existing Expense instance. I hear a lot of talk about lambda functions to do the compression on the fly, but can't find any decent guides on how to set it up. I'm … -
How to remove plus sign in Django Admin many to many field?
many to many field How to remove add and edit button on Django Admin in many-to-many fields? -
Saving custom Signup form in django-allauth
I have problems with saving my custom signup form using django-allauth. The form displays correctly on the page. When I click the "register" button, a POST request is sent which does not save anything to the database. The save() method is not called on the form. models.py: import uuid from django.contrib.auth import password_validation from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager from edu.models import Course, Group class User(AbstractBaseUser, PermissionsMixin): MODERATION_STATUS_SIGNUP = 'signup' MODERATION_STATUS_ON_REVIEW = 'on_review' MODERATION_STATUS_REJECTED = 'rejected' MODERATION_STATUS_APPROVED = 'approved' MODERATION_STATUSES = [ (MODERATION_STATUS_SIGNUP, 'В процессе регистрации'), (MODERATION_STATUS_ON_REVIEW, 'На рассмотрении'), (MODERATION_STATUS_REJECTED, 'Отклонен'), (MODERATION_STATUS_APPROVED, 'Подтвержден'), ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) secret_hash = models.UUIDField('хэш', default=uuid.uuid4, blank=True, editable=False) email = models.EmailField('email', unique=True) first_name = models.CharField('имя', max_length=150, blank=False) middle_name = models.CharField('отчество', max_length=150, blank=False) last_name = models.CharField('фамилия', max_length=150, blank=False) is_student = models.BooleanField('курсант', default=False) is_elder = models.BooleanField('старшина', default=False) is_ct = models.BooleanField('классный руководитель', default=False) is_hc = models.BooleanField('воспитатель', default=False) is_watch = models.BooleanField('работник вахты', default=False) is_staff = models.BooleanField('работник института', default=False) is_admin = models.BooleanField('администратор', default=False) is_active = models.BooleanField('активный пользователь', default=False) moderation_status = models.CharField( 'статус аккаунта', max_length=32, choices=MODERATION_STATUSES, default=MODERATION_STATUS_SIGNUP, ) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) last_login = … -
Looping issue in Django Template
enter image description here As you can see in the above picture {{forloop.counter}} is working just below the loop but not at Quiz{{forloop.counter}} Is there any specific reason? How can i solve it?