Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Save Django Website State across all browsers the app is accessed at
I have created a Django webiste which fetches data on a realtime basis through view and renders to the Html Template, I am already running serveral ajax queries to refresh my specific views to render and display data every second, but now i have a bigger problem which is to maintain the same state of the template accross all the browsers the Django server is accessed at. For example If user 'A' logs in and do certain operations on the webiste which changes the states of tables in my pstgres, and after an hour user 'B' logs in with same credentials he should be able to see the same operations running but right only the raw template is visible to user 'B'. I have created the middleware using postgres. I am not getting the solution to this since a long time now. I tries using ajax to call every view once but i don't think this solution is a long term because as more views get added more and more ajax calls will slow down the system. -
GraphQL I am trying to get a list based on a variable and getting "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'."
Initially, I had a problem with the error: There is no current event loop in thread 'Thread-2'." but after adding async to the resolver code another error appeared: "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'." There is Query and resolvers: class Query(graphene.ObjectType): prices = graphene.List(PriceType) tours = graphene.List(TourType) users = graphene.List(UserType) reservations = graphene.List(ReservationType) reservations_by_place = graphene.List(ReservationType, place=graphene.String()) def resolve_prices(root, info, **kwargs): return Price.objects.all() def resolve_tours(root, info, **kwargs): return Tour.objects.all() def resolve_users(root, info, **kwargs): return User.objects.all() def resolve_reservations(root, info, **kwargs): return Reservation.objects.all() async def resolve_reservations_by_place(root, info, place: String): return Reservation.objects.all(place=place) GraphQl query: query GetReservationByTour($tour_place: String!) { reservationsByPlace(place: $tour_place) { id tour { id place } } } and full error: { "errors": [ { "message": "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "reservationsByPlace" ] } ], "data": { "reservationsByPlace": null } } I've already tried changing from all to get and from Field to List etc. -
How to get confirmation from rabbitmq after publishing a message
I'm trying in python to get an acknowledgment from rabbitmq after publishing a message to a queue. I am using this example for test. https://pika.readthedocs.io/en/stable/examples/blocking_delivery_confirmations.html But the desired result is not obtained. -
no errors thrown when running pipenv install, but running a python manage.py migrate after results in errors
ModuleNotFoundError: No module named 'django_on_heroku' I've got a new machine at work and I'm attempting to run an old project which I've cloned. Cannot get the api server up and running. (ps, my first stack overflow post -- sorry if the format isn't great or specific enough!) Have tried installing django on heroku in the pipenv - that is sucesfull, the error reoccurs though on the next dependency when i attempt a migrate and then run server. -
Django is showing me a 404 error instead of my image
my friends, this is my first question here. So, I follow the Django documentation and some questions here, but the problem keep happening. I did what was said on other similar questions, like this one, for examaple: Issue with image in django But the problem persists. So, my model looks like this: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True) picture = models.ImageField(blank = True, null = True, upload_to = user_directory_path) whatsapp = models.PositiveIntegerField(blank = True, null = True) My settings looks like this: MEDIA_ROOT = f"{BASE_DIR}/media" MEDIA_URL = '/media/' I added + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) to the end of my urls.py file. The folder and images are being created on my file system when I add them via the admin, but when I click to see them over there I recieve a 404. admin screen error screen I am making a mobile app and serving my data using Django Rest Framework, the images are the only thing giving me a headache right now. -
React, Django and FastAPI architecture
My team is developing a platform where our clients upload data through an API (typically once per hour). The data is analyzed and then made accessible through a web/dashboard of sorts. I don't have experience with Django/React so I'm struggling to understand how a good architecture should look like combining the following tools/frameworks: React for frontend Django as our web-server FastAPI as the API to upload data (and as DB access layer) (Note: FastAPI will run separatly - Django and FastAPI communicate through HTTP/JSON) My struggle is this: Do I need django? Can I just use React and the expose all data through FastAPI? Should I throw out FastAPI because I'm using Django anyway? (for API's FastAPI is so much better imo) The original idea was to have no public APIs and only allow our clients to upload data through our data upload API from specified IP addresses with authentication. Only our web-server should access our internal API's to serve data back to our dashboards. Is that an overdesign? Im running with the assumption that Django REST and authentication support is superior to using just React/FastAPI to service web-pages. The FastAPI is alread implemented based on current needs and the … -
How to override the default login for Django rest framework browsable API
I have a django rest fw application and when we are using the browable api page and click login it goes to default django login page. When I try to reach https://my-app/api/v1/getdetails and my login has expired, I get defaulted to this page: https://my-app/api-auth/login/ But the new login page i wan is this: http://my-app/signin/ the auth is done by Okta in the application. I did try overriding this LOGIN_REDIRECT_URL = '/signin/' LOGIN_URL = '/signin/'