Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
I'm trying to perform math operation (specifically addition) with the contents of integer fields on my django models
I'm trying to perform math operation (specifically addition) with the values of integer fields on my django models but i kept getting this warning even before running the program: "Class 'IntegerField' does not define 'add', so the '+' operator cannot be used on its instances" this is my django model code: class Applicants(models.Model): fname = models.CharField(max_length=255) lname = models.CharField(max_length=255) number = models.CharField(max_length=255) email = models.CharField(max_length=255) gender = models.CharField(max_length=255) p_course = models.CharField(max_length=255) o_course = models.CharField(max_length=255) grade1 = models.IntegerField(max_length=255) grade2 = models.IntegerField(max_length=255) grade3 = models.IntegerField(max_length=255) grade4 = models.IntegerField(max_length=255) grade5 = models.IntegerField(max_length=255) grade6 = models.IntegerField(max_length=255) total_grade = grade1 + grade2 + grade3 + grade4 + grade4 + grade5 -
Why can't the normal module mock.patch in the celery task?
Why does it not continue to apply when I change return_value using moker.patch? tasks @shared_task def send_reminder(): reminders = Reminder.objects.filter(remind=False) for reminder in reminders: result = send_reminder(reminder.id) if result == 200: reminder.remind = True reminder.save() send_reminder / file dir : reminder/kakao/send_reminder.py def send_reminder(reminder_id: int): tokens = Token.objects.first() reminder = Reminder.objects.get(id=reminder_id) url = "https://kapi.kakao.com/v2/api/talk/memo/default/send" headers = {"Authorization": "Bearer " + tokens.access_token} data = { "object_type": "text", "text": f"{reminder.notice.title}\n" f"{reminder.notice.school.url}\n\n", "link": { "web_url": reminder.notice.school.url, }, "button_title": reminder.notice.school.name, } data = {"template_object": json.dumps(data)} response = requests.post(url, headers=headers, data=data) print("response : ", response) return response.status_code test_send_reminder from reminder.tasks import send_reminder from unittest.mock import patch import pytest @pytest.mark.django_db(transaction=True) def test_send_reminder(mocker, school_one, notice_one, reminder_one, celery_app, celery_worker): mocker.patch('reminder.kakao.send_reminder.send_reminder', return_value=200) # When: start batch job crawling result = send_kakao_reminder.delay() # Then: result.get() should be None assert result.get() is None fail_message FAILED reminder/tests/test_tasks.py::test_send_reminder - AttributeError: 'NoneType' object has no attribute 'access_token' I want to test that the return_value of the function written in moker.patch is 200 and False is changed to True. -
How to use foreign key as a distinct value and sort the queryset with a timestamp field first in Django?
I am using Postgres in my django project and I want to get all the tickets based on a customer full_name search with distict customer_id and sort the ticket queryset based on card_timestamp field in Ticket model. I have two models like the following: class Ticket(BaseTimeClass, BaseDeletedClass): customer=models.ForeignKey(Customer,on_delete=models.CASCADE, related_name="generated_tickets") is_replied = models.BooleanField(default=False) is_resolved = models.BooleanField(default=False) card_timestamp = models.DateTimeField(blank=True, null=True) class Customer(BaseDeletedClass): created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True, db_index=True) modified_at = models.DateTimeField(auto_now=True, blank=True, null=True) first_name = models.CharField(max_length=64, default="") last_name = models.CharField(max_length=64, default="") full_name = models.CharField(max_length=256, default="") I have tried with this: Ticket.objects.filter(Q(customer__full_name__icontains="shuvo")) .select_related("customer") .order_by("customer_id", "-card_timestamp") .distinct("customer_id") ) the problem with this query is, it is returning the queryset sorted by the customer_id 1st then using the card_timestamp. for better scenario, e.g. there can be multiple customer named with "shuvo": customer_id can be 1870, 1120, 3210, and their card_timestamp value is "13 january 2023", "28 december 2022" and "14 december 2022". expected scenario, the queryset should return customer_id 1870, 1120 and 3210 sequentially but it is returning customer_id 3210,1870, 1120. how to solve this problem using django-orm? thanks in advance! -
getting valueerror too many values to unpack (expected 2) in send_mass_mail
class SendMailViews(APIView): def post(self, request, format=None): html_message = render_to_string('email/test.html') plain_message = strip_tags(html_message) message1 = ("subject", plain_message, 'rahulsha24445@gmail.com', ['sharmaviraj300@gmail.com'], html_message) message2 = ("subject", plain_message, 'rahulsha24445@gmail.com', ['abhijeetlaal7899@gmail.com'], html_message) emailList = [message1, message2] send_mass_mail(emailList, fail_silently=False) return Response({"status": True}) I want to send HTML based email to a mass recipient.