Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update with signals in django
I would like when i make any changes on client, to be modified on this table too. class ClientsBalance(models.Model): company = models.ForeignKey(Company, on_delete=models.PROTECT) exercice = models.ForeignKey(Exercice, on_delete=models.PROTECT) client = models.OneToOneField('Client', on_delete=models.CASCADE, related_name='Client') def create_client(sender, **kwargs): if kwargs['created']: client = ClientsBalance.objects.create(client=kwargs['instance'], company=kwargs['instance'].company, exercice=kwargs['instance'].exercice) post_save.connect(create_client, sender=Client) -
dj-rest-auth limit social sign up to a specific email address domain
I'm getting started with dj-rest-auth and I have an app which allows user to only sign in via google. However, I want users to only be able to access my service with a specific google apps email domain. I'm using dj-rest-auth in conjunction with django-allauth. This is what I tried: I created allauth adapters like this: class CustomAccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return False # No email/password signups allowed class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request, socialaccount): u = socialaccount.user return u.email.split("@")[1] == "mydomain.com" and in my settings I have ACCOUNT_ADAPTER = "users.adapters.CustomAccountAdapter" SOCIALACCOUNT_ADAPTER = "users.adapters.CustomSocialAccountAdapter" With this solution, if the user tries to sign in with a valid email, everything works, whereas if they use a non-allowed email domain, I get this error in my console: Traceback (most recent call last): File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/rest_framework/views.py", line … -
partial matching in django-filter
suppose, i'v an username (abcde). now if i search for abcd or bcde it should return that object which username is abcde. How to do that? #filters.py from .models import User import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username'] #views.py @api_view(['GET']) @permission_classes((IsAuthenticated,)) def search(request): queryset = User.objects.all() filterset = UserFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs serializer = SimpleUserSerializer(queryset, many=True) return Response(serializer.data) -
How to activate virtual environment
I installed Django not knowing I was to create a virtual environment before installing it.(I don't know if I am making sense) but now I cant activate my virtual environment? is there something that I can do to rectify this -
Is Django's Caching Framework per user or across all user's
I have read through Django's caching framework documentation (https://docs.djangoproject.com/en/3.1/topics/cache/#), and want to know if the caching is per user or for all user's. For example, User A: Generates this link with parameters --> https://example.com/?parameters=hello User A: Re-opens the previous link and experiences a fast reload. User B: Opens the link User A generated, but does not experience a fast reload time. No where in the documentation does it state it's per user, but from testing it seems to be that way. I just want to know if this is the intended purpose behind the caching framework? If, so is there a way to cache the requests for all user's? -
How to redirect to different site, and pass auth credentials using Django
Is it possible to redirect to a different URL with authentication using django? For example, with python requests, I can log into a site by passing credentials like: UN= "myuser" PWD = "mypassword" loginUrl = "https://example.com/" client = requests.session() header_data = {'referer' : loginUrl, 'User-Agent' : 'Custom'} r = client.post(loginURL, auth=(UN, PWD), headers = header_data) But If I want a button on a django powered page to redirect to another site, and login into it automatically, how can this be done? I tried using redirect, which works to redirect obviously, but I can't seem to figure out how to pass auth crendtials using a django view. I also tried redirect(user:password@example.com) which gives an error that this feature is depreciated on chrome, and I cannot pass credentials this way. Any help is appreciated! -
Is Pinax still being maintained?
This question is basically an update for this one. I recently discovered the django pinax ecosystem but I am not sure if this is currently being maintained and works for recent versions of Django. Documentation is not clear to me on this. Since this is a collection of different apps it may happen that some of them are more maintained than others, so the question would be if most of the apps listed here and the pinax-starter-projects are up to date with current django/python versions in 2021 (django 2.2/3, python 3+) -
What am I Doing Wrong? Trying to Deploy Django Application to Heroku and keep getting error code H10
I apologize this is my first time posting on here and I am not familiar with the formatting. Can someone please help me identify what I am doing wrong here? ''' 2021-03-17T15:47:40.537869+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=a917acfe-3ff8-4d9b-8ce8-62df15f56b58 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T15:47:41.230050+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=phil.herokuapp.com request_id=8cb225e2-c677-48d1-936e-1a5ed8c29904 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' '''2021-03-17T16:33:48.040804+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=69e8e429-e064-42dc-be4d-2c4c7db5ce47 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T16:33:48.592375+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=phil.herokuapp.com request_id=c26a368c-af03-4604-93a0-13fd5c6be104 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T16:44:02.920835+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=a3444390-698d-4c77-8998-23bb6a75b04b fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' -
Django - Pandas - add_format: cell get format but only applied if enter keys is pressed
I have a django function in the backend that collect some numbers from a database using a for loop, set the format for the workbook with workbook.add_format and write to a spreadsheet that get then downloaded. This is the core of my code: native_format = workbook.add_format({'num_format': '#,##0.00;[Red]-#,##0.00'}) for index, wp_number in enumerate(df['WP no.']): # workpackets' row index start at row=1 row = index + 1 worksheet.write_number(row, 5, df['Invoice total'][index], formats[-1]) worksheet.write_number(row, 6, df['Against this WP'][index], native_format) the format is correctly applied to the cells but when i download and open the spreadsheet the following happens: As you can see the format is applied as custom and not number. Only if I select a cell and press enter the format is recognised and applied: I can make the format to automatically apply to all cell? Thank you for your help -
default groups& permissions not working for abstract base user with permissions mixin in django
I am working with AbstractBase user. I have created users and groups. After I assign group to user, if I login with that user , the user has access to the complete admin site with all the CRUD operations. I have a created a product group with add-delete-edit-view permissions(default) and assigned a user to it. But when this user logins to the admin site, he has access to all the other items of the site as well. How do I make sure the logged in user can access only the items from assigned groups /permissions??? #managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) #models.py from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import … -
What is _() in a Python dictionary?
This might be a dumb question but I recently stumbled upon this code in Django Rest Framework, couldn't find out what is the _() inside that dictionary... class SlugField(CharField): default_error_messages = { 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'), 'invalid_unicode': _('Enter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.') } -
link to user who posted an ad displays current users profile. django
I am building a web application for finding tutors where tutors can post a job. In the post, a link to user whose profile should be displayed is given. I tried doing that on my own but ended up showing the current user profile (profile of the user who is logged in currently). Please teach how to show the profile of the user who posted the job. View for profile: def profile(request): if request.method == 'POST': p_form = UpdateProfile(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.instance.user = request.user p_form.save() return redirect('profile') else: p_form = UpdateProfile(instance=request.user.profile) context = { 'p_form': p_form, } return render(request,'profile.html',context) Note: the profile view also has model form to update Urls.py: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post/<int:id>', views.post, name='post'), path('post_delete/<int:pk>', views.post_delete, name='post_delete') ] models.py and form for profile : class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) image= models.ImageField(default = 'default.jpg',upload_to='profile_pics') bio=models.CharField(default = 'no bio',max_length=350) def __str__ (self): return f'{self.user.username} Profile' class UpdateProfile(forms.ModelForm): class Meta: model = Profile fields =['image','bio',] def clean(self): super(UpdateProfile, self).clean() return self.cleaned_data Template profile.html: {% extends "base_generic.html" %} {% load crispy_forms_tags %} {% block content %} <style> #hide { display: none; width: 100%; padding: 50px … -
Issues when converting image binary data from PostgreSQL using Python to string format
I am trying to come up with a solution to retrieve binary data of an image saved as byteatype from PostgreSQL, and convert it to string format so that <img src>can read it. It was written in the Python based framework Django. Here is the code from models.py class Images(models.Model): image_code = models.BinaryField() caption = models.CharField(max_length=100,default='IMG_CAPTION') In my views.py,what I have is the following: def imageRetrieving(request): store_length = len(Images.objects.all()) image_shown = Images.objects.all()[store_length-1] print(image_shown.image_code.decode('ascii')) context = { 'img_src':str(image_shown.image_code) } return render(request,'imgstore/formTesting.html',context) When I run, I always receive an error message 'memoryview' object has no attribute 'decode' in the browser. I am looking for some guidance here. Thank you. -
Django MYSQL created_date and mod_date with specific SQL
I'm relatively new to Django, and am trying to have the following SQL statements for two fields that appear in all of my models: sys_created_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, sys_mod_date datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, currently the model fields look like this: sys_created_date = models.DateTimeField(auto_now_add=True,blank=False,null=False) sys_mod_date = models.DateTimeField(auto_now=True) However, when I inspect the MYSQL database directly the fields look like this: `sys_created_date` datetime(6) NOT NULL, `sys_mod_date` datetime(6) NOT NULL, What would be the best (most Django appropriate) way to alter these MYSQL columns so that the constraints listed above are contained directly within the MYSQL database? Thanks for the help. -
virtualenv is installed in my machine but still getting "not recognised as internal or external command "
I have installed virtualenv and virtualenvwrapper-win directories in my machine using commands pip install virtualenv and virtualenvwrapper-win And also when I run pip show virtualenv It is displaying everything about it .But when I try to run mkvirtualenv my_project It's showing me this error 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file. Idk why ... please help me out . -
Is it possible to pass a variable variable when including Django template
I want to use a Django template to create links to unchosen releases in a dropdown button. The created links are defined like this: {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{release}}&out_release= {{out_release}}">{{release}}</a> {% endif %} {% endfor %} and {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{in_release}}&out_release={{release}}">{{release}}</a> {% endif %} {% endfor %} Would it be possible to create dropdown-link.html file containing: {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{in_release_query}}&out_release={{out_release_query}}">{{release}}</a> {% endif %} {% endfor %} and to invoke it in the actual rendered template like this, sort of creating variable variables: {% include "release-dropdown.html" with in_release_query=release out_release_query=out_release %} ... {% include "release-dropdown.html" with in_release_query=in_release out_release_query=release %} I know this exact approach is not possible here. Would you recommend an alternative? -
Is it possible to deploy Django Mayan-eds to Heroku?
I am not an experienced developer but I recently was able to deploy some small Django projects to Heroku free hosting service. Now, I am investigating mayan-edms for a project I have, that seems to provide many features I would need, but it seems a bit complicated to install in local computer and probably even more to deploy to the web. Given that I am more familiar with the heroku deployment process for django apps (than with the use of docker style deployments) my question is: Is it possible to deploy a django Mayan-edms system to Heroku? If so, is there a tutorial, how-to guide about this? -
Django: can't change language
I think the solution should be quite simple. But I can't understand it. If nothing works, I'll do it through context processors. settings.py: LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ('ru', 'Русский'), ('uk', 'Українська') ] TIME_ZONE = 'UTC' USE_I18N = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] urls.py: urlpatterns = [ path('', index, name='index'), path('set_lang/<lang>', set_lang, name='set_lang') ] and my views.py: def index(request): print('language after changing ', translation.get_language()) print(request.session.get(LANGUAGE_SESSION_KEY)) return render(request, 'project/index.html', locals()) def set_lang(request, lang): print('language before ', translation.get_language()) translation.activate(lang) print('language after activating', translation.get_language()) request.session[translation.LANGUAGE_SESSION_KEY] = lang return HttpResponseRedirect(request.META.get('HTTP_REFERER', 'index')) Every time I refer to this link(http://127.0.0.1:8000/set_lang/en)... The language never changes and always remains uk Console trace(prints) -
Using Websocket in Django View Not Working
Problem Summary I am sending data to a front-end (React component) using Django and web-sockets. When I run the app and send the data from my console everything works. When I use a button on the front-end to trigger a Django view that runs the same function, it does not work and generates a confusing error message. I want to be able to click a front-end button which begins sending the data to the websocket. I am new to Django, websockets and React and so respectfully ask you to be patient. Overview Django back-end and React front-end connected using Django Channels (web-sockets). User clicks button on front-end, which does fetch() on Django REST API end-point. [NOT WORKING] The above endpoint's view begins sending data through the web-socket. Front-end is updated with this value. Short Error Description The error Traceback is long, so it is included at the end of this post. It begins with: Internal Server Error: /api/run-create And ends with: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host What I've Tried Sending Data Outside The Django View The function below sends data to the web-socket. Works perfectly when I run it in my console … -
Error accediendo a Sendinblue (Hosting: Pythonanywhere)
¡Hola! He desplegado recientemente en Pythonanywhere un sitio web desarrollado en Django. La web esta integrada con Sendinblue, revise la Whitelisted y vi que está permitida la API para las cuentas free en Pythonanywhere. Les solicito ayuda porque todas las consultas a la API me dan errores como el que le muestro al final, en cambio fuera del hosting funciona todo bien. Les agradecería si pudieran indicarme que debo hacer para poder acceder a la API de Sendinblue. Muchas Gracias a todos. Saludos Error de las consultas: 2021-03-17 11:55:19,469: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fb4274735d0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/contacts?limit=5&offset=0 -
Creating a task (child) with restricted pool of projects (parent)
I'm trying to create a TODO app where you can create tasks and projects. Projects are used for collecting tasks. Tasks can be standalone tasks or a part of a project. I want user to be restricted when he creates a task so he can assign it only to projects which he created or he's a part of (participant1 field). For some reason my current code isn't really using custom perform_create I created. It even doesn't seems to execute code in else of perform_create models.py class Project(models.Model): title = models.CharField(max_length=100) project_owner = models.ForeignKey(User, on_delete=models.CASCADE ) created = models.DateTimeField(auto_now_add=True) completed = models.DateTimeField(blank=True, null=True) participant1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="participant", null=True, blank=True) deleted = models.BooleanField(default=False) class Task(models.Model): title = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) scheduled = models.DateTimeField(blank=True, null=True) completed = models.DateTimeField(blank=True, null=True) importance = models.BooleanField(default=False) task_owner = models.ForeignKey(User, on_delete=models.CASCADE) project_id = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="tasks" , null=True, blank=True) deleted = models.BooleanField(default=False) serializers.py class TaskSerializer(serializers.ModelSerializer): project_id = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all(), required=False) task_owner = serializers.ReadOnlyField(source='task_owner.username') class Meta: model = Task fields = '__all__' views.py class TaskList(generics.ListCreateAPIView): serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user project = Project.objects.filter(participant1=user).values_list('id', flat=True) return Task.objects.filter(Q(deleted=False) & (Q(completed = None) & Q(task_owner=user)) | Q(deleted=False) & (Q(project_id__in=project) & Q(completed = None))).order_by('-id') def perform_create(self, … -
drf: Search filter in function based views
Is it possible to make search filter in function based views in drf? i'v run the command pip install django-filter and added django_filters in INSTALLED_APP. I tried in class based views and it works fine. Here is my code: #@api_view(['GET']) #@permission_classes((IsAuthenticated,)) class SearchUser(ListAPIView): queryset = User.objects.all() serializer_class = SimpleUserSerializer filterset_fields = ['username'] settings.py: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'], } but i want to do it in function based views. views.py: #from ?? import ?? @api_view(['GET']) @permission_classes((IsAuthenticated,)) def searchUser(request): queryset = User.objects.all() serializer = SimpleUserSerializer(queryset, many=True) # what next??? serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') And i'v another problem. If an object has an username called abcdef and then i search for cdef it should return that object(which username is abcdef). Is it possible in function/class based views? if so, how to do that? -
Integration testing DRF
I'm using Django with DRF as just an API--it doesn't serve any FE assets of any kind. I know the Django testing suite is built on the Python native unittest library and plan on using it for unit testing. When it comes to integration testing, is it sufficient or should something like Behave be used? If unittest is sufficient, should it be used in conjunction with some kind of faker? -
Efficient Multiple Row and Columns Lookup Django
I need an efficient query that can enable lookup on multiple table rows and different columns. I have the below model: class Vahala(models.Model): tourist = models.ForeignKey(User) name = models.CharField(max_length=100) can_visit = models.BooleanField(default=False) can_move_out = models.BooleanField(default=False) I need to confirm if Mr A who is a tourist can visit a location named 'bali' and can also move out of a location named 'cape_verde'. I want to believe the naive approach would be check_a = Vahala.objects.filter(name='bali', can_visit=True, tourist__email='mra@mail.com') check_b = Vahala.objects.filter(name='cape_verde', can_move_out=True, tourist__email='mra@mail.com') check_a and check_b must exists() before Mr A can complete the process. I need an efficient approach. I don't want to keep hitting the database multiple times. Is it possible to confirm the conditions via a single DB hit or at most two if the conditions are much? What am I missing? -
How to custom values for a many to many field in a create view in django
I want to just show published tags in a many to many field ( relation with tag model ) in a CreateView in django. my code for create view --> enter image description here and i want to just show published tags in many to many field. enter image description here