Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password hashing error in Django 3.1.4 - hashers.py
Today when I started my Django project I got error: 'str' object has no attribute 'decode' After research I figured out that it is problem in hashers.py file in django.contrib.auth library. Somehow it stopped working I am not sure if it is after Django update or anything else. This error appears when app is registering new User or when i try to Login existing User. My code to login user looks like this: from django.contrib.auth import authenticate user = authenticate(username=email, password=password) code to register user like this: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], phone=validated_data.get('phone', None) ) also here is my User Model class: class User(AbstractUser): email = models.EmailField(_('email'), unique=True) username = models.CharField(_('username'), max_length=255, blank=True) phone = PhoneField(_('phone'), blank=True) status = models.IntegerField(_('status'), default=11) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: # db_table = 'label_user' verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, … -
Connecting Django web interfaces with Python
I am trying to connect a button on my web interface to a program running behind Python. I feel it sounds weird so I'm just going to give a scenario for better visualisation of the problem. When a submit button is clicked on the web application, it will call a function running behind a python program on the back end to process the submitted information (encryption/converting the data into another format) then store it in a database or file server. How do I code it on Django as well as in Python? -
Django and AWS S3: Storing and securing private files
I have a Django app that will invoke an API call (a Python function) to create a folder with a private S3 bucket. To invoke the function, a user will have to be logged in first. The S3 bucket will look like this: s3://somebucket/user1 s3://somebucket/user2 and so on API call: https://somedomain.com/createfolder/user1 I don't want to allow user2 to call the API by substituting the user1 string with his username. Assuming I can secure this API call, my Python function will then just go ahead and create a folder with the username given to it. user1 will also have the ability to download only his/her files. users can log in to my app via OAuth2 or username/password. The questions: a. How do I secure my API so that user2 cannot commit actions on user1? b. Similarly, how do I create pre-signed URLs pointing to user1's file (a specific file, which could be a zipped form of a folder? My research: I have heard of JWT and pre-signed URLs, but I'm having difficulties in understanding how to practically implement them in Django. -
Why we add templates path in DIRS in django?
I am confused here to find the proper answer why we add templates in DIRS in settings.py like below: TEMPLATES =[ .... 'DIRS': [os.path.join(BASE_DIR,'templates')], .... ] I have checked that if I don't add templates in DIRS then the tempates and leave it empty then templates is also working. Can anyone please explain what's the difference? Many Thanks -
Run Python service and calculation code in different venv
I need to run Django service on Python 3.8 and some calculation code on Python 3.5 inside a Docker container. How to achieve that? I am thinking: Install miniconda of Python 3.8 to path /usr/miniconda Install anaconda of Python 3.5 to path /usr/anaconda Start Django service with /usr/miniconda/bin/python For each incoming request, use os.system("/usr/anaconda/bin/python calculation.py") to calculate My questions are: I need pip install packages for each code / module. For example, Django, djangorestframework for Django service, numpy and pandas for calculation.py. How to install them separately in different venv in one Docker container. I can use Python 3.8 as the base, and Python 3.5 as the venv. Will the os.system("/usr/anaconda/bin/python calculation.py") execute calculation.py in the Python 3.5 with the venv. In another word, will it be executed in the context of all packages needed, no more no less? How to pass the parameters needed by the calculation.py and get the result back? Thanks! -
Reading only x amount of bytes from a binary file
def streamView(request): # zip_path = './pages/data.zip' zip_path = './pages/data/test.txt' start_index = 0 end_index = 50 with open(zip_path, 'rb', 50) as fin: fin.seek(start_index) data = fin.read(end_index - start_index) response = HttpResponse(fin, content_type="application/zip") response["Content-Disposition"] = f"attachment; filename={zip_path}" return response So I'm using the above code to read just the first 50 bits of a file and return them. However, this just returns the entire file to the user. Ideally, I would like to send start and end parameters to this function, and then just read between those two points, and send that data. How can I acheive this? -
Django | search for same values in specific table field & add/subtract depending on another field
I'm just a bit lost right now programming my first Django app. I want to create something like a portfolio overview for stock market investments. So every time I add an order to my app overview statistics etc. change. Right now I have my order table, that contains all the orders that are made. Orders should have all the information that are needed for further analyses. This the the model: class Order(models.Model): name = models.CharField(max_length=100) ko_identifier = models.BooleanField() order_price = models.FloatField() quantity = models.FloatField() order_value = models.FloatField() order_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0, null=True) order_commission = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) stock_exchange_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) courtage_fee = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) own_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) transaction_fee = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) transaction_fee_sum = models.FloatField() order_date = models.DateTimeField('order date') #order_date = models.DateTimeField(auto_add_now=true) order_wkn = models.CharField(max_length=6) order_isin = models.CharField(max_length=12) order_direction = models.ForeignKey(OrderDirection, null=True, on_delete= models.SET_NULL) order_place = models.ForeignKey(OrderPlace, null=True, on_delete= models.SET_NULL) and here you find a simplyfied import file: later of course the table will contain hundreds / thousands of entries. where I have difficulties: I need to create at least two views on this table Current Portfolio finished "trades" so somethink like this for the current portfolio: and somethink like this for sold positions: so how: can I loop through the table and display all the … -
Table Search bar using django
How can I display search bar for my table whose data is being taken from the database. I have tried the following code but my search bar is not displaying on my webpage. Can anyone please guide me with this? My codes are: index.html <table id="dtBasicExample" class="table table-striped small "> search.js: $(document).ready(function () { $('#dtBasicExample').DataTable(); $('.dataTables_length').addClass('bs-select'); }); search.css table.dataTable thead .sorting:after, table.dataTable thead .sorting:before, table.dataTable thead .sorting_asc:after, table.dataTable thead .sorting_asc:before, table.dataTable thead .sorting_asc_disabled:after, table.dataTable thead .sorting_asc_disabled:before, table.dataTable thead .sorting_desc:after, table.dataTable thead .sorting_desc:before, table.dataTable thead .sorting_desc_disabled:after, table.dataTable thead .sorting_desc_disabled:before { bottom: .5em; } -
Why postgresql tables are in djano are empty
I have created Django project and also i have used Postgresql as database. I have user dockercompose file and created a user with python manage.py create superuser command although I can login into panel admin with this user but when I check the auth_user table in docker shell this table is empty then I decided to create another table as a table test it has created in database I can insert data into this table but this tale is empty too. How can I fix this problem? -
Unable to access django API
I have the following settings.py.I only have token authentication REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), } views.py class UserView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self,request,*args,**kwargs): print(request.user) When I try to access a particular url,I am getting the following error HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } I have tried removing IsAuthenticated,then it works but the user is anonymoususer.How do I fix this? I want to access the current logged in user details -
Slug in different language not working Django even with allow_unicode=True
I'm trying to make an automatic slug using the slugify in django.utils.text. The following are my code: # models.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(allow_unicode=True) body = models.TextField() date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.title # article_create.html {% extends 'base.html' %} {% block content %} <div class="create-article"> <h2>Awesome New Article </h2> <form class='site-form' action="{% url 'articles:article_create' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="create"> </form> </div> {% endblock %} # html template - article_lists.html ... <a href="{% url 'articles:article_details' article.slug %}"></a> ... I used the allowed_unicode=True in order to allow different languages to be used, but the following error comes up when I type in Korean in the title in the form: The first underlined is the title of the article that I'm trying to post, and the second underline is the Django backend checking the slug, but I see that it doesn't recognize the Korean letters... I did what all the other similar StackOverflow, including putting the allow_unicode=True, but it's not working. … -
Getting Posts from Instagram in Python Django
I am making a Django Project in which I need to download images from all the instagram posts of an account and save it in a model and once daily check for new post. Can someone show me how can I extract all the posts from instagram and also download the images and save them in a model. Right now my models is : class ImageModel(models.Model): img = models.ImageField(upload_to='photos/') class Post(models.Model): title = models.CharField(max_length=100, null=True, blank=True) text = models.TextField(null=True, blank=True) image = models.ForeignKey(ImageModel, on_delete=models.CASCADE) url = models.URLField(unique=True) tag = models.CharField(max_length=100, null=True, blank=True) date = models.DateTimeField(default=timezone.now, null=True, blank=True) class Meta: verbose_name_plural = "Publications" def __str__(self): return self.text Thank you. -
how to display Django model based form to the center of page(Crispy form)
I am trying to use the crispy form for Django model-based form. I have referred a few questions already asked but no luck I did not found the way how to centralize the Crispy form. Please find the below code. forms.py class SignUpForm(forms.ModelForm): username = forms.CharField(label=' Enter Username',widget=forms.TextInput(attrs={'placeholder': 'LDAPID/AppleConnect'})) password = forms.CharField(label='Enter Password',widget=forms.PasswordInput(attrs={'placeholder': 'alphanumeric password'})) User._meta.get_field('email')._unique = True email = forms.CharField(label='Enter Email ID', widget=forms.EmailInput(attrs={'placeholder': 'abc@apple.com'})) # username = forms.CharField(label=_("Enter LDAP ID"), widget=MyPasswordInput def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) # If you pass FormHelper constructor a form instance # It builds a default layout with all its fields self.helper = FormHelper(self) self.helper.form_class = 'vertical-form' # You can dynamically adjust your layout self.helper.layout.append(Submit('save', 'save')) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name'] help_texts = { 'username': None,} HTML file: <div class="jumbotron"> <div class="container" align=''> <div class="alert warning"> <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> Please Read the below Instruction Carefully.<br> <strong>Alert!</strong> <br> 1. In <span2> Username</span2> enter your ldap ID and in <span2>Email</span2> field enter apple Email.<br>&nbsp&nbsp 2.Once the Account created user will not have Access to the respective Portal.To get Access please file radar with business justification(User should be part of vendor Company group). </div> <br> <div class="col-md-12 well"> <div … -
django owner permission in detail view
I that there many materials on the subject, i checked many, but i can't find slick and simple way to deal with the problem. This is very frustrating (because the problem is not complicated at all). So this my code in the view class EnrollmentDetail(generic.DetailView): model = Enrollment template_name = 'enrollments/enrollment_detail.html' context_object_name = 'enrollment Simple django generic detail view. I want only the owner of this detail view to has access to it. Everyone else i don't wont go get it, i try to limit their access to it. I think for raising some error in that case, but don't know which one exactly is accurate. I checked some posts on that matter. There is solutions with queryset, super, decoratos etc. but they seem chaotic and not working form me. Thanks for help! -
Creating new user with random password in django
I have been working on a project where admin registers users to use the website. say in my case admin registers teachers and students of the school. I need some way to create random password for every new user and a email will be sent using registered email with the password. I am using custom user model. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have email Id") if not username: raise ValueError("Users must have an username") user = self.model(email=self.normalize_email(email), username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user(email=self.normalize_email(email), username=username, password=password) user.role = 'ADM' user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(verbose_name="Email", unique=True) ROLE_CHOICES = [ ('STD', 'STUDENT'), ('THR', 'TEACHER'), ('ADM', 'ADMIN') ] role = models.CharField(max_length=3, choices=ROLE_CHOICES, default='STD') username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_of_birth = models.DateField(null=True) description = models.TextField(null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') 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_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = MyAccountManager() here my register view. @login_required def register(request): if not request.user.is_superuser: return HttpResponse('Unauthorized', status=401) if request.method == … -
storing a QR Code png image in a django database
I'm trying to store a QR Code image in a .png file in a django database model. It is created using the qrcode python module (pip install qrcode). However, my problem is I get an error when trying to migrate the models, getting an error saying: ValueError: Cannot serialize: <qrcode.image.pil.PilImage object at 0x7f89c1f9b760> I read the django documentation and it mentioned something about a migration serializer but wasn't very helpful with the implementation. Here is my code as it stands: from qrcode import make # models.py def create_qr_code(id): # this line creates the qr code image which in production will be a url return make(id) class PDFDoc(models.Model): id = models.IntegerField(primary_key=True) account_id = models.ForeignKey(Account, on_delete=models.CASCADE) name = models.CharField(max_length=15, default="", blank=True) num_requests = models.IntegerField() document = models.FileField(upload_to="documents/") qr_code = create_qr_code(id) qr_code = models.ImageField(blank=False, upload_to="pdf-qrcodes/", default=qr_code) def __str__(self): return f"Name: {self.name}\nNumber of requests: {self.num_requests}\n" Any help would be greatly appreciated :) -
In permissions.py "has_object_permission" obj's ManyToManyField is being None
Project Model has relation with ManyToManyField to User Model. class Project(models.Model): user = models.ManyToManyField(User, related_name="projects") Serializing the data in serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id"] class ProjectSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Project fields = [... "user" ...] depth = 1 There is no problem. I nest the ManyToManyField User field into the Projects. BUT in permissions.py, when I try to reach the user field like below. def has_object_permission(self, request, view, obj): print(obj.user) It returns ...User.None and I am not sure what is the reason. The way I serialize the User field in ProjectSerializer() is wrong? By the way I can check on browser that User field is nested. But in terminal I can't reach it trough obj -
Django command: how to schedule properly on Windows Server
coming from Linux I have to build a Django application on Windows Server. Everything works fine, but I have a Django command that needs to be run every hour. In Linux I would create a cronjob. I wrote a batch file that activates the virtual env and runs the django command, scheduled it with windows, but the command jobs fails, despite task scheduler says it executed properly. What is simple on Linux on Windows it seems to be rocket science... I feel that task scheduler / batch file approach isn't the right way to do that. Is there a more pythonesque way to run a django command on windows server every hour? thanx in advance, Jan -
DRF Token Authentication - not able to retrieve Token
I'm trying to retrieve a token for the user using the following request through Postman. http://127.0.0.1:8000/api-token-auth/ JSON Body - { "username": "user1", "password": "Test#1234" } The following is the error response - { "detail": "CSRF Failed: CSRF token missing or incorrect." } I've checked the instructions provided in the official DRF Authentication document as well as various other question posts and implemented the following code. settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', .... ] AUTH_USER_MODEL = 'users.CustomUser' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } signals.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) urls.py urlpatterns= [ path('admin/', admin.site.urls), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path("api-token-auth/", authtoken_views.obtain_auth_token, name="api-token-auth"), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), ] Have I missed something? -
Error when trying to update the group that a user belongs to
I am developing an application that has different users, for that I am using the groups, but I am having a problem and that is that when a user is updated to belong to another different group, it is added and another and the one that has is to preserve: @receiver(post_save, sender=User) def set_role_user(sender, instance, *args, **kwargs): if instance.role: if instance.role == 'administrador': group = Group.objects.get(name='administradores') instance.groups.add(group) else: group = Group.objects.get(name='desarrolladores') instance.groups.add(group) It is preserved because I am adding the group, so what I tried was only to update: @receiver(post_save, sender=User) def set_role_user(sender, instance, *args, **kwargs): if instance.role: if instance.role == 'administrador': group = Group.objects.get(name='administradores') instance.groups.update(group) else: group = Group.objects.get(name='desarrolladores') instance.groups.update(group) But doing this generates an error which says that update () takes 1 positional argument but 2 were given, which I don't understand because when displaying the instance.role by console, it only shows me one. -
vs code is showing this error, have installed django 2.1 in the system but still it is showing this error , can anyone suggest how to solve
Import "django.db" could not be resolved from source Pylance from django.db import models- while importing models module above said error message was showing. -
Missing "dnspython" error for django + gninx + gunicorn app, even after installing it to the correct virtual environment
Getting the following Error: The "dnspython" module must be installed to use mongodb+srv:// URIs Exception location: ../python3.7/site-packages/pymongo/uri_parser.py, line 428, in parse_uri When trying to use pymongo with django app. I tried to install dnspython with pip3 to the correct virtual environment but still got the error. I also tried to re-start gninx. -
how to create django form from dictionary
I have dictionary like this p_dic = { 'Frequency': ['8kHz', '9kHz', '3.6kHz', '2.8kHz', '1.2kHz', ], 'Voltage - Input (Max)': ['-', '15V p-p', '80V p-p', '30V p-p'], 'Type': ['Feedback', 'Standard'], 'Impedance': ['500 Ohms', '400 Ohms', '350 Ohms', ], 'Capacitance @ Frequency': [ '25000pF @ 1kHz', '93000pF @ 1kHz'], } I want to create form where name will be key and options will be values as given in the list, how to do so. -
django: Auto populate m2m field of a model
I have a category kind of model (called Tag): class Tag(models.Model): name = models.CharField(...) slug = models.SlugField(unique=True) #... Used as m2m field in another model: class Order(models.Model): user = models.ForeignKey(...) type = models.CharField(...) tag = models.ManyToManyField(Tag, blank=True) Now, suppose an order is created and program wants to assign some tags to it automatically. Say, program wants to add Order.type to itsOrder.tag list. (Suppose Order.type happens to be same as a valid Tag.name) I tried Order's post_save to no luck: def order_post_save_reciever(sender, instance, *args, **kwargs): #... instance.tag.add(Tag.objects.filter(name=instance.type)) instance.save() Apparently, I have to use signals, but I don't know how. Your help is much appreciated. -
How to load django installed apps staticfiles in production?
This is probably a really simple adjustment that I've lost enough time searching for a solution. I built a project using Django + React and deployed it on Heroku. Everything works perfectly excepts for the static files from the INSTALLED_APPS: /admin and de Django Rest Framework views. In these urls, django throws a 500 server error. django.contrib.staticfiles is in my INSTALLED_APPS. I'm using whitenoise. My allowed hosts are correct. My STATIC_ROOT path is also correct. STATIC_URL = "/static/" STATIC_ROOT = os.path.join(FRONTEND_DIR, "build", "static") I've tried to add an empty directory in the STATICFILES_DIRS but it didn't work. What am I missing? Why django isn't collecting the static files from the INSTALLED_APPS?