Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: User Login only working with terminal created users
I'm only new to django & this is my first time posting on stack overflow so appologies if I havent done this right. My problem is that when I use my login function, it only seems to work with those created with the createsuperuser command in the terminal. Those created within the website just dont work. The users show within the admin panel and have a password within them. models.py class Trickster_User(AbstractBaseUser, PermissionsMixin): UserID = models.AutoField(primary_key=True) Email = models.EmailField(('Email Address'), unique=True) Username = models.CharField(('Username'),max_length=25, unique=True) FirstName = models.CharField(('First Name'),max_length=25) LastName = models.CharField(('Last Name'),max_length=25) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomUserManager() USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ['Username', 'FirstName', 'LastName'] def __str__(self): return self.FirstName + ' ' + self.LastName views.py def user_login(request): context = {} user = request.user if user.is_authenticated: return redirect('home') if request.method == "POST": form = UserAuthenticationForm(request.POST) if form.is_valid(): Email = request.POST['Email'] password = request.POST['password'] user = authenticate(Email=Email, password=password) if user is not None: login(request, user) return redirect('home') else: form = UserAuthenticationForm() context['user_login'] = form return render(request, 'authentication/login.html', context) forms.py class UserAuthenticationForm(forms.ModelForm): Email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) password = forms.CharField(label='password', widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = Trickster_User fields = ('Email', 'password') def clean(self): Email = self.cleaned_data['Email'] password = self.cleaned_data['password'] if not … -
How to update a field of Django Model Object whenever that particular object is fetched as a part of QuerySet from Database
I have a field called pending_since for a Ticket model. This contains the the difference between the date when the ticket is created ( created_on field ) and the current date. Now, when a single ticket is fetched, then I am able to update this field as below. views.py def pending_days_calculator(date1): current_date = timezone.now() diff = current_date - date1 diff_in_days = diff.total_seconds() / ( 60*60*24) pending_days = round(diff_in_days,2) return pending_days @login_required(login_url=settings.CUSTOM_LOGIN_URL) def ticket_detail(request, ticket_no): ticket = Ticket.objects.get(ticket_no=ticket_no) ticket.pending_since = pending_days_calculator(ticket.created_on) ticket.save() if request.method == 'POST': .....other logic here..... But, when a bunch of Ticket objects are fetched at a time as shown below, is there any way to update this field for each object, other than looping through the queryset. @login_required(login_url=settings.CUSTOM_LOGIN_URL) def common_pool(request): tickets = request.user.ticket_set.exclude(ticket_status='closed').order_by('sla') Ticket model has ForeignKey reference to user model GHDUser models.py for reference class Ticket(models.Model): ticket_no = models.CharField(max_length=10, blank=True) raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE,related_name='raised_ticket', default=1) created_on = models.DateTimeField(default=timezone.now) pending_since = models.FloatField(default=0.0) -
Is there a way to exclude a Django model from Aldjemy model creation?
I have a Django model with a field that is a nested Postgres array class MyModel(models.Model): array_of_arrays = ArrayField( ArrayField( models.CharField(max_length=20), size=3, ), ) Aldjemy doesn't support nested arrays, and Aldjemy's array_type function is throwing RuntimeError("Unsupported array element type") for this field. I don't actually need a SQLAlchemy model for this Django model. Is there a way to exclude a Django model from the Aldjemy model generation process? -
Django Rosetta autoreload new translations bad gateway error
I have a problem with django-rosetta, it works fine but when changing translations it is not applied to the site until restarting the docker. I tried adding these codes: ROSETTA_WSGI_AUTO_RELOAD = True ROSETTA_UWSGI_AUTO_RELOAD = True But after adding this codes when saving rosetta it gives 502 bad gateway error despite saving new translations but it is still not applying new translations to the site until I restart. -
Django websocket cannot connect through https request blocked in railway app
My websocket works fine on localhost. But fails to run when I deploy my project on railway app (which uses https) It shows this error in the console log: first error - ''' (index):382 Mixed Content: The page at 'https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://supreme-key-production.up.railway.app/ws/bangladesh_ott/'. This request has been blocked; this endpoint must be available over WSS. ''' second error - ''' (index):382 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. at window.onload (https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/:382:24) ''' This is in my script : ''' window.onload = function() { const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e) { console.log('onmessage') const data = JSON.parse(e.data); if (data.message) { let html = '<div class="message">'; html += '<p class="messsage_username">' + data.username + '</p>'; html += '<p class="message_message">' + data.message + '</p></div>'; document.querySelector('#chat-messages').innerHTML += html; } else { alert('The message was empty!'); } } chatSocket.onclose = function(e) { console.log('onclose') } // document.querySelector('#chat-message-submit').onclick = function(e) { e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, … -
make an element disappear if the date is greater than 30
I want to make the Countdown Timer element disappear if it is less than 0 or greater than 30 ` {% if data.fin>0 and if data.fin<30 %} <div id="clockdiv"> <div> <span class="days" id="day"></span> <div class="smalltext">Jours</div> </div> <div> <span class="hours" id="hour"></span> <div class="smalltext">Heures</div> </div> <div> <span class="minutes" id="minute"></span> <div class="smalltext">Minutes</div> </div> <div> <span class="seconds" id="second"></span> <div class="smalltext">Seconds</div> </div> </div> {% endif %} ` -
Django Rest Framework trying to update or create a related model but need the related object
I have a profile model and a location can belong to a profile. But a person might not add the location when they create the profile so I would like to update or create the profile if it does not exist, when the user adds it later. I tried doing it through the profile serializer but there is no request data so I cannot create or update a location model object. So I presume I have to do it through the view and here it is: class UpdateProfileView(generics.UpdateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ProfileSerializer name = "update-profile" def get_queryset(self): id = self.kwargs["pk"] return Profile.objects.all().filter(id=id) def update(self, request, *args, **kwargs): street = request.data.get("street") user = User.objects.get(id=request.data.get("user")) city = City.objects.get(id=request.data.get("city")) additional = request.data.get("additional") zip_code = request.data.get("zip") name = user.profile.first_name + '\'s location' user_location = Location.objects.update_or_create(name=name, street=street, additional=additional, city=city, zip=zip_code, profile=?) My question is three fold: Is this the best way to update or create a model object for location? If I create the location this way will the profile still be updated as well or am I missing data I should add? How do I get the profile instance that is for a field (profile=?) I have to fill for location. I … -
Django - allauth: How to keep only the allauth login url
How can I remove the allauth signup URL while keeping the login URL in Django? I am using the allauth package for authentication and I would like to only keep the login URL while removing the rest URLs as i have project that needs only the login. Can anyone provide a code snippet on how to achieve this? I have tried using the url method to exclude the rest urls from my URL patterns, but that also broke the login URL. I was expecting to only remove the signup URL while keeping the login URL accessible through allauth package in Django -
django view filter ManyToMany field to guard view
I have a tag model, with ManyToMany field "parents" to tag model, to itself. There is also "allowed_users" field. I need to guard a view in such a way, that the user won't see any tags in parents field, to which he is not allowed. I try to modify queryset, removing the corresponding tags from parents. But when I change the instance, tag_instance.parents.set(my_new_list) it gets saved automatically so I'm altering the database and changing the real value of the instance. So the general question is "how to guard my view in such a way, that object's ManyToMany field is filtered by custom logic". Another question is "how to set manytomany field without altering database", as this would be a solution to the former one. yes I use DRF -
Running a batch file from Django View
I have a Button in django template to call a .bat file def launchBatchScript(request): import subprocess subprocess.call([r'C:\Projects\Run_Bat.bat']) @echo off "C:\Tools\python.exe" "C:\Projects\samplePY.py" pause it does run the code written in py file (i see it in terminal) but it is not well visualised at frontend. Need Solution -
Why is my flash message style not working properly?
enter image description hereenter image description here I also function the messages function in views, but it still doesn't work properly -
Deploying Django project from GitHub to railway
I'm trying to deploy my Django project from GitHub to the railway and I keep getting a failed error during the build process (Deployment Failed during build process) Have checked for resources to solve this but none seems to be of help, can anyone who can help me with this, please? -
Sending email feature not working when run using Docker. Showing Error : 530, b'5.7.0 Authentication Required. But runs perfectly without docker
I am making a Django App using GraphQl APIs in which I am trying to make an email sending feature for changing and sending user password if they forget while login. This feature is perfectly working when I am running it from my laptop's localhost:8000, but when I pushed it to dockerhub using github actions, and pulled it and tried to run, it didn't work. The error is: "(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError w13-20020aa7954d000000b00574c54423d3sm14276612pfq.145 - gsmtp', 'webmaster@localhost')" Now it is saying "webmaster@localhost", this cannot happen as I am using smpt.gmail.com, also I have made the feature for creating environment variables in .github/workflows/main.yml file. This means somehow my docker-image is not able to access the .envvariables. All my secret credentials are correct as they work when I use it from my laptop's localhost server, but not in docker localhost server. Can anybody shed some light on this? Below is my main.yml files I firstly tried this name: Publish Docker Image to Docker Hub on: push: branches: ['master'] pull_request: branches: ['master'] jobs: build: runs-on: ubuntu-latest steps: - name: 'Create env file' run: | echo "${{ secrets.ENV_FILE }}" > .env - uses: actions/checkout@v3 - name: Log in to Docker Hub … -
SESSION_COOKIE_AGE vs set_expiry() in Django
I have noticed different behavior between SESSION_COOKIE_AGE and set_expiry method. Usually, I am using set_expiry on login as it changes according to the user whether he/she selects REMEMBER BE or not. I understand that if I set SESSION_SAVE_EVERY_REQUEST to True, this means that the expiration date will be updated every time on user activity. However, I noticed that the expiration date of the session is updated on user activity without setting SESSION_SAVE_EVERY_REQUEST (default: False) and without modifying the session. On the other side, it is not working that way if I set SESSION_COOKIE_AGE only without custom setting of set_expiry. From the documentation, it is mentioned that if we set value using set_expiry: the session will expire after that many seconds of inactivity Is that means INACTIVITY in accessing the application or inactivity in modifying the session? And set_expiry equals SESSION_COOKIE_AGE plus SESSION_SAVE_EVERY_REQUEST=True? -
I am not able to perform update operation in crud
I am trying to perform update operation in Django. Actually what I need when I click the update button of an existing entry it should load in an another form with the data and once I change the details need to save it. I have referred a video with same requirement but that code is not working for me. Please help me I am really stuck. These are my files and code details. forms.py from .models import Building from django.forms import ModelForm class BuildingForm(ModelForm): class Meta: model = Building fields = '__all__' models.py from django.db import models # Create your models here. class BuildingType(models.Model): building_type = models.CharField(max_length=100) def __str__(self): return self.building_type class Building(models.Model): building_name = models.CharField(max_length=50) name_of_owner = models.CharField(max_length=50) building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE) number_of_rooms = models.IntegerField() mobile_number = models.IntegerField() current_lease_period = models.DateField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Home, name='home'), path('buildings', views.Buildings, name='buildings'), path('rooms', views.Rooms, name='rooms'), path('customers', views.Customers, name='customers'), path('receipts', views.Receipts, name='receipts'), path('new_building', views.NewBuilding, name='new_building'), path('update/<int:bldg_id>', views.UpdateBuilding, name='update_building'), path('delete_building/<int:bldg_id>', views.DeleteBuilding, name='delete_building'), path('new_room', views.NewRoom, name='new_room'), path('new_customer', views.NewCustomer, name='new_customer'), path('new_receipt', views.NewReceipt, name='new_receipt'), path('login', views.Login, name='login'), path('signup', views.Signup, name='signup'), ] views.py from django.shortcuts import render, redirect from .forms import BuildingForm from webapp.models import Building, BuildingType # … -
Where does business logic go in Django API
I am very new to Django. I am able to set up a basic endpoint thanks to all the tutorials but what many of them miss is Where does one put the business logic of the app? Does it just go in a random file? Do I need to connect it somehow? File structure that I have now I think that I should create a file in apps, then add file with any name inside that folder -
Why can't you find the template?
This is settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my views.py def iniciar_sesion(request): return render(request,'registrar/iniciar_sesion.html') This is the structure appweb |-plantillas |-templates |-registrar |-iniciar_sesion.html It's strange that he can't find it, I don't know why he doesn't -
How to embed an XLSX local file into HTML page with Python and Django
For a Python web project (with Django) I developed a tool that generates an XLSX file. For questions of ergonomics and ease for users I would like to integrate this excel on my HTML page. So I first thought of converting the XLSX to an HTML array, with the xlsx2html python library. It works but since I can’t determine the desired size for my cells or trim the content during conversion, I end up with huge cells and tiny text.. I found an interesting way with the html tag associated with OneDrive to embed an excel window into a web page, but my file being in my code and not on Excel Online I cannot import it like that. Yet the display is perfect and I don’t need the user to interact with this table. I have searched a lot for other methods but apart from developing a function to browse my file and generate the script of the html table line by line, I have the feeling that I cannot simply use a method to convert or display it on my web page. I am not accustomed to this need and wonder if there would not be a cleaner … -
how to solve django login function not logging in the created user
I have a custom register and login with Phone number and i have define a custom backend, this backens.py : class MobileAuthentication(BaseBackend): """ Authenticate with Phone Number """ def authenticate(self, request, phonenumber=None): try: user = User.objects.get(phonenumber=phonenumber) except User.DoesNotExist: user = User(phonenumber=phonenumber) user.is_staff = True user.is_superuser = True user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None and this the Apiview : class ValidateAuthenticationCode(APIView): def post(self, request, format=None): serializer = OneTimePasswordAuthentication(data=request.data) user = authenticate(phonenumber=serializer.data['phonenumber']) if user is not None : login(request, user) data = self.get_response_data(user) if data: response = Response( data.data, status=status.HTTP_201_CREATED ) else: response = Response(status=status.HTTP_204_NO_CONTENT) return response and this the serilizer : class OneTimePasswordAuthentication(serializers.Serializer): phonenumber = serializers.IntegerField() activation_code = serializers.IntegerField(required=False,write_only=True) when i run the code the authentication is done and it returns the created or existing user but login(request, user) not working -
Nested Serializer Connects with Foreign Keys but Fields Comes Empty - django-rest-framework
I have a view that gets Product model and inside there is some fields refers to another tables(foreignkeys). So I want a nested field also a json export format. I want a export that I could see another tables referrings too views.py class ExportDataViewDeneme3(APIView): permission_classes = () def post(self, request): model_list = ["Products"] # Get the foreign key id from the request dagRunId = request.data.get("dagRunId", None) data = {} for model_name in model_list: try: model = globals()[model_name] queryset = model.objects.filter(dagRunId=dagRunId) serializer = model.objects.filter(dagRunId=dagRunId) serializer = model_name + 'ExportSerializer' serializer = globals()[serializer](queryset, many=True) data[model_name] = serializer.data except LookupError: pass json_data = json.dumps(data, indent=4,cls=DateTimeEncoder) response = HttpResponse(json_data, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="export_%s.json"'%(datetime.now()) return response models.py class Products(BaseIdentifiableModel): name = models.CharField(max_length=255, default=None, null=True, blank=True) price = models.CharField(max_length=50, default=None, null=True, blank=True) cost = models.CharField(max_length=50, default=None, null=True, blank=True) manufacturer = models.CharField(max_length=100, default=None, null=True, blank=True) model = models.CharField(max_length=255, default=None, null=True, blank=True) material = models.CharField(max_length=255, default=None, null=True, blank=True) interior = models.CharField(max_length=255, default=None, null=True, blank=True) upc = models.CharField(max_length=100, default=None, null=True, blank=True) imageUrl = models.CharField(max_length=255, default=None, null=True, blank=True) isTaxed = models.BooleanField(null=True, default=None) stateTax = models.BooleanField(null=True, default=None) localTax = models.BooleanField(null=True, default=None) funeralHomeLocations = models.ForeignKey("death_spec.FuneralHomeLocations", models.DO_NOTHING, default=None, null=True, related_name="products_funeral_home_locations", blank=True) productCategory = models.ForeignKey("death_spec.ProductCategories", models.DO_NOTHING, default=None, null=True, related_name="products_product_category", blank=True) generalPriceList = models.ForeignKey("death_spec.GeneralPriceLists", … -
django model override save m2m field
I want to update m2m field on save() method I have the following model: class Tag(models.Model): label = models.CharField(max_length=50) parents_direct = models.ManyToManyField("Tag", related_name="children", blank=True) created = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True, blank=True) administrators = models.ManyToManyField( to=KittyUser, related_name="administrated_tags", blank=True) moderators = models.ManyToManyField( to=KittyUser, related_name="moderated_tags", blank=True) allowed_users = models.ManyToManyField( to=KittyUser, related_name="allowed_tags", blank=True) visible = models.BooleanField(default=True, verbose_name="visible to anyone") POSTABILITY_CHOICES = ( ('0', 'any allowed user can post'), ('1', 'only moderators\\admins can post') ) postability_type = models.CharField(default='0', max_length=1, choices=POSTABILITY_CHOICES) parents_tree = models.ManyToManyField("Tag", related_name="parents_tree_in_for", blank=True) related_tags = models.ManyToManyField("Tag", related_name="related_tags_in_for", blank=True) def save(self, *args, **kwargs): self.label="overriden label" super(Tag, self).save(*args, **kwargs) self.parents_tree.add(*self.parents_direct.all()) breakpoint() super(Tag, self).save(*args, **kwargs) Through django-admin the tags get created, the label substitution works, though parents_tree don't get updated. If I create it from the shell, it is swearing at the second super().save: django.db.utils.IntegrityError: duplicate key value violates unique constraint "posts_tag_pkey" If you take away the first super.save(), you get the following: "<Tag: overriden label>" needs to have a value for field "id" before this many-to-many relationship can be used. in both shell and admin. The question is, how to update my m2m field on save? Another question is why does it work differently in admin panel and shell? -
Django is using wrong TIME_ZONE
On my production environment only, my app uses America/Chicago as time zone while I have TIME_ZONE = "UTC" in my settings. I'm running my code on Debian and the system locale is C.UTF-8 with Django 4.1. I dug in Django code and find the source of my problem here: https://github.com/django/django/blob/c2118d72d61746f2462fca695dbf3adf44ebf8f7/django/utils/timezone.py#L72 I tried in ./manage.py shell to reproduce the problem: # ./manage.py shell Python 3.10.9 (main, Dec 21 2022, 08:51:48) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.conf import settings >>> from django.utils import timezone >>> import zoneinfo >>> settings.TIME_ZONE 'UTC' >>> timezone.get_current_timezone() zoneinfo.ZoneInfo(key='America/Chicago') And if I call the methods in get_current_timezone, I have a different result >>> settings.USE_DEPRECATED_PYTZ False >>> zoneinfo.ZoneInfo(settings.TIME_ZONE) zoneinfo.ZoneInfo(key='UTC') Where could the America/Chicago come from ? -
Django html template in production
im not sure if that is normal in django production deployment but im using django on a ubuntu and using nginx and gunicorn but im still able when i go to network tab to see all the html and javascript code . i have debug mode False and followed different tutorials but none shows or explain the expected behavior , like is it normal to see all the static files in the source and network and the code within those files ? -
How can I adjuste the width of column in the Django Admin
I'm try edit the width of my column in the django admin and let editable, but i don't know how to... When I add this column "nome_short_oficina" in list_editable, show me an error: enter image description here Could you help me? For exemplo: def nome_short_oficina(self): return u"%s" % self.oficina nome_short_oficina.short_description = _(u"Oficina") nome_short_oficina.allow_tags = True I'm try edit the width of my column in the django admin and let editable, but i don't know how to... When I add this column "nome_short_oficina" in list_editable, show me an error. -
Reseting the value of auto_increment field of a django model with `_set_next_value()`
MyModel Definition class MyModel(models.Model): name = models.CharField(max_length=50) To reset the auto increment to a new value from django.db import migrations def set_id(apps, schema_editor): MyModel = apps.get_model('myapp', 'MyModel') max_id = MyModel.objects.all().aggregate(max_id=Max('id'))['max_id'] MyModel._meta.get_field('id').auto_created = True MyModel._meta.get_field('id').auto_created = False MyModel._meta.get_field('id')._set_next_value(max_id + 1) class Migration(migrations.Migration): dependencies = [ ('myapp', '<your previous migration>'), ] operations = [ migrations.RunPython(set_id), ] Line MyModel._meta.get_field('id')._set_next_value(max_id + 1) Giving Error AttributeError: 'AutoField' object has no attribute '_set_next_value' Trying to reset the AutoField to a specific value so that new entries id would start from that id. However I'm getting this error.