Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model property depended on request.session value
My models have validation_range field. Very complex. For simplicity I will show example - it may looks stupid but this is for explanation only - so don't look at the model itself, please class Person(models.Model): validity_range=DateTimeRangeField(default=(None,None)) class PersonData(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) first_name = models.CharField(max_length=255) last_name =models.CharField(max_length=255) validity_range=DateTimeRangeField(default=(None,None)) And now Person can have a two names: E.g. Miss Eva Smith born 1.1.1980 gets married 22.03.2022 and becomes Mrs. Eva Novak. (for simplicity I omit time part of validity_range) So datas look like: Person{id:1,validity_range:(1980-01-01,None)} PersonData{id:1,person_id:1,first_name:'Eva',last_name:'Smith',validity_range:[1980-01-01,2022-03-22)} PersonData{id:2,person_id:1,first_name:'Eva',last_name:'Novak',validity_range:[2022-03-22,None)} I preserve context_date in request.session['context_date']. And I will show Eva's full name dependent of request.session['context_date'] def index(request): person = Person.objects.get(pk=1) context ={ 'person' : person, 'context_date' : request.session.get('context_date') } html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) html: Context_date is: {{ context_date }} At that date Person no {{ person.id }} was called {{ person.person_data.first_name }} {{ person.person_data.last_name }} Of course this is wrong, because person_data is a set not a object. I thought to make a property in model: class Person(models.Model): validity_range=DateTimeRangeField(default=(None,None)) @property def first_name(self, date): try: person_data =PersonData.objects.get(validation_range__contains=date) #We can assume, that validation_ranges don't overlaps (database constraint) return person_data.first_name except PersonData.DoesNotExist: return None #oups - there's no persondata in that date! But how pass parameter … -
Partitioned tables in psql with django
I partitioned a table in Postgres with Django. All was fine, the insertion went good but when I try to make a query the response is just a field from the original table. So my question is: How is right way to make query in partitioned table in Django? -
Simple blog django application deployed using Heroku/PostgreSQL database utilizing Tinymce image plugin for textarea - Not Working
I followed these simple instructions to replace a text area in django with an HTMLField from tinymce. You simply install tinymce and add it to installed apps in your settings file and then import tinymce in your models file and use the HTMLField() where appropriate. https://www.youtube.com/watch?v=qUOPn5xi0oA My text area is editable as expected using tinymce. However, I wanted to add the capability to add pictures to the blog post (this is mentioned in the second half of the video). When I follow these instructions my editable textarea does not include a file uploader option. https://www.tiny.cloud/docs/plugins/opensource/image/ JS snippet I copied from tinymce: <script> tinymce.init({ selector: 'textarea#file-picker', plugins: 'image code', toolbar: 'undo redo | link image | code', /* enable title field in the Image dialog*/ image_title: true, /* enable automatic uploads of images represented by blob or data URIs*/ automatic_uploads: true, /* URL of our upload handler (for more details check: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url) images_upload_url: 'postAcceptor.php', here we add custom filepicker only to Image dialog */ file_picker_types: 'image', /* and here's our custom image picker*/ file_picker_callback: function (cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); /* Note: In modern browsers input[type="file"] is functional without even adding it to the … -
Cannot resolve keyword 'tag' into field. Choices are: author, author_id, category_id, category_id_id, created_date, id
I want to navigate through tags, but it gives me an error. "Cannot resolve keyword 'tag' into field. Choices are: author, author_id, category_id, category_id_id, created_date, id, id_published, image, likes, published_date, tagged_items, tags, text, title" models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Автор') title = models.CharField(max_length=222, verbose_name='Заголовок') tags = TaggableManager() objects = models.Manager() # The default manager published = PublishedManager() # Custom manager def get_absolute_url(self): return reverse('new_detail', kwargs={'pk': self.pk}) views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'main/list.html', {'page': page, 'posts': posts, 'tag': tag}) urls.py urlpatterns = [ re_path(r'^$', views.post_list, name='post_list'), re_path(r'^tag/(?P<tag_slug>[-\w]*)/$', views.post_list, name='post_list_by_tag'), ] index.html <p class="tags"> Tags: {% for tag in news.tags.all %} <a href="{% url 'post_list_by_tag' tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> list.html ` {% … -
Upgrading dependencies while upgrading django
so I've been tasked with upgrading a fairly large Django project with multiple apps and over 60 dependencies... the app is also a fairly old 2.0 version of Django. For the most part, I know what the main code refactors I'll have to make in terms of the actual Django code but upgrading third-party packages is what's worrying me.. its been a bit difficult to find if those packages are compatible with newer versions of Django and so I'm not sure whether to upgrade the dependencies or not. I'd appreciate any help on this process if someone has attempted it before and what they would reccomend. -
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