Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App (Front end and Backend) in Docker Container - Advice Needed [closed]
I have a Django App that uses a Postgres SQL backend. The front end is simply css/html/js/jquery with jinga. I think it would be wise to containerise the App. Should I containerise both front end - Django and the database in 1 container? Let's say I make a container for the database - would that not slow down the behaviour of the database? What advantages would I get in containerising a postgresSQL database? -
How can i Formatting a date field in a ModelForm to dd/mm/yy in Django?
In my project settings.py i try this : USE_L10N = False DATE_INPUT_FORMATS = ['%d/%m/%Y'] In my models.py i try this : from django.db import models from django.conf import settings class PersonalInfo(models.Model): Married_Status = ( ("1", "Married"), ("2", "Unmarried"), ) Name = models.CharField(max_length=50) Age = models.IntegerField() Married_Status = models.CharField(max_length=10, choices=Married_Status, default="Unmarried") Birth_Date = models.DateField(input_formats=settings.DATE_INPUT_FORMATS) It's show a error "TypeError: init() got an unexpected keyword argument 'input_formats'" I read django document and other stackoverflow question answer but i could not understand. I want input from user like : 17/03/1998 I'm a noob to python and Django so any help would be greatly appreciated. -
Foreign key to user in central authtentication system
I have used a central authentication system for my Django projects (micro-service architecture). In one of my services, I should save user as a foreign key in model. class Group(models.Model): name = models.CharField(max_length=63, null=True, blank=False) owner = models.CharField(max_length=127, blank=True) class GroupAccess(models.Model): group = models.ForeignKey(Group, null=True, blank=False, related_name='accesses') username = models.CharField(max_length=127, null=True, blank=False) As I'm using CAS I don't have auth user model. How can I limit GroupAccess form in django admin to choose only available usernames in the cas? -
can Django serialize a Json with unknown lists and dicts?
I have a Json file that I receive and I would like to serialize it using Django. However, I do not always know what fields will be included in the Json. Some of these Json files will include noted lists and nested dicts. Is there a way to use Django serializer in order to serialize all of the fields or do I have to specify each field name as well as the type of object that it is? -
AttributeError: 'ExampleView' object has no attribute 'data' django rest framework
I have to write a custom function inside class based view which is like below. class ExampleView(ListCreateAPIView, DestroyAPIView, RetrieveUpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer def dispatch(self, request, *args, **kwargs): if request.method == 'PUT' and kwargs.get('slug'): return self.custom_function(request,*args,**kwargs) return super().dispatch(request, *args, **kwargs) def custom_function(self, request, *args, **kwargs): instance = self.get_object() print(instance) slug = kwargs.get("slug") print(slug) print(request.data) Here I can see that from dispatch, the custom function is called and I can see the print of instance and slug but when I print(request.data) it says the error below: AttributeError: 'ExampleView' object has no attribute 'data' I need request.data to perform some logic in the data. -
query.alias_map empty when trying to join to queryset
I've created a custom join that I'm attempting to join back onto a queryset to perform a 'full join' to a subquery. The SQL I'm attempting to generate looks something like this: select * from foo full join (some subquery goes here) as bar on bar.x = foo.x and I've created a method for creating a custom join an the SQL required for this. def join_to_subquery_with_function(table, function_model, table_field, function_field, queryset, alias, table_function_params): foreign_object = ForeignObject(to=function_model, on_delete=DO_NOTHING, from_fields=[None], to_fields=[None], rel=None) foreign_object.opts = Options(table._meta) foreign_object.opts.model = table foreign_object.get_joining_columns = lambda: ((table_field, function_field),) # Create the join and manually apply it to the queryset join = TableToSubqueryFunctionJoin( function_model._meta.db_table, table._meta.db_table, alias, "FULL JOIN", foreign_object, True, table_function_params=table_function_params, queryset=queryset) # Prepare the alias for join queryset.query.alias_map[alias] = alias join.table_alias = alias queryset.query.external_aliases[alias] = alias queryset.query.join(join) return queryset and TableToSubqueryFunctionJoin class that is used to generate the join looks like: class TableToSubqueryFunctionJoin(Join): def init(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params=None, queryset=None): super().init(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params self.queryset = queryset def as_sql(self, compiler, connection): for (lhs_col, rhs_col) in self.join_cols: on_clause_sql = '{}.{} = {}.{}'.format( self.parent_alias, lhs_col, self.table_alias, rhs_col, ) function_placeholders = '%s::date, %s::date, %s::interval' resolved_params = [] for param in self.table_function_params: … -
Django - combining multiple models into the same form class
Is there a way of combining multiple models in the same form class in the form.py file. Right now I have three Models, and have to create three separate form classes in the form.py file using forms.Modelform for each form class. I define the model for each form class in the Meta tag, Something like: class Form1(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Model 1 class Form2(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Model 2 class Form3(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Model 3 Then I have to combine all three forms (a selection of fields from each Model), in the HTML template, so there is only one submit button. Then I have to make sure I save each of the 3 forms, in the view.py file, so that things get saved from hitting one submit button Question Is there not a way of combining models into one form class to begin with in the form.py file? It would make the coding upstream in the view, and html template a lot easier, more compact and less repititious! Also all the error checks would be in one place. -
No module named 'django.core.context_processors' while I didn't use it anywhere
This is my Views.py from django.shortcuts import render from .models import * def photoeditapp (request): if request.method == 'POST': imgmdl = ImageEditModel() img = request.FILES.get('img') imgmdl.imagename = 'sample1' imgmdl.image = img imgmdl.save() return render(request, 'photoedit.html') Templates in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.csrf', ], }, }, ] ERROR while running the server ModuleNotFoundError at /photoedit/ No module named 'django.core.context_processors' urls.py of the app urlpatterns = [ path('photoedit/', views.photoeditapp, name='photoedit'), ] I didn't use django.core.context_processors but it is till giving the error -
View Django MySQL tables within MySQL Workbench
I was trying to view a MySQLvtable I created in Django, from within MySQL Workbench I have all the default tables within MySQL, and I can see them all on workbench, however the new created tables (created within the Django shell) do not appear. Any help? -
Where is `USERNAME_FIELD` defined in Django source code?
I found below in Django source code class AbstractBaseUser(models.Model): ... def get_username(self): """Return the username for this User.""" return getattr(self, self.USERNAME_FIELD) ... I searched out the whole Django source code, but did not find out where the USERNAME_FIELD was defined. Can anyone help on this please ? -
How Notify Current user ,your insurance is going expiry within 5 days in django
I am stuck in one problem and i want to notify current logged user for it's insurance will be expired within 5 days ago. class Vehicle(models.Model): vehicle_no = models.CharField(max_length=100, blank=False, null=False) chasis_no = models.CharField(max_length=100, blank=False, null=False, unique=True) make = models.CharField(max_length=100, blank=False, null=False) insurance_no = models.CharField(max_length=100, blank=False, null=False) insurance_date = models.DateField(blank=False, null=False) insurance_expiry_date = models.DateField(blank=False, null=False) Please help me to find exact solution -
How to group permissions for some models?
I have today 2 models: Image Video These models have their own permissions ("Can add Image", "Can add Video", etc ...) I would like to make a permission that combines both. For example: I want to create the permission "Can add Media". And If I add the permission "Can add Media" to an user, he can add Image or Video. -
Django Error: Email sends with the HTML code instead of showing the template
Hey guys I am trying to send an email with html template via django, I am facing this issue as the email shows html code instead of the template. I am confused about what to do next. Can anyone let me know the issue with the code. I have my email setup with Office365. @app.task(name="account_opening_email") def account_opening_email(email): """ Method to send account opening email :argument 1) email """ try: user = Account.objects.get(email=email) subject = "Signup Successful" html_msg = render_to_string('accounts/Welcome email.html', context={"username": user.first_name}) plain_msg = strip_tags(html_msg) from_email = settings.EMAIL_HOST_USER to_email = [user.email] msg = EmailMultiAlternatives(subject=subject, body=plain_msg, from_email=from_email, to=to_email) msg.attach_alternative(html_msg, "text/html") msg.content_subtype = 'html' msg.mixed_subtype = 'related' try: for i in range(1, 11): img_path = settings.STATIC_ROOT + f'/images/image-{i}.png' image_name = Path(img_path).name with open(img_path, 'rb') as f: image = MIMEImage(f.read()) msg.attach(image) image.add_header('Content-ID', f"<{image_name}>") except: pass msg.send() logger.info("Email Send") except: logger.exception("Failed") Thank you. -
Django - Postgresql - JSON Field - #>> operator - Index of out range
In a django project which is using postgresql DB, there is a collection called 'table1' which has a JSON field called 'data'. In this JSON field, we will be storing an email against a dynamic key. For ex: ID | DATA 1 | '{"0_email": "user1@mail.com"}' 2 | '{"3_email": "user2@mail.com"}' 3 | '{"1_email": "user3@mail.com"}' Problem Statement: Filter out the rows in which "user2@mail.com" exists in the "data" field. My Approach: from django.db import connection @transaction.atomic def run(given_email): with connection.cursor() as crsr: crsr.execute( """ DECLARE mycursor CURSOR FOR SELECT id, data FROM table1 WHERE data #>> '{}' like '%\"%s\"%' """, [given_email] ) while True: crsr.execute("FETCH 10 FROM mycursor") chunk = crsr.fetchall() # DO SOME OPERATIONS... Explanation for data #>> '{}' like '%\"%s\"%': I am using the #>> operator to get object at specific path of JSON as text. I am providing '{}' empty path so that I will get the complete JSON as a text. From this stringified JSON, I am checking if the given_email (user2@mail.com from the above example) is present Then, I have pointed this function to a API in django in which I will get the given_email in payload. I am facing the below error which triggering this function: … -
django special multitenancy with keycloak
i am planning a web application with multiple tenants (or i call it companies). Every model in django has a foreign key to a specific company, to separate the data. It is possible that a user has access to multiple companies. You can see this in the following diagram: The user can login over a login page and then the user sees all companies he related to. Now he can choose one of the company to work with the data. Up to this point i have no problem. Some of the companies would like to use their own active directory or other systems to synchronize theirs users with my web application and authenticate them. I found keycloak during my search and it looks like good for my plan because i also would like to split my web application in smaller services in a kubernetes cluster. But i can't find informations about if keycloak work with my plan and the requirement for linking multiple active directories or other systems. I think keycloak would have to check the username (email address) and decide from the domain if an external service is configured for the domain or the normal login page is used. … -
Override specific field __get__ on model instance in Django
I'm trying to temporarily monkey-patch the request.user to change its behavior (in my case, I need to warn developers that the field is deprecated or raise an exception) I have a middleware like this: def middleware(request: HttpRequest) -> HttpResponse: if request.user.is_authenticated and request.user.patient is not None: def _get_patient(): raise SomeAPIError() # or return value with warning request.user.patient = _get_patient response = get_response(request) return response return middleware The problem is that, of course, Django doesn't let me to do this so straightforward. I understand that patient property here is a descriptor, and I want to override its __get__ method, but I don't know how. -
How does this ".set() thing work in generic relations in django? If I want to create an object using python shell
Here are my models User, Business has the generic relation with Deposit class Deposit(BaseModel): amount = models.IntegerField(default=0, blank=False) # set up generic foreign keys content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() depositor = GenericForeignKey() def __str__(self): return "%s %s made by %s" % (self.amount, self.deposit_type, self.depositor) class User(AbstractUser, BaseModelMixin): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) employers = models.ManyToManyField(Business, through="Employment") address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE) email = models.EmailField("Email Address", blank=True, unique=True) deposits = GenericRelation("Deposit", related_query_name="user") class Business(BaseModel): name = models.CharField(max_length=255) tax_id = models.CharField(max_length=255, blank=True, default="") contact_email = models.CharField(max_length=255) contact_first_name = models.CharField(max_length=255) contact_last_name = models.CharField(max_length=255) contact_phone = models.CharField(max_length=255, blank=True, default="") description = models.TextField(blank=True, default="") address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE) deposits = GenericRelation("Deposit", related_query_name="business") when I create a Deposit object using Python shell business = Business.objects.get(pk=1) deposits= Deposit.objects.create(business=business, amount=50) I get this error TypeError: Direct assignment to the reverse side of a related set is prohibited. Use business.set() instead. How to resolve this issue? -
Running multiple django apps in apache https server one in / and another in /app2
I am trying to deploy two django apps in same server ssl port 443. While I comment following three lines in first block app2 is running while commenting in second block app1 is running and when uncommenting in both block both apps is not running and showing Internal Server Error and apache error log showing "mod_wsgi (pid=48352): Failed to exec Python script file '/var/www/html/app1/app1/wsgi.py'." WSGIDaemonProcess ...... WSGIProcessGroup ...... WSGIScriptAlias ...... *my default.conf file VirtualHost :443 block is as follows Alias /static /var/www/html/app1/static <Directory /var/www/html/app1/static> Require all granted </Directory> <Directory /var/www/html/app1/app1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app1 python-path=/var/www/html/app1 WSGIProcessGroup app1 WSGIScriptAlias / /var/www/html/app1/app1/wsgi.py ######################################################################################## Alias /museum/static /var/www/html/app2/static <Directory /var/www/html/app2/static> Require all granted </Directory> <Directory /var/www/html/app2/app2> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess app2 python-path=/var/www/html/app2 #WSGIProcessGroup app2 #WSGIScriptAlias /app2 /var/www/html/app2/app2/wsgi.py for the above code app1 is running perfectly Alias /static /var/www/html/app1/static <Directory /var/www/html/app1/static> Require all granted </Directory> <Directory /var/www/html/app1/app1> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess app1 python-path=/var/www/html/app1 #WSGIProcessGroup app1 #WSGIScriptAlias / /var/www/html/app1/app1/wsgi.py ######################################################################################## Alias /museum/static /var/www/html/app2/static <Directory /var/www/html/app2/static> Require all granted </Directory> <Directory /var/www/html/app2/app2> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app2 python-path=/var/www/html/app2 WSGIProcessGroup app2 WSGIScriptAlias /app2 /var/www/html/app2/app2/wsgi.py for the above code app2 is running … -
Azure-pipelines: No module named "xmlrunner"
There seem to be many "No module names..." on Azure Pipelines issues in Stackoverflow... and now, as none of them helped me, it's my turn :( This is the pipeline I'm trying to run: a simple CI to test my Django app, based on Microsoft's own template: trigger: - master pool: vmImage: ubuntu-latest strategy: matrix: Python310: PYTHON_VERSION: '3.10' maxParallel: 2 steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(PYTHON_VERSION)' architecture: 'x64' - task: DownloadSecureFile@1 name: dotEnv inputs: secureFile: 'uploaded.env' - task: PythonScript@0 displayName: 'Export project path' inputs: scriptSource: 'inline' script: | """Search all subdirectories for `manage.py`.""" from glob import iglob from os import path # Python >= 3.5 manage_py = next(iglob(path.join('**', 'manage.py'), recursive=True), None) if not manage_py: raise SystemExit('Could not find a Django project') project_location = path.dirname(path.abspath(manage_py)) print('Found Django project in', project_location) print('##vso[task.setvariable variable=projectRoot]{}'.format(project_location)) - task: CopyFiles@2 displayName: 'Add .env file' inputs: SourceFolder: '$(Agent.TempDirectory)' Contents: 'uploaded.env' TargetFolder: '$(projectRoot)' - script: mv uploaded.env .env displayName: 'Rename .env file' - script: | python -m pip install --upgrade pip setuptools wheel python -m pip install poetry python -m pip install unittest-xml-reporting xmlrunner poetry install displayName: 'Install dependencies' - script: | pushd '$(projectRoot)' poetry run python manage.py test --testrunner xmlrunner.extra.djangotestrunner.XMLTestRunner --no-input poetry run coverage xml displayName: … -
Django FileField with custom storage still uploads to default storage (GoogleCloudStorage)
I want to upload files to custom storage, other than the one for static. But each time when i try to declare a custom google cloud storage bucket, it still refers to the bucket related to statics (probably to the default storage) I am trying to Declare a new class from wagtail's AbstractDocument class class VirtualVisitDocs(AbstractDocument): file = models.FileField(storage=CustomGoogleCloudStorage(), verbose_name=_('file')) Then using it as a foreign key for another wagtail page with document chooserpanel as follows: virtual_visit = models.ForeignKey( VirtualVisitDocs, on_delete=models.SET_NULL, verbose_name=_('Virtual Visit Zip File'), related_name='promotion_pages', null=True, blank=True, ) MultiFieldPanel( [ DocumentChooserPanel("virtual_visit"), ], heading=_("Virtual Visit"), classname="collapsible collapsed", ), The storage instance from above CustomGoogleCloudStorage is the one which I have declared as follows: @deconstructible class CustomGoogleCloudStorage(GoogleCloudStorage): def get_default_settings(self): default_settings = super().get_default_settings() default_settings['bucket_name'] = settings.GS_VIRTUAL_TOUR_BUCKET_NAME default_settings['project_id'] = settings.GS_VIRTUAL_PROJECT_ID return default_settings Each time I try to upload documents this way, I get HTTP 403 which is correct, cause the service account I am using is not allowed to make changes on the default bucket. Rather, I want files to be uploaded to the second bucket where my service account is allowed to create bucket instance objects, but I just can't point to that another bucket. Whenever I try to print custom CustomGoogleCloudStorage … -
How do I fill in the ProcessedImageField after saving the original image?
How do I fill in the ProcessedImageField after saving the original image? I tried to override the save method, smth like this: class A(models.Model): original = models.ImageField() webp_1x = ProcessedImageField(format='WEBP', processors=[ResizeToFit(320, 320), null=True, blank=True) webp_2x = ProcessedImageField(format='WEBP', processors=[ResizeToFit(640, 640)], null=True, blank=True) def save(self, *args, **kwargs): self.webp_1x = self.original self.webp_2x = self.original super().save(*args, **kwargs) But it doesn't work. Unfortunately, there is no argument source in ProcessedImageField -
How can I use 2 websocket in same page?
I am developing a django project and in chat page you can send message other people using websockets but in the same page I want to use webRTC to make video call but in asgi.py how can I define 2 different websocket or is there a better way to solve this problem. asgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_asgi_application() ws_pattern = [] application = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack(URLRouter( chat.routing.websocket_urlpatterns )) }) application2 = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack(URLRouter( call.routing.websocket_urlpatterns )) }) chat.roting: websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer.as_asgi(),name="websocketreconnect"), ] call.routing: websocket_urlpatterns = [ re_path(r'ws/call/', consumers.CallConsumer.as_asgi()), ] -
How do i modify my create function in Django model manager
So i have this model: class Token(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) code = models.IntegerField(default=code) date_created = models.DateTimeField(auto_now_add=True) expiration_date = models.DateTimeField(null=False, blank=True) as you can see I have an expiration_date field. The reason why I set it to (null=False, blank=True) is because I want it to fill itself based of the date_created field, and I'm trying to do that from the model manager create method I have little to no experience in model manager outside of custom user model manager. Here's my first failed attempt: class TokenManager(models.Manager): def create(self, user, code, date_created): exp = date_created + datetime.timedelta(minutes=10) token = self.model(user=user, code=code, date_created=date_created, expiration_date=exp) token.save() return token basically my goal here is to get the value of date_created field, add the value by 10 minutes and set it as the expiration_date. can anyone help me with this? -
Django: set DEBUG = False causes Server Error (500)
the templats work when DEBUG = True but change to False gives Server Error (500) i used django 3.2.8 This is views.py file def test(request): context = {} if request.method == "POST": uploaded_file = request.FILES['document'] print(uploaded_file) if uploaded_file.name.endswith('.csv'): #save file in media folder savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) #name of the file #know where to save file d = os.getcwd() #current directory of the project file_directory = d + '\media\\' + name readfile(file_directory) return redirect(results) else: messages.warning(request, 'File was not uploaded. Please use csv or xlsx file extension!') return render(request, 'test.html', {}) #project.csv def readfile(filename): global rows, columns, data, my_file, missing_values, mydict, dhead, dtail, dinfo, ddesc, dcor, graph, dheat my_file = pd.read_csv(filename, engine='python', index_col = False, sep='[: ; , | -]', error_bad_lines=False) data = pd.DataFrame(data=my_file) #my_file= read_file(filename) data = pd.DataFrame(data=my_file) mydict = { "data ": data.to_html(), } #rows and columns rows = len(data.axes[0]) columns = len(data.axes[1]) #find missing data missingsings = ['?','0','--'] null_data = data[data.isnull().any(axis=1)] missing_values = len(null_data) def results(request): message = 'I found ' + str(rows) + ' rows and ' + str(columns) + ' columns. Missing data are: ' + str(missing_values) #message = info messages.warning(request, message) return render(request, 'results.html', context = mydict) This is settings.py file … -
WebSocket like grouping for Server Sent Events in Django
I have a Django website and I have a real-time "game" on it. Multiple people connect and play it. Every x seconds the users in the specific game will be getting updates. I have done this using WebSockets and it works, I would say, pretty good. The things I think that using WebSocket-s is an overkill, plus I'm not utilising the Bi-directional part of it, rather using it to get the updates from the server and using AJAX to send the data. I'm considering switching over to Server Sent Events. I've used it a bit and read about it online and have decided that it would be a good fit for my project (using it instead of WS). The "problem" that I have is that I'm not sure how to (I assume its possible) use something like a groups in ws. I've searched online and the best solution that I could find is doing the client side filtering, which although its totally fine, I do not prefer as I think it's a waste of resources. The way that I have it set up is that based on the url for the game, the users that are connecting would be placed …