Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django view function is not executing in asgi mode
I am using django development environment to develope an app while trying to execute view function i am getting raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. i have configured the django app using asgi mode and running the daphne via command daphne myproject.asgi:application. there is a signup form in my app where user put his name,company_id,email as username and password. i want to store the username,password in user model and the company_id against that user in userprofile model. signup view is failing to execute the django orm queries and i am unable to store the data as expected. ``` async def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = user.username user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.save() customer_id = request.POST.get('customer_Id') # Get the customer_id from the form print(customer_id) try: customer = await sync_to_async(Customer.objects.get)(customer_id=customer_id) except Customer.DoesNotExist: return render(request, 'core/signup.html', {'form': form, 'error_message': 'NA'}) userprofile = await sync_to_async(Userprofile.objects.create)(user=user, customer=customer) await sync_to_async(userprofile.save)() await sync_to_async(login)(request, user) # Using sync_to_async for login return redirect('landingpage') else: form = UserCreationForm() return render(request, 'core/signup.html', {'form': form}) ``` -
How can I move data from one model to another with Django/python?
basically i have trhee models where the information of user is already there, but i created a third model called License user, so that i can move the information to that model, how can i do that in an efficient way? Model 1 class License1(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) Model 2 class License2(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) User Model class UserLicense(models.Model): """User information model.""" user_name = models.CharField(max_length=40, blank=False, null=False, unique=True) full_name = models.CharField(max_length=80, blank=False, null=False, unique=True) email = models.TextField(blank=False, null=False) I'm usign db.sqlite3, if anyone can explain the process i would be really grateful -
Running R code in Python using rpy2 - Kernel dying
I want to run a R code in my pythons jupyter notebook, My plan is to run the model with both R code and python combined in Django server to publish the ML model(I myself din't make the model so I dont know anything about it). People who made the ML model have used both python varaibles in R code and R varibles in python code. So it would be better if I have all of the programs in a single django server. Due to which I want to run the R code in my python jupyter notebook as the first step. I came accros rpy2 and tried using rpy2 for this. But whenever I try to import something from rpy2 my kernel just dies I just did "pip install rpy2" as suggested to install rpy2. Do I need to set a path like this to for the import to work, But I dont know where to set the path of R to set to since I dont have R folder in my libs even after I installed rpy2 using pip Optional Quetion: Also on the side note is it possible to do what I am thinking on running the … -
Nautobot celery ERROR/MainProcess] Received unregistered task of type
I'm using nautobot with celery and redis for background tasks but it doesn't seem to work. This is my error: [2023-08-15 18:37:13,227: ERROR/MainProcess] Received unregistered task of type 'nautobot_device_onboarding.worker.onboard_device_worker'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[["bcc4229d-f59b-427d-b702-042ff378bfed", {"__nautobot_type__": "nautobot_device_onboarding.utils.credentials.Credentials", "username": "UserAdmin", "password": "Acuat1v3", "secret": "Acuat1v3"}], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (269b) Thw full contents of the message headers: {'lang': 'py', 'task': 'nautobot_device_onboarding.worker.onboard_device_worker', 'id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'parent_id': None, 'argsrepr': "(UUID('bcc4229d-f59b-427d-b702-042ff378bfed'), *Credentials argument hidden*)", 'kwargsrepr': '{}', 'origin': 'gen56@f8decca231bf', 'ignore_result': False} The delivery info for this task is: {'exchange': '', 'routing_key': 'default'} Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 591, in on_task_received strategy = strategies[type_] KeyError: 'nautobot_device_onboarding.worker.onboard_device_worker' This file is the worker.py where the task should be defined with the @nautobot_task, the import works but it doesn't define the function. try: from nautobot.core.celery import nautobot_task CELERY_WORKER = True @nautobot_task def onboard_device_worker(task_id, credentials): """Onboard device with Celery worker.""" return onboard_device(task_id=task_id, credentials=credentials) except ImportError: … -
Microsoft Teams integration for Django self-hosted in AWS
I already spent several hours on Microsoft docs making very little progress for what I believe should be a trivial integration, but apparently it's not. I've a Slack integration (via Slack app, built in Django and hosted on AWS) that works this way: our client installs the app and we receive a single token with the token we can pull all slack workspace accounts once that's done, our app sends 2 types of messages using that same token: a message to a public slack channel a 1-to-1 message to an individual I need to replicate this behaviour for Microsoft Teams. I don't want to use Azure, nor node.js, ideally if I could spin up few endpoints to exchange tokens on Django and some logic to send the messages that would be gold. At this point I will take any wisdom from Teams experts ... Thanks -
AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi'
I have a problem when i'll deploy my Django application. The error return is: error return This is my file path: file path I have too my web.config in wwwroot: web.config I'm using windows server 2008 and python 3.7 wsgi.py: wsgi.py I already check my Handler Mappings and FastCGI Settings, but doesn't found anything wrong, by i know. I trying to deploy a Django application in a local Windows Server, but when open in the port 80 returns me this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi' StdOut: StdErr: -
Why I ain't able to open a file after downloading "virtualenv env" as I saw it in a Yt tutorial video
I decided to learn the Django tutorial from the Yt video but as I saw that guy gave a command "pip install "virtulenv env" and a new file was opened in his file explorer. Then he again downloaded several other stuffs but I stucked on this step only and he moved ahead of me completing Django download successfully and started coding. A complete set up guidance for Django environment for Windows11, including commands and if raised any issue their solutions. -
How can I add taggit tags to a newly created Django model instance?
I'm unable to add Taggit tags to a newly created Django model instance from within a DRF serializer. When attempting to do use the new instance, the operation fails with list object has no attribute add. class ThingSerializer(serializers.ModelSerializer): def create(self, validated_data): # fails with `list object has no attribute add` thing = Thing.objects.create(**validated_data) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing.save() def create_with_hack(self, validated_data): # works after fetching the record from DB thing = Thing.objects.create(**validated_data) thing_ = Thing.objects.get(pk=thing.id) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing_.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing_.save() As noted above, I'm able to work around this by first explicitly fetching record from the database but that is undesirable. Also, the refresh_from_db model method does not solve the problem. Python 3.8 Django 4.2.2 Taggit 4.0.0 -
How to use Django views variables in Google Maps API Javascript on HTML template?
For obvious reasons, I'll be referring to my API KEY by [GOOGLE_API_KEY]. I have the following view : def search_places(request): GOOGLE_API_KEY = os.getenv('google_api_key') search_keywords = request.POST.get('keywords') search_type = request.POST.get('type') top = request.POST.get('top') is_open = request.POST.get('open') w_duration = 1 - (int(request.POST.get('w-duration')) / 100) rating_filter = float(request.POST.get('btnradio-rtg')) price_filter = int(request.POST.get('btnradio-price')) # Converting is_open from string to bool if is_open: is_open = True else: is_open = False df_users = get_all_users_df() dict_users = format_df_users_for_map(df_users) barycenter = compute_barycenter(df_users) return render(request, "index.html", {'google_api_key': GOOGLE_API_KEY, 'dict_users': dict_users, 'barycenter': barycenter } ) Which return in dict_users and in barycenter the following : dict_users = [{'lat': 48.8501531, 'lng': 2.3897723, 'name': 'John'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jack'}, {'lat': 48.8472106, 'lng': 2.3792469, 'name': 'James'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jose'}] barycenter = (48.848887225, 2.4216118) In my 'index.html' template, I have : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="shortcut icon" href="{% static 'css/favicon.ico' %}" type="image/x-icon"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://maps.googleapis.com/maps/api/js?key=[GOOGLE_API_KEY]&libraries=places" defer></script> </head> With a script block : <html lang="en"> <body style="background-color: #f4f6f9;"> <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "[GOOGLE_API_KEY]", v: "beta"}); // … -
prevent closing of python app using windows CMD X button (by mistake)
I have a running Django app (localy) in "start.bat" file. CALL venv\Scripts\activate.bat manage.py runserver 0.0.0.0:8000 --insecure --noreload Someone on the PC sometimes close the window How can I prevent this? like: warning popup with prompet / hide X button / run in different app than CMD ? I did run it on TK gui but it was messing with my process manager inside the Django. -
Update the text entry widget in a django_jsonform JSONField
I'm using a JSONField from django_transform for a json column in my DB. On the admin page Django renders a nice form that allows users to add entries to the json according to the schema. I want to switch out the text entry input field (a Textinput, I think) for string inputs in the JSONField form with a rich text entry widget. I've tried overwriting the JSONField widget with a rich text widget (I'm using TinyMCE) but that replaces the whole thing and just prints the dumped json string in it. Is it possible to override internal widgets of the JSONField form? -
TypeError at /empinfo/add EmployeeInfoViewset.get_empinfo() got an unexpected keyword argument 'pk'
Here i was used Django Rest Framework to create simple API, But I was facing the Error on try to create new data model.py class EmpPersonalInfo(models.Model): emp_id = models.OneToOneField( 'Employees', models.PROTECT, primary_key=True, db_column='emp_id', verbose_name='Employee ID') dob = models.DateField(verbose_name='Date of Birth') mobile = models.CharField( max_length=10, unique=True, verbose_name='Mobile No.') email = models.CharField(max_length=45, unique=True, verbose_name='Email Address') aadhar = models.CharField(max_length=12, unique=True, verbose_name='Aadhar No.', help_text='Enter Aadhar no. without space') pan = models.CharField(max_length=20, unique=True, verbose_name='PAN No.') add1 = models.CharField(max_length=100, blank=True, null=True, verbose_name='Address line') city = models.CharField(max_length=25, blank=True, null=True, verbose_name='City') state = models.CharField(max_length=25, blank=True, null=True, verbose_name='State') pincode = models.IntegerField( blank=True, null=True, verbose_name='Pincode') class Meta: managed = False db_table = 'emp_personal_info' verbose_name_plural = "Personal Information" def __str__(self): return str(self.emp_id) in my Django app i was used without id field, but in my Mysql Db table i have extra id field Auto increment but not PK, emp_id only used FK and PK here. views.py class EmployeeInfoViewset(viewsets.ViewSet): queryset = EmpPersonalInfo.objects.all() serializer_class = EmpInfoSerializer lookup_field = 'emp_id' @api_view(['GET']) def get_empinfo(request, emp_id=None): with connection.cursor() as cursor: if emp_id is not None: cursor.execute("CALL sp_get_empInfo(%s)", [emp_id]) else: cursor.execute("CALL sp_get_empInfo('')") results = cursor.fetchall() employee_info = [] for result in results: employee_info.append({'emp_id': result[0], 'dob': result[1], 'mobile': result[2], 'email': result[3], 'aadhar': result[4], 'pan': result[5], 'address1': result[6], 'city': … -
Multiple processes spawned when running Django runserver
Sometimes, When I run Django (ver 4.1.6) runserver and monitor the usage memory usage using htop I see that there multiple processes or threads spawned (see the below image). The same thing doesn't happen when running another application's Django even though most of the code is almost identical. Any idea why this is happening? Is there any setting to determine the number of threads? and how do I figure out where the issue is? -
Sending Catalogue WhatsApp Business API
I am trying to ingrate integrate WhatsaApp Business API. I have setup the webhook and can now receive messages through the webhook but when when I send a catalogue, the webhook says Message type is currently not supported.Below is the full response { 'object': 'whatsapp_business_account', 'entry': [ { 'id': '**********************', 'changes': [ { 'value': { 'messaging_product': 'whatsapp', 'metadata': { 'display_phone_number': '***************', 'phone_number_id': ''***************' }, 'contacts': [ { 'profile': { 'name': 'Majesty' }, 'wa_id': 'Majesty' } ], 'messages': [ { 'from': ''***************', 'id': 'wamid.'***************==', 'timestamp': ''***************', 'errors': [ { 'code': ******, 'title': 'Message type unknown', 'message': 'Message type unknown', 'error_data': { 'details': 'Message type is currently not supported.' } } ], 'type': 'unsupported' } ] }, 'field': 'messages' } ] } ] } Is there a way to send catalogue receive it through the webhook -
Django - How to fix multiple pks in url?
I currently have a live search functionality built out mostly working how I want. Functionality works like this: A user searches a word on the search bar. Then the user gets a display of suggested searches that includes text and an image. The user clicks on the text/image from the suggested searches that they want and then the user goes to the template page that includes the primary key in the url. The Problem: When the user is on the template page that includes the primary key and another form submission is made. An additional pk gets added to the URL. Example: http://127.0.0.1:8000/1/2/ This results in Page Not Found 404. How do i fix this? After a user makes another submission I just need the url updated with the new primary key. So this: http://127.0.0.1:8000/1/2/ needs to be this http://127.0.0.1:8000/2/ Any help is gladly appreciated. Thanks! Code Below: urls.py: urlpatterns = [ path('', account_view_home, name='home'), # Below are the urls where the live search is enabled # path ('game_details/', search_results_view, name="game_details"), path ('<pk>/', search_detail_view, name="detail") ] views.py def search_detail_view(request,pk): obj = get_object_or_404(Game_Info, id=pk) user_prices = Shopping_Prices.objects.all() game_leaderboard = User_Info.objects.all() # return render(request, 'detail.html', {'obj':obj}) if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context … -
How to resolve the StaleElementReferenceException in selenium
I was trying to create an automation tool using selenium with python which searches google for a particular link and if the link is in the top results it will be marked as indexed and if it is not present it will be marked as not indexed. The first link gets searched with no problem but when I target the search bar to search the next link I'm getting this error. I'm looping over all my links in my database. Below given is the code I used for searching google. parser/parser.py from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from indexer.models import Link from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def main(): indexed = 0 not_indexed = 0 db_links = Link.objects.all() options = webdriver.FirefoxOptions() options.add_argument("-headless") driver = webdriver.Firefox(options=options) wait = WebDriverWait(driver, timeout=10) visited_google = False for link in db_links: try: if not visited_google: driver.get(f"https://www.google.com") visited_google = True wait.until(EC.element_to_be_clickable((By.XPATH, "//textarea[@id='APjFqb']"))) textarea = driver.find_element(By.XPATH, value="//textarea[@id='APjFqb']") textarea.send_keys(link.link) textarea.send_keys(Keys.ENTER) wait.until(EC.presence_of_element_located(locator=(By.XPATH, "//div[@id='search']"))) search = driver.find_element(By.XPATH, value="//div[@id='search']") anchor = search.find_element(By.XPATH, value=f"//a[@href='{link}']") if anchor: indexed += 1 else: not_indexed += 1 except NoSuchElementException: not_indexed += 1 driver.quit() print(indexed) print(not_indexed) I am using django. My view function … -
How to export in nextjs without regenerate the elements
I have a project with nextjs and I had to get output from it Now, if I want to make a change in the created html pages, I have to go to the chunks folder and edit the js file related to it, but I don't want this to happen because I want to set it with Django variables, and I don't want it to be related in any way. I can also use restful Thankful Also, I tried rendering on the server side and set webpack to false in the nextjs configuration, but no results were obtained. -
Is there a way to know what triggered the beforeunload?
I have a page on my Django app with a form. I would like to alert users if they try to exit the page without submitting their form. I implemented this with the beforeunload method, written below: window.addEventListener('beforeunload', function (e) { e.preventDefault(); e.returnValue = ''; }); However, this also raises an alert when a user submits a page. Is there a way to identify which event is triggering the beforeunload (either submit or exiting, refreshing,etc.)? -
Form Validation Errors Not Displayed in my HTML Template
I developed a login and registration system using Django on a single HTML page with a tabbing system. But, I encountered an error: upon registering, the page just refreshes. To troubleshoot, I debugged by printing errors to the console. It printed that the form is invalid. I intentionally provided invalid details to troubleshoot, like entering a password similar to the username or a password that isn't longer than 8 characters. It printed that in the console, but I want it to show the errors in the HTML template for each field. So, I wrote a login-register view. Everything seems to be okay in the view, but it still isn't showing the errors in the HTML template. Forms class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(label="Email", max_length=255, required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field_name in self.fields: field = self.fields[field_name] field.widget.attrs.update({'class': 'u-full-width bg-light pb-2', 'placeholder': field.label}) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Views def login_register_view(request): if request.user.is_authenticated: return redirect('core:home') if request.method == 'POST': action = request.POST.get('action') if action == 'login': # login functionality elif action == 'register': registration_form = CustomUserCreationForm(request.POST) if registration_form.is_valid(): user = User.objects.create_user( username=registration_form.cleaned_data['username'], email=registration_form.cleaned_data['email'], password=registration_form.cleaned_data['password1'] ) user.save() return redirect('core:login_register') login_form = CustomAuthenticationForm() registration_form = CustomUserCreationForm() … -
Strapi filtering dose not work when I provide JWT token and returns every thing
I have this Strapi endpoint that return the products The problem is when I include the jwt token in the headers the filtering dose not work and it returns every thing but when I take the jwt suddenly the filtering work this is the function def get_products_by_supplier(jwt, supplier_id): url = f"{STRAPI_BASE_URL}/products?populate=*&filters[supplier][id][$eq]={supplier_id}" if jwt: headers = { "Authorization": f"Bearer {jwt}", "Content-Type": "application/json" } response = requests.request("GET", url, headers=headers) if response.status_code == 200: return response.json() else: return None else: return None how can I solve this issue because I need to use the jwt token in the headers -
no such table Django
I have a problem with Django. I got the Error Message: no such table: tablename. I already defined the model and now I want to safe Data in this model. But it cannot find the table. I hope you can help me. #my models.py class ImageUpload(models.Model): image = models.FileField(upload_to= user_directory_path) camera = models.CharField(max_length=100) ... #my view.py if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] camera = form.cleaned_data['camera'] uploaded_file = ImageUpload( image=image, camera=camera, ) uploaded_file.save() -
Please enter the correct email and password for a staff account
I created super user using python manage.py createsuperuser and i am sure that is_staff = True, is_superuser = True, is_active = True. I used custom user, here is models.py: from django.db import models from django.contrib.auth.hashers import make_password from django.contrib.auth.models import AbstractUser, Group, Permission, UserManager class CustomUserManager(UserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) def _create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.password = make_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=254, unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() # use the custom manager def __str__(self): return self.email why can't login into the admin panal? -
Wagtail hook for richtext editor
I created a wagtail hook for adding a code block from the Richtext editor. The hook is working but I have the problem. The hook supposed to work like as follows, <div class="code"> content line one content line two </div> But when I apply the block from editor , it is applying each line with the code like, <div class="code">content line one </div> <div class="code">content line two </div> This was supposed to be one line, The wagtail editor is applying multiple divs for each of the lines instead of one div for the selected block My hook code is as follows, @hooks.register('register_rich_text_features') def register_py_code_block_feature(features): """ Registering for adding python code block """ feature_name = 'py-code-block' type_ = 'py-code-block' control = { 'type': type_, 'label': 'PY', 'description': 'Python Code Block', # Optionally, we can tell Draftail what element to use when displaying those blocks in the editor. 'element': 'div', 'style': { "display": "block", }, } db_conversion = { 'from_database_format': {'div': BlockElementHandler(type_)}, 'to_database_format': {'block_map': {type_: { 'element': 'div', 'props': { 'class': 'code blog_code language-python' } } } }, } features.register_editor_plugin('draftail', feature_name, draftail_features.BlockFeature(control)) features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append('py-code-block') Can some one point me the right direction -
How to connect local database with .env file?
I have a django docker container. And I have two .env files: one for local and one for production. And I am using Azure for the database service. So if I connect the env file with the Azure database it works. But when I try it the .env file for the local datbase. I get am error. so docker-compose file looks like: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./Welzijn:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" environment: - DEBUG=1 env_file: - ./.env.sample and the local env file looks like: DEBUG=True SECRET_KEY="%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u" DATABASE_NAME="zijn" DATABASE_USER="zijn" DATABASE_PASSWORD="password" DATABASE_HOST="127.0.0.1" DATABASE_PORT="" So when I do a:docker-compose up --build I get this error: dwl_backend-app-1 | django.db.utils.OperationalError: could not connect to server: Connection refused dwl_backend-app-1 | Is the server running on host "127.0.0.1" and accepting dwl_backend-app-1 | TCP/IP connections on port 5432? But I also have a production env file: DEBUG=False SECRET_KEY="+)d)&d0^&0xda+s%1o(&r3+24)x#i^bk8p8r)@jl_q2=%usxw=" DATABASE_NAME="zijn" DATABASE_USER="zijn" DATABASE_PASSWORD="85jLGTj{v?s38_Jr" DATABASE_HOST="db-zijn.postgres.database.azure.com" DATABASE_PORT="" And that is working if I do a docker-compose up --build Question: How to connect with the local database with the .env file? -
How to create a REST API with Django and implement SSL, token authentication?
So, I need provide an API endpoint for my app. The one who requests this kinda link /api/thing/?thing_id=abc123 would get a JSON data. I am done with this part but cannot figure it out how make auth token implementation and I think I am mixing terms with SSL. So, it would be really appreciated, if someone explains!