Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass parameter to url into the template to redirect to a specific category - django
i made a website hotels , there are some hotels , and i make their rooms into different categories , but in the url i want to show something like this /hotel-name/categories or /hotel-name/rooms/booking but i cant do that in some cases , when the admin one of the hotels access categories via the menu it returns Reverse for 'categories' with no arguments not found. 1 pattern(s) tried: ['categories/(?P[^/]+)$'] this is some of my models class Hotel(models.Model): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Room(models.Model): hotel = models.ForeignKey(Hotel,on_delete=models.PROTECT) room_no = models.IntegerField() beds = models.IntegerField(default=2) this is my views.py def hotels(request): hotels = Hotel.objects.all() return render(request,'rooms/hotels.html',{'hotels':hotels}) def categories(request,hotel): lists = Room.objects.filter(hotel__hotel_name=hotel).values('hotel__hotel_name','room_type','beds', 'balcon').annotate(total=Count('pk')).order_by('-total') return render(request,'rooms/categories.html',{'lists':lists}) i know i can access to a room's specific category through hotels.html <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3 pt-3"> {% for i in hotels %} <a href="{% url 'rooms:categories' i.hotel_name %}"><button class="text-pink-500 bg-transparent border border-solid border-pink-500 hover:bg-pink-500 hover:text-white active:bg-pink-600 font-bold uppercase px-8 py-3 rounded outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150" type="button"> {{i.hotel_name}} </button></a> {% endfor %} but sometimes i want to let the users access to their rooms through the menu main.html <div class="z-50 h-screen overflow-y-scroll w-72 menunon header" id="menu"> <button class="absolute mr-4 text-white … -
how to use django's urlize tag in a modal?
My modal is working fine,and i have used urlize on my html body well as you can see below, The challenge comes when i need to use urlize in a modal, the data for the span tag in the modal is populated in the script,and i cannot apply the urlize tag like before. this is working well <p class="h-3x">{{post.description|urlize|url_target_blank }} </p> the challenge is using urlize tag in the modal because the span tag is populated in the script. modal: <div style="text-align: center;" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <img id="thanks" class="d-block w-100" class="img-responsive" src="#"> </div> <div class="modal-footer justify-content-center"> <span id="deb" class="mr-4"></span> <div> <button type="button" class="btn btn-outline-primary btn-rounded btn-md ml-4" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> script: <script language="JavaScript" type="text/javascript"> $('#exampleModalCenter').on('show.bs.modal', function (event) { var img = $(event.relatedTarget).data('img') // Button that triggered the modal var deb = $(event.relatedTarget).data('deb') $("#thanks").attr("src", img); $("#deb").text(deb); }) </script> -
Browser Output of HTML/Django/Python shows nothing of Python code
I am following Mosh course (Python for beginner (6 hrs)). In the Django project, When listing the products from the database with HTML/Python/Django code. The output not showing it correctly. In fact, it shows blank after the h1 tag. View module code. from django.shortcuts import render from products.models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'product': products}) def new_products(request): return HttpResponse('The Following are our new Products') HTML Code. <ul> {% for product in products %} <li>{{ product.name }}</li> {% endfor %} </ul> The output just show heading Products -
Django Nested Serializer - Return Null Field if condition is fullfiled
I have a nested serializes, which content I need to return as Null in case of the parent-serializer field "is_profile_private" (a boolean) is True. I tried using get_queryset in order to filter the User Profile but no progress was made. Tried using SerializerMethordField() and get_profile() but Django complained about UserProfileSerializer type of object not being allowed to be serialized. serializers.py class UserProfileSerializer(UserSerializer): height = serializers.SerializerMethodField() class Meta: model = UserProfile fields = ( "bio", "gender", "custom_gender", "non_binary_list", "birthdate", "avatar", "height", "hometown", "zodiac_sign", "language", ) @staticmethod def get_height(obj): return {"value": obj.height, "unit": obj.height_unit} class SimpleUserSerializer(UserSerializer): profile = UserProfileSerializer(source="user", required=False) class Meta: model = User fields = ( "id", "name", "username", "is_profile_private", "date_joined", "profile", ) views.py class UserProfileAPIView(RetrieveModelMixin, UpdateModelMixin, GenericViewSet): lookup_field = "id" queryset = User.objects.all() serializer_class = SimpleUserSerializer http_method_names = ["get"] @staticmethod def get(request, *args, **kwargs): return User.objects.get(id=str(request.data)) -
Django Server Error integrating Newsletter signup
I am having an issue integrating my mailchimp signup to my Django server. I am using Django as a server, then connecting it to my frontend with react native. When going to this url (http://127.0.0.1:8000/subscribe_email) I get the following error: AssertionError at /subscribe_email 'MailSubscriptionAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. What am I doing wrong? I just want to be able to use the post method to subscribe a user. Here's my views.py # Mailchimp Settings MAILCHIMP_API_KEY = settings.MAILCHIMP_API_KEY MAILCHIMP_DATA_CENTER = settings.MAILCHIMP_DATA_CENTER MAILCHIMP_LIST_ID = settings.MAILCHIMP_EMAIL_LIST_ID class MailSubscriptionAPIView(GenericAPIView): def subscribe_email(email): mailchimp = Client() mailchimp.set_config({ "api_key": MAILCHIMP_API_KEY, "server": MAILCHIMP_DATA_CENTER }) member_info = { "email_address": email, "status": "subscribed", } try: mailchimp.lists.add_list_member(MAILCHIMP_LIST_ID, member_info) except ApiClientError as error: print(error.text) def post(self, request, *args, **kwargs): email = request.data['email'] MailSubscriptionAPIView.subscribe_email(email) return Response({ "status_code": status.HTTP_200_OK, "message": "Mail added to mailchimp" }) urls.py urlpatterns = [ path('', include(router.urls)), path('subscribe_email', MailSubscriptionAPIView.as_view(), name= 'subscribe-email' ), ] Any help is appreciated! -
When I enter startapp command in django, app did not be added in project
I'm making website using django by pycharm pro version. A command "python manage.py startapp 'app name'" worked well before, but unexpectedly, the command does not work now. when I enter the command in terminal, in terminal, there is nothing difference. but app doesn't develop in the file, so I retry the command, CommandError: 'app name' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. commanderror raised... what is the problem? I want to know the solution. -
How to get your own Pytesseract font in Heroku project?
I have a Vue, Django integrated project. I hosted the Vue project on Netlify and the Django project on Heroku. A python script (integrated into Heroku) is called on certain buttons which extract data and posts this to the Django API to be viewed on the frontend. Now in my normal project I have made a font type within Pytesseract to extract data correctly. How do I integrate this font type into Heroku? I'm trying to get Heroku to use my font (my .traineddata file). So I have it in my local tessdata folder (the traineddata file, in the same directory as the normal 'eng' data file), but don't know how to get it on Heroku. Thanks! -
Django Password Reset Confirm error (custom user model)
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to create a password reset form... but I got the following error when accessing the link from the forgot password email - and before that the password was not saving: get_context_data() missing 1 required positional argument: 'user' forms.py (almost copy/paste from Django's form; minor changes) class ResetPasswordForm(SetPasswordForm): error_messages = { 'password_mismatch': static_textLanguage['page_user_passwordReset_alert_passwordNotMatch'], 'password_empty': static_textLanguage['global_alert_mandatoryField'], 'minimum_length': static_textLanguage['global_alert_minCharacters_password'], } new_password1 = forms.CharField( required=False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordA', 'maxlength': '25', 'class': 'global_component_input_box' }), ) new_password2 = forms.CharField( required = False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordB', 'maxlength': '25', 'class': 'global_component_input_box' }), ) def __init__(self, user, *args, **kwargs): self.user = user super(ResetPasswordForm, self).__init__(user, *args, **kwargs) def clean_new_password1(self): password1 = self.cleaned_data.get('new_password1') if password1 == '' or password1 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') elif len(password1) < 8: raise forms.ValidationError(self.error_messages['minimum_length'], code='password_too_short') return password1 def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password2 == '' or password2 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') if password1 and password2: if password1 != password2: raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch') password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user views.py class UserPasswordResetView(auth_views.PasswordResetConfirmView): template_name = '../frontend/templates/frontend/templates.user/template.page_passwordReset.html' form_class = ResetPasswordForm post_reset_login = True success_url = reverse_lazy('page_userLoginPrivate') def … -
shuffle HTML list element order - django
I want to shuffle list when the user open the page he will see every time different order for example: <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> -
Django 3 - password reset - not generating email
I've followed multiple sources on how to set this up. Now everything seems working (no error) but I just don't see the email. gmail - Allow less secure apps: ON url.py path('pw_reset/', auth_views.PasswordResetView.as_view(template_name="authacc/pw_reset.html"), name="reset_password"), path('pw_done/', auth_views.PasswordResetDoneView.as_view(template_name="authacc/pw_done.html"), name="password_reset_done"), path('pw_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="authacc/pw_confirm.html"), name="password_reset_confirm"), path('pw_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="authacc/pw_complete.html"), name="password_reset_complete"), settings.py #SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') What I've tried... use debuggingserver to check the email locally. settings.py EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 cmd python -m smtpd -n -c DebuggingServer localhost:1025 I can see the "Password reset sent" page, but no email is generated. So I suspect there's something wrong with the default PasswordResetView? Probably similar problem, but unresolved: Reset password emails in Django -
gunicorn prevent HUP after it has been triggered
Based on Gunicorn's documentation there is no hook for pre_worker_exit. What I am basically trying to achieve is to prevent workers from exiting if some criteria are met. In my Django application, I have some functions that due to race condition, they are being initiated after the HUP signal and therefore once the workers exit and new ones are spawned, the functions get interrupted in the old workers. Is there a way to stop the HUP signal after it has been triggered or have some kind of pre_worker_exit hook that will check if some criteria are met and therefore delay the worker exiting? Thanks -
export a table with a foreign key to excel
I have these 2 models: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255) def get_absolute_url(self): return reverse('bilans:canva_detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Bilan(models.Model): agregat = models.CharField(null=True, blank=True, max_length=255) SCF = models.CharField(null=True, blank=True, max_length=255) canva = models.ForeignKey('Canva', null=True, blank=True, on_delete=models.CASCADE, related_name='bilan_canva') I have this page that lists the objects of Canva: {% for c in canva %} <a class="btn btn-info btn-outline-dark w-auto mb-2" href='/canvas/consult/{{c.pk}}'>{{ c.name }}</a> {% endfor %} that link lead to this page that show the objects in Bilan that match canva primarykey: {% for bilan in canva.bilan_canva.all %} <table width="100%" border="1"> <tbody> <tr> <th scope="col">{{ bilan.agregat }}</th> <th scope="col"> {{ bilan.SCF }} </th> </tr> </tbody> </table> {% endfor %} I added this link at the end of the html page to export to excel: href="{% url 'bilans:export_excel' %}" role="button" class="btn btn-secondary w-50">export to excel this is the view.py: def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Canvas.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('canvas list') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['agregat', 'scf', 'mois1', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # … -
How to view other group members if i am a member of that group?
In my mobile app,i am trying to create a system which i can fetch other group members that are already member to groups i belong to.But i can only fetch myself,rather than them.How can i do it? Note: I can fetch them from GroupViewSet that i am in,but i have to access to them in GroupMemberViewSet so if i am admin of that group i can patch the groupmember's membership. Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class Group(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50,blank=True) class GroupMember(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='groupmembers') group = models.ForeignKey(Group,on_delete=models.CASCADE,related_name='groupmembers_set') isadmin = models.BooleanField(default=False) ismod = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) Views.py class GroupMemberViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = GroupMember.objects.all().order_by('-timestamp') serializer_class = GroupMemberSerializer filter_backends = [UserFilterBackend] Filters.py class UserFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(author=request.user) -
Adding additional information into each form field
I am using Django/Wagtail and the wagtailstreamforms package to build forms. Unfortunately you cannot add two fields side-by-side in the wagtailstreamforms form builder out of the box, so I am trying to add a functionality that allows the user to input an integer 1 to 12 (based on Bootstrap columns - col-1 to col-12) for each field and this number will be retrieved in the templates and will be used. In the wagtailstreamforms_fields.py file, I've started to override the CharField model to add the extra width integer: from django import forms from wagtailstreamforms.fields import BaseField, register from wagtail.core import blocks class CustomCharField(forms.CharField): def __init__(self,*args, **kwargs): self.width = kwargs.pop('width') super().__init__(*args,**kwargs) @register('singleline') class Column_SingleLineTextField(BaseField): field_class = CustomCharField def get_options(self, block_value): options = super().get_options(block_value) options.update({'width': block_value.get('width')}) return options def get_formfield(self, block_value): options = super().get_formfield(block_value) return options def get_form_block(self): return blocks.StructBlock([ ('label', blocks.CharBlock()), ('help_text', blocks.CharBlock(required=False)), ('required', blocks.BooleanBlock(required=False)), ('default_value', blocks.CharBlock(required=False)), ('width', blocks.IntegerBlock(help_text="Width of field, 1 to 12, 12 is full width.", max_value=12, min_value=1, default=12, required=True)), ], icon=self.icon, label=self.label) This code adds the extra integer input for the singleline field in the wagtailstreamforms form builder page in Wagtail settings. Now the issue I'm facing is, I'm not able to retrieve the width parameter in the templates. … -
Django database does not exists in postgreSQL container?
How can I connect my postgreSQL database container with my django application. I have created the postgreSQL container and with this command docker exec -it ae732 bash I gained the bash and entered into psql and created a database and with this container ID I used this container ID with docker-compose file as shown below. services: app: build: context: . environment: - SECRET_KEY=changeme - ALLOWED_HOSTS=127.0.0.1,localhost depends_on: - db db: image: postgres restart: always volumes: - static_data:/static/db ports: - 5432:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: ae73234b58e8 proxy: build: context: ./proxy volumes: - static_data:/vol/static ports: - 80:8080 depends_on: - app volumes: static_data: But still the django application says that database doesn't exit even-though I saw it is in there in postgreSQL container. -
I am trying to learn pytest and 1 test case keep failing with details shared below
#!/usr/bin/python -- coding: utf-8 -- #I have written pytest as per #comments in test_invetory.py file.All test cases are passed but only 1 still failing. can someone please help me with ans. -------Given Files: inventory.py------ class InsufficientException(Exception): pass class MobileInventory: def __init__(self, inventory=None): if inventory is None: self.balance_inventory = {} else: if not isinstance(inventory, dict): raise TypeError('Input inventory must be a dictionary') for model in inventory: if not isinstance(model, str): raise ValueError('Mobile model name must be a string' ) if not isinstance(inventory[model], int) \ or inventory[model] < 0: raise ValueError('No. of mobiles must be a positive integer' ) self.balance_inventory = inventory def add_stock(self, new_stock): if not isinstance(new_stock, dict): raise TypeError('Input stock must be a dictionary') for model in new_stock: if not isinstance(model, str): raise ValueError('Mobile model name must be a string') if not isinstance(new_stock[model], int) \ or new_stock[model] < 0: raise ValueError('No. of mobiles must be a positive integer' ) if model in self.balance_inventory: self.balance_inventory[model] += new_stock[model] else: self.balance_inventory[model] = new_stock[model] def sell_stock(self, requested_stock): if not isinstance(requested_stock, dict): raise TypeError('Requested stock must be a dictionary') for model in requested_stock: if not isinstance(model, str): raise ValueError('Mobile model name must be a string') if not isinstance(requested_stock[model], int) \ or requested_stock[model] < 0: raise … -
How to generate random uid and token in django without generating models and logins of user
I have to activate user without models. I am not generating any user. I want to generate random uid and token. for that I want to pass this uid and token in /activate/{uid}/{token} link. I created this code in view for generate uid and token: class ActivateUser(CreateAPIView): def get(self, request, uid, token, format = None): payload = {'uid': uid, 'token': token} print("payload : " , payload) url = "http://localhost:8000/api/auth/users/activate/" response = request.post(url, data = payload) if response.status_code == 204: return Response({}, response.status_code) else: return Response(response.json()) For activate user I generate this link in url re_path('api/auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/',ActivateUser.as_view()) create activation url in setting.py DJOSER = {'ACTIVATION_URL': 'activate/{uid}/{token}/', } -
Django How to sign up for membership on another page
I am a student who is learning Django. If you press the OK button on the sign-up page, the sign-up is complete! I'd like to put the confirmation button in another html and save what I entered on the membership page, is it possible? To summarize, I would like to move the button on my membership to Different html so that my membership can be completed. register.html <form method="post" class="post-form"> {% include "accounts/form_errors.html" %} {% csrf_token %} <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label"><b>이름</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" id="name" value="{{ form.name.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="username" class="col-sm-2 col-form-label"><b>아이디</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="username" id="username" value="{{ form.username.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="password1" class="col-sm-2 col-form-label"><b>비밀번호</b></label> <div class="col-sm-10"> <input type="password" class="form-control" name="password1" id="password1" value="{{ form.password1.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="password2" class="col-sm-2 col-form-label"><b>비밀번호 확인</b></label> <div class="col-sm-10"> <input type="password" class="form-control" name="password2" id="password2" value="{{ form.password2.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="phone" class="col-sm-2 col-form-label"><b>전화번호</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="phone" id="phone" value="{{ form.phone.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="email" class="col-sm-2 col-form-label"><b>이메일</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="email" id="email" value="{{ form.email.value|default_if_none:'' }}"> </div> </div> <button type="submit" style="background: #637B46; float: right; border: white" … -
Why serving static files are an issue in Python apps
I don't seem to understand the issue with serving static files in Python apps, for example Django. Now I am reading a documentation of WhiteNoise and first question is why it was developed in the first place? I mean what problem it solves? Why we can't save all the static files in /static folder and copy it to hosting. -
call update of a serializer in a function in django
I have this date coming from the frontend: d = {'dispatch_date': '2021-08-25T10:40:19.783Z', 'send_from_warehouse': 2, 'sales_order': 635, 'flows': [{'flow': 67, 'kit': 8, 'asked_quantity': 9, 'alloted_quantity': '9'}, {'flow': 67, 'kit': 3, 'asked_quantity': 8, 'alloted_quantity': '0'}, {'flow': 67, 'kit': 49, 'asked_quantity': 7, 'alloted_quantity': '0'}], 'model': 'Rent', 'vehicle_type': 'Part Load', 'transport_by': 4, 'expected_delivery': '2021-08-25T10:40:19.783Z', 'owner': 2, 'transaction_no': 2807} using this data I want to edit an object of Material Request with id 635. How do I call the edit from serializer of Material Request? class MaterialRequestFlowSerializer(serializers.ModelSerializer): class Meta: model = MaterialRequestFlow fields = "__all__" class MaterialRequestSerializer(serializers.ModelSerializer): flows = MaterialRequestFlowSerializer(many=True) class Meta: model = MaterialRequest fields = "__all__" def create(self, validated_data): print("validated", validated_data) items_objects = validated_data.pop('flows', None) prdcts = [] for item in items_objects: i = MaterialRequestFlow.objects.create(**item) prdcts.append(i) instance = MaterialRequest.objects.create(**validated_data) print("prdcts", prdcts) instance.flows.set(prdcts) return instance def update(self, instance, validated_data): print("s") items_objects = validated_data.pop('flows',None) prdcts = [] for item in items_objects: print("item", item) fk_instance, created = MaterialRequestFlow.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(fk_instance.pk) instance.flows.set(prdcts) instance = super(MaterialRequestSerializer, self).update(instance, validated_data) return instance -
How to run a hub pulled docker image setting the environment variables
I have a Django project and I'm trying to deploy it on an AWS EC2 instance. I've created 2 docker images (application and nginx), tested locally, pushed to hub, but when I pull in my EC2 instance and try to run it, I'm getting environment variable errors like this one: File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 90, in __getattr__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I've tried to create the .env file in the root folder and run: docker run <image_id> --env-file ./.env Also tried to set the varible manually with: expose MY_VAR='something' Still not working. Is there a specific way to run images that was created and pushed with docker-compose, setting the environment variables? -
I am trying to add Twilio broadcast SMS feature to my Django app, but can't work out how to retrieve all Database phone numbers
I have created a 'Post' model in my django app that uploads a basic article to the database. I am trying to implement a feature that notifies users that a new article has been uploaded via SMS, but this needs to be sent to all users who have registered their number in the database (saved in a separate 'Profile' model). I have added a 'save' function to the model that sends the SMS when the post is uploaded: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() detail_text = models.TextField(default='') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN user_numbers = '' client = Client(account_sid, auth_token) message = client.messages.create( body= 'Hello, a new article is available from your dashboard.', from_= settings.TWILIO_NUMBER, to = user_numbers ) print(message.sid) return super().save(*args, **kwargs) I have made the API work with a single number, hard-coded in the app, but now want to draw numbers from the database and send to all users who have registered their mobile number. I have tried using Profile.objects.get(phone_numbers) but this didn't work. Looking at the Twilio docs I am minded that I will need to save the numbers in settings.py … -
How to get the user that modified an object? django-simple-history
I am trying to save the history of an object by using django-simply-history library, so far i can see the changes of the object itself but not the user that made the changes. I have the following set up. Settings: # settings.py INSTALLED_APPS = [ # ... 'simple_history', # ... ] MIDDLEWARE = [ # ... 'simple_history.middleware.HistoryRequestMiddleware', # ... ] Models: from django.db import models from apps.companies.models import Company from simple_history.models import HistoricalRecords # Create your models here. class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) dateCreated = models.DateTimeField(auto_now_add=True,) dateUpdated = models.DateTimeField(auto_now=True,) telephone = models.CharField(max_length=20, blank=True, null=True) address = models.CharField(max_length=20, blank=True, null=True) email = models.EmailField(max_length=254, blank=True, null=True) history = HistoricalRecords() Then in the Shell i do: customer = Customer.objects.all().last() customer.name = "Test" customer.save() customer.history.all().last() Out[79]: <HistoricalCustomer: Customer object (d2211cc1-9762-4f6d-9086-634deee95b1e) as of 2021-08-24 09:28:44.978543+00:00> # How can I print the user that changed the object???? customer.history.all().last()_history_user Thanks, -
Change model in CreateView dependending on user in django
I want to change the model of a createview dependending on the user. The view class is as follow: class SubirCasoView(LoginRequiredMixin, CreateView): login_url = reverse_lazy('users_app:user-login') template_name = 'casos/crear-caso.html' success_url = reverse_lazy('casos_app:update-caso') def get_form_class(self): current_user = self.request.user if current_user.especialidad == 'Reumatología': self.form_class = CasoReumaForm else: self.form_class = CasoDermaForm return self.form_class def form_valid(self, form): """If the form is valid, save the associated model.""" if 'borrador' == self.request.POST: publicar = False self.object = form.save() self.object.user = self.request.user '''for each in self.cleaned_data['images_description']: ImageDescriptionDerma.objects.create(file=each, caso=self.object) for each in self.cleaned_data['images_evolucion']: ImageEvolucionDerma.objects.create(file=each, caso=self.object)''' else: publicar = True self.object = form.save() self.object.user = self.request.user '''for each in self.cleaned_data['images_description']: ImageDescriptionDerma.objects.create(file=each, caso=self.object) for each in self.cleaned_data['images_evolucion']: ImageEvolucionDerma.objects.create(file=each, caso=self.object)''' return super().form_valid(form) What I was trying to do is something similar to the function 'get_form_class' but with model. I have try it with 'get_object' function but seems not to work. My idea is to do something like: def function_name(self): current_user = self.request.user if current_user.especialidad == 'Reumatología': self.model = CasoReuma else: self.model = CasoDerma return self.model -
id field which is not primary key in django django model
Is it possible to create an id field in a model that is not primary_key in django? If so, how to do it? To be clearer, here is my model: class GWS(models.Model): id = models.CharField(max_length=20,primary_key=False) ... What can I do to prevent the id field from being primary key? api.GWS: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'