Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connection postgres sql during test in Gitlab pipeline with django
I am looking to perform a CI/CD pipeline for a small django project. During this one, I want to run the tests on my postgressql database, which is on a google cloud instance. However, during the push, and the launch of the test command, I have an error which highlights a connection refused. django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "<MY_HOST_GCP_INSTANCE>" and accepting TCP/IP connections on port 5432? here, settings.py elif config('SPEC_ENV') == "staging": DEBUG = False ALLOWED_HOSTS = ['host.docker.internal', 'localhost', '127.0.0.1'] ENVIRONMENT_NAME = "SERVEUR DE TEST STAGING" ENVIRONMENT_COLOR = "#F8F4A7" ENVIRONMENT_TEXT_COLOR = "#000000" ENVIRONMENT_FLOAT = True SECRET_KEY = config('SECRET_KEY_STAGING') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME_STAGING'), 'USER': config('DB_USER_STAGING'), 'PASSWORD': config('DB_PWD_STAGING'), 'HOST': config('DB_HOST_STAGING'), 'PORT': config('DB_PORT_STAGING'), 'OPTIONS': { 'sslmode': 'verify-ca', 'sslrootcert': config('CERT_SERVEUR_STAGING'), "sslcert": config('CERT_CLIENT_STAGING'), "sslkey": config('CERT_KEY_STAGING'), } } } STRIPE_PUBLISHABLE_KEY = config('STRIPE_PUBLISHABLE_KEY_TEST') STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY_TEST') STRIPE_WEBHOOK_SECRET = config('STRIPE_WEBHOOK_SECRET_TEST') GS_BUCKET_NAME = config('BUCKET_STAGING') CELERY_BROKER_URL = config('REDIS_STAGING') CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': config('REDIS_STAGING'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PASSWORD': config('REDIS_PW_STAGING') } } } The environment variables are well configured on Gitlab and I can access them with echo. here, gitlab-ci.yml image: python:3.8.13 stages: - test - deploy variables: DJANGO_SETTINGS_MODULE: ialab.settings SPEC_ENV: $SPEC_ENV … -
CVB with 2 forms in one template: form2 errors are not displayed
EDIT in fact form2 errors are displayed as 'form2.errors' and not 'form2.date_of_last_period.errors' Django 4.1.6 I try to implement a single CBV to manage 2 forms. I use ModelForm to define the 2 forms Inclusion and Patient. Models Inclusion and Patient are link with a one-to-one relationship (I understand I could do a single model but have to separate). I have override methods of CVB CreateView. In post methods, I test for 2 forms validity. And if not valid, call appropriate form_invalid method. In debbug (print('invalid',form.errors,form2.errors)) I see errors raised. But the form2 render to the context (context['form2'] = kwargs.get('form2', self.second_form_class())) do not content any errors. What is wrong with my code? template ... <div class="col-md-12"> <div class="input-group input-group-dynamic mb-4 is-invalid"> <label class="form-label">{{ form2.date_of_last_period.label }}</label> {{ form2.date_of_last_period }} {% for error in form2.date_of_last_period.errors %} <div class="invalid-feedback d-block text-danger"> {{ error }} </div> {% endfor %} </div> </div> views.py @method_decorator(login_required, name="dispatch") class InclusionCreate(SuccessMessageMixin, CreateView): model = Inclusion form_class = InclusionForm second_form_class = PatientForm template_name = "web/inclusion_form.html" success_message = "Inclusion created." success_url = reverse_lazy('web:inclusion_list') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.object = None def get_initial(self, **kwargs): initial = super().get_initial() initial['uuid'] = uuid.uuid4() return initial def form_valid(self, form, form2): form.save(commit=False) form.instance.created_by = self.request.user.username # … -
How to log info from DeleteView to log file
I have DeleteView and im looking for way to send info of model info which this DeleteView delete to log file I tried to write that in get_object but it gives me multiple info about delete views.py class DeleteWorkLog(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): login_url = 'login/' redirect_field_name = '' model = WorkLog success_url = reverse_lazy('contractor_home') template_name = 'inc/modal_delete.html' def test_func(self): self.object = self.get_object() current_user = self.request.user if current_user.is_superuser: return True if self.object.author == current_user: return True else: return False def handle_no_permission(self): messages.error(self.request, 'У вас нет прав на удаление этого журнала') return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) def get_object(self, queryset=None): worklog = WorkLog.objects.get(pk=self.kwargs['pk']) writing_logs(self.request, f'Удалил_журнал_работ {worklog.contractor_object} {worklog.worklog_date}') return worklog def get_success_message(self, cleaned_data): return 'Успешно удалено' -
IndexError at /accounts/signup/
class UserSignUp(CreateView): template_name = "registration/signup.html" model = User form_class = UserSignupForm success_url = reverse_lazy('home') failed_message = "The User couldn't be added" def form_valid(self, form): user_to_add = form.cleaned_data # check the data we get when the form is valid print("user_to_add", user_to_add) super(UserSignUp, self).form_valid(form) # # inherit from ModelFormMixin : form_valid(form) # # Saves the form instance, sets the current object for the view, # # and redirects to get_success_url(). print("---------form valid") # The form is valid, automatically sign-in the user user = authenticate(self.request, username=form.cleaned_data['username'], password=form.cleaned_data['password1']) if user is None: print("---------user none") # User not validated for some reason, return standard form_valid() response # Inherit from TemplateResponseMixin : # render_to_response(context, **response_kwargs)¶ return self.render_to_response( self.get_context_data(form=form, failed_message=self.failed_message)) else: print("-----------user good") # Log the user in login(self.request, user) # Redirect to success url return redirect(reverse(self.get_success_url())) This is the error i'm getting: IndexError at /accounts/signup/ list index out of range -
Redis GRAPH | unable to set TTL to the node and edge created in redis graph via python
I am using redis graph in my django project to save huge number of data nodes. I am not able to set the expire time of these nodes so the redis data keeps on increasing. I do not want to set a TTL in configuration as different nodes can have different TTL. I am using django-redis==5.2.0 for intereacting with redis from django. Also i am mostly using raw graph query to save data in redis graph like "CREATE (n:label {a:1}) RETURN n" , so if there is a parameter which i can set here to set TTL it will be helpful. -
Issue In Django Channels. I'm try to broadcast message on a channels using channel_layer.group_send from outside the consumer
I have a one consumer in Django channels. and i'm try to broadcast message to this channels from Django APIView using async_to_sync. But i'm facing event loop error. Let me share the error Consumer Code class OnlineConsumer(AsyncWebsocketConsumer): REDIS_KEY_PROFILES = "online_profiles" REDIS_KEY_PREFERENCES = "preferences_profile" async def connect(self): pass async def date_remaining(self, event: "dict"): await self.send(json.dumps( event.get("data", []), )) I try to call date_remaining this method from django View View Code def broadcast_to_online_socket(user): try: room_name = get_online_room_name_sync(user) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( room_name, { 'type': 'date_remaining', 'data': 'Your data here', } ) except Exception as e: pass class ReduceDateRemaning(APIView): def get(self, request): try: throttle_1 = Throttling(request.user.id) throttle_1.throttle_success() date_remaning = throttle_1.get_remaining_hits() broadcast_to_online_socket(request.user) return Response(data={"message": f"You have only {date_remaning} dates Remaning today"}, status=status.HTTP_200_OK) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "Something went wrong"}) If you have any suggestion or solution please let me know I have tried to call group_send using asyncio event lopp but still same error -
Django Firebase iOS Push Notifications
I have an iOS application where I want to add push notifications. I also setup a Django backend for the app. I want to send push notifications from the Django backend to the iOS app for specific users. I successfully setup Firebase Messaging and am receiving the push notifications on the mobile app when I create one through the FireBase dashboard. However, I am incredible confused on how I can achieve this through the backend. I am using the Django-push-notifications app from Github I have setup the settings as follows: INSTALLED_APPS = ( ... "push_notifications" ) PUSH_NOTIFICATIONS_SETTINGS = { "FCM_API_KEY": os.environ.get('FCM_API_KEY', "AAAAA"), "APNS_AUTH_KEY_PATH": "/MYkey.p8", "APNS_AUTH_KEY_ID": os.environ.get('APNS_AUTH_KEY_ID', "AAAAA"), "APNS_TEAM_ID": os.environ.get('APNS_TEAM_ID', "AAAAA"), } I don't manually use the APNS tokens. I use the FCM tokens to send a message to a specific user in the dashboard of FireBase. However, I am not aware that Firebase is using any APNS tokens (but it must I suppose). This topic just adds to the confusion since APNS tokens aren't necessarily tied to the retrieval of FCM tokens. From what I gather I should use the following code to send a message: from push_notifications.models import APNSDevice device = APNSDevice.objects.get(registration_id=apns_token) device.send_message(message={"title" : "Game Request", "body" : "Bob … -
Blank Page for React frontend (django backend) when deploying through Google Cloud Platform Nginx
Im deploying my server with nginx inside a GCP Compute Engine. The Application uses django and react. So far the Django Backend API shows allright on my domain.However, I am trying to connect to the React.js I tried : npm run build (build successful) with the following files inside my build folder (asset-manifest.json, index.html, manifest.json. static/css/main.css, static/js/main.js) sudo nano /etc/nginx/sites-available/backend server {server_name domain_name.org; location /api/ { include proxy_params; proxy_pass http://127.0.0.1:8000; } location /static/ { root /home/username/projectname/backend/static/; } location / { root /home/username/projectname/frontend/build/; try_files $uri $uri/ /index.html; } .... some ssl certicates etc .... However, When I restart my nginx server inside the compute engine, I get a blank screen but the bar on top of my browser is stated as "React App" Also When I go to the chrome console-> Network, there are 4 Names domain.org(200) mainfest.json(200) main.js(404) main.css(404) Im not sure why they return status code as 404. Could it also have something to do with my index.html in the react/build having the base template from react instead of my own? <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <link rel="icon" href="/favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="Web site created using create-react-app"/> <link rel="apple-touch-icon" href="/logo192.png"/> <link rel="manifest" … -
django csrf token is not getting set in application cookie when called in a react app using api
I am calling an api in react app using axios which has Set-cookies in response headers but it is not setting the csrf token in cookies storage in application when the api is called it should set the csrf token in cookies storage as csrfToken= -
Model fields not being created in the database
I am creating a project application, in which the users are going to be designated tasks and able to make comments to the project in general. After struggling with no fields fields from the comment model, I am now faced with only one field. So far I have not been able to sort out why this is happening. Any input or clues on where to look for information would be greatly appreciated. class Project(models.Model): project_id = models.CharField( primary_key=True, max_length=50, null=False, blank=False, ) project_owner2 = models.ForeignKey(Entity, on_delete=models.CASCADE, default='916 075 855', #dette er bruker sin organisasjon ) direction = models.CharField( max_length=50, null=True, blank=True, ) title = models.CharField( unique=True, max_length=50, null=False, blank=False, ) scope = models.TextField( verbose_name='Scope', # denne må få nytt navn help_text='Her skal du beskrive prosjektets omfang', max_length=2000, null=True, blank=True, ) project_status_choices = ( ('PLANNED', 'Planned'), ('ACTIVE', 'Active'), ('ON_HOLD', 'On hold'), ('COMPLETED', 'Completed'), ('CANCELLED', 'Cancelled'), ) project_create = models.DateField( verbose_name='Project creation date', help_text='When the project was initiated', null=True, blank=True, ) project_start = models.DateField( verbose_name='Project start date', help_text='Her skal du beskrive prosjektet', null=True, blank=True, ) project_end = models.DateField( verbose_name='Project end date', help_text='Originaly end date', null=True, blank=True, ) class Meta: pass def __str__(self): return self.title` class ProjectComment(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE), pub_date = … -
Django select users groups
How do I use Django's User and Group models to allow the user to select and switch one of their assigned groups forms.py class UserGroupForm(forms.ModelForm): class Meta: model=models.UserGroup fields = [‘group’] def __init__(self, user, *args, **kwargs) super (UserGroupForm, self).__init__(*args, **kwargs) self.fields['group'].queryset = Group.objects.filter (user=user) def clean_role(self): role = self.cleaned_data.get('group’) if role is None: raise forms.ValidationError("Choose role") return role views.py def select_role(request): if request.method == ‘POST’: form = UserGroupForm(request.user, request.POST) if form.is_valid: user_group = for.save(commit=False) user_group.user = request.user user_group.save() return redirect(‘home’) else: form = UserGroupForm(request.user) return render(redirect, ‘select_role.html’, {‘form’:form}) -
Django how to create model tables in a specific schema
So this is the question: Let's say I have 2 schemas in my database: schema1 and schema2 I have a simple user table and a simple car table class User(models.Model) class Meta: db_table = 'user' class Car(models.Model) class Meta: db_table = 'car' I want the user table to be in schema1 And the car table is to be in schema2 How would you guys go about doing this? I saw a post that said I need to specify int he db_table = 'schema_name"."table_name' But that doesn't work. -
How do I clear this base64 error in my django project?
I have tried everything I can, I just can't seem to set up the project on my pc. I'm trying to clone a django project to my local directory. This is the error it keeps giving me when I run 'python manage.py migrate' C:\Users\alame\Desktop\backend_block\tripapi>python manage.py migrate Traceback (most recent call last): File "C:\Users\alame\Desktop\backend_block\tripapi\manage.py", line 23, in <module> main() File "C:\Users\alame\Desktop\backend_block\tripapi\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\__init__.py", line 401, in execute django.setup() File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\alame\Desktop\backend_block\tripapi\account\models.py", line 4, in <module> from utils.base.general import get_name_from_email, send_email File "C:\Users\alame\Desktop\backend_block\tripapi\utils\base\general.py", line 74, in <module> cryptor = Crypthex() File "C:\Users\alame\Desktop\backend_block\tripapi\utils\base\general.py", line 45, in __init__ self.fernet = Fernet(self.key.encode()) File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 33, in __init__ key = base64.urlsafe_b64decode(key) File "C:\Users\alame\AppData\Local\Programs\Python\Python39\lib\base64.py", line 133, in urlsafe_b64decode … -
I have errors by using low-level caching of Django
I’m working on a project with Django and trying to set up the low-level cache it offers. I would like to keep specific context objects in memory so as not to regenerate them each time if it is not necessary. For the moment I have defined the settings as follows: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': BASE_DIR / 'var/tmp/django_cache', } } Then in my view i used this organisation (it's not the real code): def Records(request): #Get cache values or update if not existing (first load or expired) dic_1 = cache.get("dic_1", None) if not dic_1 : dic_1 = generate_dic_1(argA, argB) cache.set('dic_1', dic_1 , 10*60) dic_2 = cache.get("dic_2", None) if not dic_2 : dic_2 = generate_dic_2(argC, argD, argE) cache.set('dic_2', dic_2 , 10*60) #update variables if buttons clicked if request.method == 'POST' and "change_dic_1_button" in request.POST: dic_1 = generate_dic_1(argA, argB) cache.set('dic_1', dic_1 , 10*60) #i want to update dic_1 cache elif request.method == 'POST' and "change_dic_2_button" in request.POST: dic_2 = generate_dic_2(argC, argD, argE) cache.set('dic_2', dic_2 , 10*60) #i want to update dic_2 cache return render(request,"Records\myPage.html", {"dic_1" : dic_1; "dic_2" : dic_2}) From what I see, I do have cache that registers but anytime, not just when I’m on that particular … -
Error: UnboundLocalError at /receptionist/patient_form/ local variable 'username' referenced before assignment
The following code gives the error : UnboundLocalError at /receptionist/patient_form/ local variable 'username' referenced before assignment. Exception Type: UnboundLocalError Exception Value: local variable 'username' referenced before assignment. ` @login_required def createPatient(request): form=PatientForm(request.POST, request.FILES) # try: if request.method == "POST": if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] address = form.cleaned_data['address'] phone_number = form.cleaned_data['phone_number'] dob = form.cleaned_data['dob'] gender = form.cleaned_data['gender'] user = CustomUser.objects.create_user(username=username, email=email,password=password, first_name=first_name, last_name=last_name,user_type=5) user.patients.address = address user.patients.phone_number = phone_number user.patients.dob=dob user.patients.gender=gender user.save() How Can I Fix This ? -
delete() in Django not working as expected
I'm new to Django and query sets. I'm trying to delete a column when user press delete button. I have user model and usecase_assign and I'm trying to execute this method logic: DELETE FROM usecase_assign WHERE usecase_assign.user_email = 'name of user'; I'm getting with my attempt "user was deleted successfully" while it's not deleted. My usecase_assign model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) if request.method=='POST' and 'delete_user' in request.POST: users = User.objects.filter(user_email=request.user) assigned_user = UsecaseAssign.objects.filter(usecase_assign_date__in=users).delete() if assigned_user: messages.success(request, "user was deleted successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) my template: <label class="mb-card h5" for="user_email">Assigned users:</label> {% for user in usecase_assigned %} <form action="/usecase-details/{{result.usecase_id}}" method="POST" style="display: inline !important;"> {% csrf_token %} <div class="btn-group me-2 mb-2"> <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button> <button type="submit" class="btn btn-danger" name="delete_user"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-x-fill" viewBox="0 0 16 16"> <path d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.854 6.146 8 7.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 8l1.147 1.146a.5.5 0 0 1-.708.708L8 8.707 6.854 9.854a.5.5 0 0 1-.708-.708L7.293 8 6.146 6.854a.5.5 0 1 1 … -
Websocket connection disconnects just after handshake
WebSocket HANDSHAKING /ws/ [127.0.0.1:54395] WebSocket DISCONNECT /ws/ [127.0.0.1:54395] My websockets gets disconnected after handshaking. Please suggest a solution or a tutorial that can be followed to implement a basic chat functionality using channels in django. My Code: class Experience(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) pass websocket_urlpatterns = [ path(r'ws/chat/(?P<room_name>\w+)/$', Experience.as_asgi()), ] application = ProtocolTypeRouter({ 'http': asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns )), # new }) CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } My websockets gets disconnected after handshaking. Please suggest a solution or a tutorial that can be followed to implement a basic chat functionality using channels in django. -
NoSuchKey error while using digitalocean spaces and django-filebrowser-no-grappelli
I'm using django-filebrowser with DigitalOcean Spaces as the storage backend for my Django project. When I try to access the filebrowser URL to browse the files, I get the following error: NoSuchKey at /admin/filebrowser/browse/ An error occurred (NoSuchKey) when calling the ListObjects operation: Unknown I'm not sure what's causing this error and how to fix it. I've already checked the bucket name, region name, and permissions, but the error still persists. Here are some more details about my configuration: I'm using django-filebrowser version 3.12.2 and django-storages version 1.11.1. I have to set up the DEFAULT_FILE_STORAGE setting in my Django settings file to use custom-made storage class: import os from filebrowser.storage import S3BotoStorageMixin from storages.backends.s3boto3 import S3Boto3Storage class MyStorage(S3Boto3Storage, S3BotoStorageMixin): def _clean_name(self, name): return os.path.join("", os.path.normpath(name).replace('\\', '/')) def isdir(self, name): return name.endswith('/') I've set up the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_STORAGE_BUCKET_NAME, AWS_S3_REGION_NAME, and AWS_S3_ENDPOINT_URL settings in my Django settings file to configure the S3 connection to DigitalOcean Spaces. I've granted the s3:ListBucket and s3:GetObject permissions to the IAM user that I'm using to access the bucket (file uploading from admin panel is working fine) I've set up the MEDIA_URL setting in my Django settings file to point to the public URL of the … -
Django AttributeError: type object 'Admin' has no attribute '_meta' error when creating custom user
I'm learning django and I want to have my custom user and admin object but I'm encountering an error when running server after applying my changes. I'm not sure if this is the right approach to do this so do enlighten me if I'm following the wrong approach. So I have created an app called 'core' where I want to do authentication stuff so that's where I've put my custom user models. Here are the files I've written for that task so far: models.py: from django.db import models from store.models import CartItem from django.contrib.auth.models import AbstractBaseUser, UserManager from enum import Enum from django_countries.fields import CountryField from django.contrib import admin ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) class AuthLevel(Enum): NONE = 0 Customer = 1 Admin = 2 Programmer = 3 class Address(models.Model): street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) zip = models.CharField(max_length=100) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) def __str__(self): return self.street_address.name + " " + self.apartment_address.name class Meta: verbose_name_plural = 'Addresses' class BaseUser(AbstractBaseUser): name = models.CharField(max_length=100, unique=True) auth_level = AuthLevel.NONE class Customer(AbstractBaseUser): username = models.CharField(max_length=100, unique=True) email = models.EmailField() address = models.OneToOneField(Address, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) one_click_purchasing = models.BooleanField(default=False) cart = models.ManyToManyField(CartItem) #on_delete=models.CASCADE) … -
tmp file write pdf file google app engine django
I am using fpdf package for creating PDF in django. My file structure is project - contain all the setting files. apps - contain all the apps folders like apps/account/views.py apps/profile/views.py static - static files templage - all the template tmp class PdfCreater(View): def get(self, request, *args, **kwargs): pdf = FPDF('P', 'mm', 'Letter') pdf.add_page() pdf.set_font('helvetica', 'BIU', 16) pdf.set_text_color(220,50,50) pdf.cell(100, 80, 'Hello World jaskaran singh!' ) pdf.set_font('times', '', 12) pdf.cell(80, 10, 'Good Bye World!') path = str(settings.XYZ) pdf.output( path+ '/tmp/pdf_2.pdf') data = 'try' return JsonResponse({"data": str(path), "header": data}) now i am wring this code but my pdf_2.pdf file is not create in tmp folder why? In my localhost file has been create successfully but not in google app engine -
Adding Path Prefix for Django
I am using Digital Ocean's app platform so I don't really have access to an Nginx instance as they handle the routing etc. on their end. I have a frontend React app at: http://subdomain.domain.com And I have the backend Django app at: http://subdomain.domain.com/backend The Django app wasn't designed to have the leading prefix, so admin and site URLs look like this locally: http://0.0.0.0:8000/dashboard/sign-in http://0.0.0.0:8000/admin/login/ My URLs look like: urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include(('dashboard.urls', 'dashboard'))), path('', include(('core.urls', 'core'))) ] When I visit the dashboard URLs, for example: http://subdomain.domain.com/backend/dashboard/home It works fine. I had to modify some of the redirects so that it would redirect to the right URL in the code, but it works fine. My issue is with the Django admin. When I manually visit lets say: http://subdomain.domain.com/backend/admin/login/ It will load the login View, but when I login/submit the form, it posts to the URL without the backend prefix. Also, if I login using my own form then navigate to the admin site, all of the links look absolute like: <a href="/admin/whatever"><a/> so when I click them it won't work. I looked into FORCE_SCRIPT_NAME, but when I use that and set it to something like backend it just … -
Not Found: /users/
I keep getting this error even though I have pathed it correctly. Can someone help me? Thanks. this is my form action url form method="post" action="/users/" id="archive-form" this is my javascript fetch url fetch("/users/", { this is my urls.py path url path("users/", views.users, name="users"), this is my views.py def users(request): active_users = User.objects.filter(status='active') archive_users = User.objects.filter(status='archived') user_form = UserForm() if request.method == 'POST': user_form = UserForm(request.POST, request.FILES) if user_form.is_valid(): user = user_form.save(commit=False) user.save() # log_message = f"Added user with ID {user.id}" Log.objects.create(user=user.first_name, role=user.job_title, date=timezone.now(), action=log_message) # return redirect('app:users') print('1') user_id = request.POST.get('user_id') user = get_object_or_404(User, id=user_id) if user: if user.status == 'active': user.status = 'archived' log_message = f"Archived user with ID {user_id}" elif user.status == 'archived': user.status = 'active' log_message = f"Unarchived user with ID {user_id}" user.save() Log.objects.create(user=user.first_name, role=user.job_title, date=timezone.now(), action=log_message) return redirect('app:users') -
Django custom login form does not validate
I have implemented a custom user model in my django project. I can use it to register a user however I cannot use it to login. It fails to validate against the is_valid() function. I have been able to confirm the email & password values are being passed through to views.py but the form is not being validated Here is my login view code def login_view(request): context = {} if request.POST: form = UserLoginForm(data = request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] print(email) print(password) user = authenticate(request, email=email,password=password) print(user) if user is not None: login(request,user) return redirect("logistics:dashboard") else: print('form not valid') form = UserLoginForm() context["loginform"] = form return render(request, 'dashboard/authentication-login.html', context) This is login form code class UserLoginForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } def clean(self): if self.is_valid(): email = self.clean_data['email'] pasword = self.clean_data['password'] if not authenticate(email=email, pasword=pasword): raise forms.ValidationError("Invalid Credentials") This is my custom user model class CustomAccountManager(BaseUserManager): def create_superuser(self,email, user_name, first_name, last_name, phone, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: … -
QR scanner does not show in dialog box pop out
Using vue.js and element-ui html, I have a table of records, which after clicking on the row, there is supposed to be a QR scanner dialog box pop out. Right now, the the dialog box does pop out upon clicking a row on the table but the QR scanner does not appear. I have tried many methods but it still does not seem to work. Hope someone can advice me on this. Thank you. <doctor_emr.html> {% load static %} {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table :data="list" @row-click="showQRScanner"> <el-table-column prop="id" label="ID"></el-table-column> <el-table-column prop="order_id" label="Order ID"></el-table-column> <el-table-column prop="ward_number" label="Ward Number"></el-table-column> </el-table> <el-dialog :visible.sync="qrDialogVisible"> <div id="qr-scanner-container" ref="scannerContainer"></div> <div slot="footer"> <el-button @click="qrDialogVisible = false">Cancel</el-button> </div> </el-dialog> </div> </div> {% endverbatim %} <script src="{% static 'js/vue.min.js' %}"></script> <script src="{% static 'js/axios.min.js' %}"></script> <script src="{% static 'js/qr-scanner.min.js' %}"></script> <script src="{% static 'js/qr-scanner-worker.min.js' %}"></script> <script> new Vue({ el: '#app2', data() { return { list: [], qrDialogVisible: false, selectedRow: null } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, showQRScanner(row) { this.selectedRow = row; this.qrDialogVisible … -
How to send response json from celery to my view Django
I want to use request_cache from 3rd party API and im looking for way to synch that every 5 minutes and if API is not responding or it got errors i want to use last json which i got from requests_cache I actually want to use celery for mb synch my request every 5 minutes and update that request but is this right way to do that? Or i just need to use expire_after in my view and i dont need to use celery Any solutions how can i do that? views.py def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') session = requests_cache.CachedSession('project_budget_cache') response = session.get(url, auth=UNICA_AUTH) session.settings.expire_after = 300 # Im not sure if its right decision