Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a parent user and a child user in Django?
We are building a free education app in Django. I have noticed that if I am logged in as a "superuser" I am able to "switch user" inside the admin app to any of our staff. This education app will have "Parents" who can "Add Child" users. The parents should be able to "switch user" to any of their children. How do we implement this feature on our main app instead of just within the admin. -
Python manage.py runserver is throwing error after Ubuntu upgrade to 20.0
I am getting this error in all the Django projects on my system. I've updated from Ubuntu 18.04 to 20.0 (Focal Fossa). Since then I am getting these errors. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/distutils/__init__.py", line 17, in <module> real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY)) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 245, in load_module return load_package(name, filename) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 217, in load_package return _load(spec) File "<frozen importlib._bootstrap>", line 683, in _load AttributeError: 'NoneType' object has no attribute 'name' -
How to get the uploaded (generated) file name in django
models.py class client_users(AbstractBaseUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=150) birthday = models.DateField() phone = models.CharField(max_length=15) profile_image = models.ImageField( upload_to='images/', default="noimage.png") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email views.py def profile(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): try: form.save() except: pass print(client_users.profile_image.field.pre_save) return HttpResponseRedirect('/profile') else: form = UploadFileForm() return render(request, 'profile.html', {'form': form}) This is a picture of the saved files with a code generated by django, because he found an image with the same name Since django generated the code after the name of the picture, i want to get the full file name after the upload so i can update my database, request.FILES['profile_image'] doesn't return the generated value, it returns the name of the file on the upload. Any help, please ? -
Accessing cookie from another sub-domain within my domain
I have two django applications that are deployed at two different sub-domains, for example: data.mysite.com i.mysite.com Both sites use the same django authentication framework and such, setting a cookie called sessionid. I can read the cookie from the current site using: def my_view(request): # suppose this view is within the i.mysite.com application i_session_id = request.COOKIES['sessionid'] data_session_id = ? # how to get this? But then how could I grab the cookies from the -
Django modelform custom widget is_multipart not working
In my modelform, I have used a custom widget. The problem is for some reason the is_multipart returns False, and so I cannot upload the picture class ProjectSetupForm(ModelForm): class Meta: model = Project fields = ['name', 'logo','picture'] widgets = { 'picture': PictureWidget, 'logo': PictureWidget, } def __init__(self, *args, **kwargs): self.fields['logo'].widget.attrs['class'] = 'file_upload blocked' self.fields['picture'].widget.attrs['class'] = 'file_upload blocked' class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None, **kwargs): if value: html = Template("""<img src="$media$link" height=100px width=auto/> <input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(media=settings.MEDIA_URL, link=value, name=name)) else: html = Template("""<input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(name=name)) # views.py: class AddProject(View): template_name = 'project.html' model = Project def get(self, request, *args, **kwargs): ... context['form'] = ProjectSetupForm() ... return render(request, self.template_name, context) def post(self, request, *args, **kwargs): ... project_form = ProjectSetupForm(request.POST if any(request.POST) else None, request.FILES or None) if project_form.is_valid() and address_form.is_valid(): ... address_instance = address_form.save() project_instance = project_form.save(commit = False) project_instance.address = address_instance project_instance.save() else: errors = {} if project_form.errors: project_form_errors = project_form.errors errors.update( {'project_form': project_form_errors} ) if address_form.errors: address_form_errors = address_form.errors errors.update( {'address_form': address_form_errors} ) context = {} context['errors'] = errors return render(request, self.template_name, context) # In template: {% if form.is_multipart %} <form action="" … -
Changing a Curl method to a django/DRF view method
I am trying to implement an API but it has only options for cURL, PHP and nodejs, but i feel its possible for me to use python to make the request as the endpoint has been given This is the cURL code, I am hoping to get a way to do it in Django Rest Framework or Django as i am using it to develop and endpoint. curl --location --request GET 'https://api.flutterwave.com/v3/transactions/123456/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {{SECRET_KEY}}' Thanks in advance. -
Django: After Successful Payment Via PayPal how to redirect user to order completed page
I am setting a PayPal payment for my E-commerce project and everything is working fine except that after the payment is executed and the PayPal windows is closed, the website page remains open and the items remain in the cart. I have set the stripe payment to redirect to a page called "order completed" with some order reference code, which I am trying to implement to PayPal payment option. Here is the views.html: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() # assign the payment to order order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") # Email when order is made template = render_to_string("payment_confirmation_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'order': order}) msg = EmailMessage('Thanks for Purchasing', template, settings.EMAIL_HOST_USER, [request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send return render(request, "order_completed.html", {'order': order}) class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") … -
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 …