Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
custom delete action admin class in django
I want to custom delete action admin class with overwrite function delete in admin.py , but it dosn't work ! this is the error : Post with ID “<django.db.models.query_utils.DeferredAttribute object at 0x0000020BF060A450>” doesn’t exist. Perhaps it was deleted? I read and used this code at following site but it wasn't work: the site I used it class PostAdmin(admin.ModelAdmin): list_display = ('delete',) def delete(self, obj): view_name = "admin:{}_{}_delete".format(obj._meta.app_label, obj._meta.model_name) link = reverse(view_name, args=[Post.id]) html = '<input type="button" onclick="location.href=\'{}\'" value="Delete" />'.format(link) return format_html(html) -
Adding a filter to a Django Module
I'm working in a Django project. I've created a model to save the last 50 errors that happen. models.py class Error(models.Model): ERROR_TYPE_CHOICES = [ ('ERROR', 'ERROR'), ('WARNING', 'WARNING'), ] user_mail = models.CharField(max_length=500, blank=True, null=True) error_type = models.CharField(max_length=7, choices=ERROR_TYPE_CHOICES) error_message = models.CharField(max_length=1000, blank=True, null=True) error_message_detail = models.CharField(max_length=500, blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) # Static field for maximum errors limit max_errors = 50 def __str__(self): return f"{self.error_type}: {self.error_message}" class Meta: ordering = ['-created_at'] # Order by descending creation date @classmethod def check_and_trim(cls): # # Obtain all errors ordered by creation date errors = cls.objects.all().order_by('-created_at') # If there are more than 50 errors, delete the older ones if errors.count() > cls.max_errors: errors_to_delete = errors[cls.max_errors:] for error in errors_to_delete: error.delete() admin.py class ErrorAdmin(admin.ModelAdmin): list_display = ('user_mail', 'error_type', 'error_message', 'error_message_detail', 'created_at') admin.site.register(Error, ErrorAdmin) So as you can see when there are more than 50 errors the oldest one is erased so that the new one can be saved. In the future maybe is needed to be saved more than 50 errors, so instead of changing the code I'd like to add a feature now so in the localhost:8000/admin/Error you can input how many errors you want to be saved. -
Forwarding messages from telegram web app
Good afternoon, now work on algorithm like user press "invite friends" button in telegram web app, then he see list of his telegram contats and choose reciever of "forwarded" message from himself, but writen by bot or web app. I wrote telegram bot on aiogramm, web app builded on django framework. Maybe someone know how to implemnt this, i tried but didnt found anything in network, maybe someone know way to implemt this (method or anything else), thaks to everyone here who can give any help! -
Best frameworks to choose for high scale web applications including databases and architectures
I'm getting started with [tag: web development] which frameworks do you recommend for designing a high scale web application should I go with java or python javascript with microservices as my backend architecture and what kind of database is best suited for these kind of highly scalable web apps sql nosql. Best pick for frontend and backend frameworks for a highly scalable web application with microservice as my backend architecture. -
TemplateDoesNotExist by inheriting LoginView
django cannot find my template but I give it correct path I make customize view for login by inheriting LoginView and form_class of AuthenticationForm from django. I give correct template_name to view but django cannot find it. I used mixin views for register and give template like this and I did'nt give error, so I check definition of LoginView and modify it's template_name to that I writed on my view class and it run without error this is my view class: class LoginAuthView(LoginView): form_class = AuthenticationForm template_name = 'login.html' success_url = reverse_lazy('accounts:test') def get_context_data(self, **kwargs): kwargs = super().get_context_data(**kwargs) if 'form' not in kwargs: kwargs['form'] = self.get_form() return kwargs def form_valid(self, form: AuthenticationForm) -> HttpResponse: response = super().form_valid(form) messages.success(self.request, f'Welcome {self.request.user}!') return response -
Using structlog with Datadog
We're using the logging module from the stdlib to send logs from our Django app to Datadog and we have customised our logging based on django-datadog-logger We're exploring a move to structlog, and I was wondering if there is a package that gives a good starting point to get log formatted for Datadog, similar to what the above library does as Datadog expects a few top level keys. Has anyone built something reusable already? Is there a recipe that we could reuse? PS: I already found the structlog Django extension, my question is more around formatting for Datadog -
What is the best approach to handle class instances in django application in a production environment?
I would like to consider 2 approaches. First, you could create a class and its instance in a class and inside views import the instance and call its methods. Second, you import the class and create instance of the class inside the view function when you handle a request. which one do you think is better. Also I am not saying about any class like , models, forms or serializer etc that are related to Django , but the ones I manually create for myself. Approach 1: Create an instance at module level and import it # utils.py class Calc: def run(self): # perform calculations return result calc_instance = Calc() # views.py from utils import calc_instance def view_function(request): result = calc_instance.run() # rest of the view logic Approach 2: Import the class and create an instance inside the view function # utils.py class Calc: def run(self): # perform calculations return result # views.py from utils import Calc def view_function(request): calc_instance = Calc() result = calc_instance.run() # rest of the view logic Also, I see Approach 1 creates a single instance that remains in memory for the lifetime of the process, at least in the development server. So based on your … -
Twig Tags are not allowed in django-html
I am Learning django , i have learnt python , html , and basic css. I was trying to sort things out, like peoples who are above 18 they can vote and peoples below 18 they cannot vote, this is a part of code of my templates/home/index.html image, You can understand the problem by seeing this output in the webpage,, I used ChatGPT to try to identify the main problem in my code, but it returned the same code, suggesting it was error-free. I also conducted a Google search, but I couldn't find a solution. Could someone please help me resolve this issue? -
How to resolve this NoReverseMatch error?
I am currently try make a task manager such that there are folders which have tasks in them, I have been stuck on this problem for hours now and am not sure at all what is the issue this is urls.py from django.urls import path from . import views app_name= 'tasks' urlpatterns = [ path('', views.folders_list,name="list"), path('new-folder/', views.folder_new,name="new-folder"), path('<slug:slug>', views.tasks_list,name="folder-page"), path('<slug:folder_slug>/<int:task_id>/', views.task_page,name="task-page"), path('new-task/', views.task_new,name="new-task"), ] this is models.py from django.db import models from django.contrib.auth.models import User # from .models import Folder # Create your models here. class Folder(models.Model): folder_id=models.AutoField(primary_key=True) title=models.CharField(max_length=75) created=models.DateTimeField(auto_now_add=True) slug=models.SlugField() author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Task(models.Model): PRIORITY_CHOICES=[ ('LOW','LOW'), ('MEDIUM','MEDIUM'), ('HIGH','HIGH'), ] task_id=models.AutoField(primary_key=True) title=models.CharField(max_length=75) description=models.TextField() slug=models.SlugField() deadline=models.DateField() uploaded=models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) folder = models.ForeignKey('Folder', on_delete=models.CASCADE, default=None) priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='LOW') def __str__(self): return self.title this is views.py from django.shortcuts import render,redirect from django.utils.regex_helper import re from .models import Task,Folder from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from . import forms # Create your views here. @login_required(login_url="/users/login/") def folders_list(request): user_folders = Folder.objects.filter(author=request.user) return render(request, 'tasks/folders_list.html', {'folders': user_folders}) #as folder_page == tasks_list.html def tasks_list(request, slug): # folder=get_object_or_404(Folder,slug=slug) folder=Folder.objects.get(slug=slug) folder_tasks = Task.objects.filter(folder=folder) return render(request, 'tasks/tasks_list.html', {'folder':folder,'tasks': folder_tasks}) def task_page(request, folder_slug, task_id): folder = get_object_or_404(Folder, slug=folder_slug) task = … -
when i am sending some data using post request in django and test it in postman it shows no error but in browser it is not responding correctly
from django.shortcuts import render from django.http import HttpResponse def register(request): if request.method == 'POST': name = request.POST['name'] #in this way we are collecting data email= request.Post['email'] password = request.Post['password'] print(f'Name :{name}') #in this way we are printing the data print(f'Email :{email}') print(f'Password :{password}') return HttpResponse('<h1> This is a post Request</h1>') elif request.method == 'GET': return HttpResponse('<h1> This is a get Request</h1>') else: return HttpResponse('<h1> This is an invalid Request</h1>') While testing in postman using post request it is showing it is a post request. But in browser it shows this is a get request why is it neglating post request -
Introducing custom-role in my Django based E-commerce application
I completed finish my Django E-commerce web-application. And now I want to add the facility of customer roles(admin,staff,merchant,customer). I'm having problems configuring this with my project. I'd really appreciate if someone can help me through the process. I am sharing the details of project. My existing Customer model class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) # user=models.OneToOneField(User,on_delete=models.CASCADE) -change I made to add CustomUser model phone=models.CharField(max_length=10) city = models.TextField(max_length=30) state = models.TextField(max_length=30) def __str__(self): return self.user.username My CustomerUser model that I want to introduce in my project class CustomUser(AbstractUser): ROLES=( ('admin', 'Admin'), ('staff', 'Staff'), ('merchant', 'Merchant'), ('user', 'User'), ) role = models.CharField(max_length=8,choices=ROLES,default='Customer') def is_admin(self): return self.role == 'admin' def is_staff(self): return self.role == 'staff' def is_merchant(self): return self.role == 'merchant' The login, logout and registration stopped working as soon as I added this CustomUser model into my project. -
whitenoise module not found in production
Error: I ran into this error when trying to deploy my Django app using GAE: ModuleNotFoundError: No module named 'whitenoise'. The error occurs when starting the wsgi application. Attempted fixes: Wrapping the wsgi in whitenoise as mentioned here was done, (https://whitenoise.readthedocs.io/en/stable/index.html#quickstart-for-django-apps) but it didn't make a difference. whitenoise 6.7.0 is downloaded and is in requirements.txt, and the necessary whitenoise middleware is in settings.py. Question: How do I get wsgi to find my whitenoise (and wiki) module?. Or what is better approach to deploying my app? wsgi.py import os import sys from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. PROJECT_PATH = os.path.abspath(os.path.dirname(os.path.split(__file__)[0])) PROJECT_PARENT = os.path.abspath(os.path.split(PROJECT_PATH)[0]) sys.path.append(PROJECT_PATH) sys.path.append(PROJECT_PARENT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) application = get_wsgi_application() application = WhiteNoise(application, root=os.path.join(PROJECT_DIR, 'static')) app.yaml with the url hidden for this post # app.yaml runtime: python311 env: standard entrypoint: gunicorn -b :$PORT testproject.wsgi env_variables: APPENGINE_URL: my_url DJANGO_SETTINGS_MODULE: "testproject.settings" handlers: - url: /.* static_dir: static/ - url: /.* script: auto runtime_config: python_version: 3 Logs 2024-07-16 22:15:28 default[20240716t221126] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-07-16 22:15:28 default[20240716t221126] File "<frozen importlib._bootstrap>", line 1204, in _gcd_import … -
Static files issue in Django while deploying to AWS EC2 Machine
I made a multi-tenant app using django and now want to deploy it to AWS. When I run the server on EC2 machine and go to django admin this is what I get: It works fine locally though. Also when I open the main login page I cannot see the pics I added: and here is my folder structure: I have my pics in chatbot/app/login/static/pics As for my settings.py I setup it up like this: The pics and django-admin panel is not loading with its full css HELP I tried changing the paths too but I guess I am not able to understand that. also after changing the paths I tried running "python manage.py collectstatic" but it did not make a difference -
Django - dropdown (select widget) in form is not saving data to db
I'm using this form to get a dropdown menu in my html form : forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(required=False,queryset=models_products.objects.values_list('product_denomination', flat=True), widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id)'}),empty_label=None ) models.py class models_bdc(models.Model): [...] bdc_description_1 = models.CharField(max_length=50) But when I save / submit the form, the data are not saving into the database. If I remove the select widget to a regular forms.charfield, the datas are saving correctly. So I assume the mistake is the forms.py but I can't see where. Thanks -
Frequent Deletion Failures in Django with CockroachDB
I'm using CockroachDb (version 24.2) with Django (version 5.0.7) but im currently running into an issue I don't really understand. When I trigger a certain view many times in a row which will delete an object from the Cockroach Database, it maybe works for like 4 out of 6 object I requested a deletion for, meaning 2 object will stay undeleted, I dont get any Error or stacktrace at all, the transaction simply does not get trough while Django reports back that everything went fine. The view can be very simple, like below.: @api_view(['DELETE']) @authentication_classes([]) @permission_classes([IsAuthenticated]) def delete_my_model_entry(request, pk): try: # Fetch the object to be deleted my_model_entry = MyModel.objects.get(pk=pk) # Delete the object my_model_entry.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ObjectDoesNotExist: return Response({'error': 'Object not found'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But if I fire against it many times in a short timeframe, the deletion actually dont happen at all ... For the moment I'm was not able to isolate the actual issue here I simply use django-cockroachdb==5.0 and psycopg2==2.9.9, exactly like described in the Readme file of the libraries. Thank in advance. -
Problem customizing search_get_results() method in Django Admin page to get Custom Search
I have an app in Django and I would like to use this template: {% load i18n static %} {% if cl.search_fields %} <div className="form-group"> <div class="search-notes col-md-6 col-sm-12">Para busqueda de terminos exactos poner el texto entre comillas Ej para editorial "VANGUARDIA PICTORICA" o en ISBN "978-959-7126-52-2"</div> </div> <div class="for-group-container row"> <div class="form-group col-md-3"> <input type="text" name="no_reg" class="form-control" placeholder="Número de Registro" /> <br> <input type="text" name="inputTitulo" class="form-control" placeholder="Título" /> <br> <br/> <input type="text" name="inputAutor" class="form-control" placeholder="Autor" /> <br/> </div> <div class="form-group col-md-3"> <input type="text" name="inputEditorial" class="form-control" placeholder="Editorial" /> <br/> <input type="text" name="inputDescriptor" class="form-control" placeholder="Descriptor" /> <br/> <div class="form-group col-md-3"> <input type="text" name="inputResumen" class="form-control" placeholder="Resumen" /> <br/> <input type="submit" value="{% translate 'Search' %}"> </div> {% if show_result_count %} <span class="small quiet">{% blocktranslate count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktranslate %} (<a href="?{% if cl.is_popup %}{{ is_popup_var }}=1{% endif %}">{% if cl.show_full_result_count %}{% blocktranslate with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktranslate %}{% else %}{% translate "Show all" %}{% endif %}</a>)</span> {% endif %} {% for pair in cl.params.items %} {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %} {% endfor %} </div> {% if cl.search_help_text %} <br class="clear"> <div class="help" id="searchbar_helptext">{{ … -
Django/Python - How to assign a file path variable in a platform-independent way?
I have a Django project where one of the .env file variables is going to represent an absolute file path. E.g., DEBUG=True SECRET_KEY='blah_blah_blah' MY_STORAGE_PATH = 'D:\\files\\for\\my\\project' Obviously the above would work fine on a Windows machine with a D: drive, but it's no good if there's no D: drive or if the machine is using some other OS. Now I can think of any number of functioning ways to supply this .env string in a platform-independent way, and then use string manipulation and the os.path methods to assemble the actual path. I could break out the drive & path separately, using a 'neutral' path separator of my own choosing: MY_STORAGE_DRIVE_FOR_WIN = 'D:' MY_STORAGE_PATH = '|files|for|my|project' ...I could supply the configuration formatted as a list, convert it to a real list, then feed into os.path.join(): MY_STORAGE_PATH_ELEMENTS = '["files","for","my","project"]' ...and so on, and so on. But before I go roll my own that way, I wanted to know: is there some accepted convention for this kind of use case? (Surely this isn't the first time someone needed to provide an .env value to represent a platform-independent path?) -
Why is my schema execution timing out in python graphene?
I'm using graphene. I was using version 2.1.9. I'm now using version 3.3. This code has not been changed since the upgrade, I'm going to outline the relevant code and then explain the problem further build_schema: neither Query or Mutation are None so this will return graphene.Schema(query=Query, mutation=Mutation) @logf(level='debug') def build_schema(*args, **kwargs) -> graphene.Schema: """Builds the Query and Mutation classes for the given schema name and adds them a schema and returns the schema """ Query, Mutation = None, None qclasses, qprops = _build_props('queries', *args, **kwargs) if qclasses: Query = type('Query', qclasses, qprops) mclasses, mprops = _build_props('mutations', *args, **kwargs) if mclasses: Mutation = type('Mutation', mclasses, mprops) if Query is None and Mutation is None: raise ValueError('No Query or Mutation classes found') elif Query is None: gqlschema = graphene.Schema(mutation=Mutation) elif Mutation is None: gqlschema = graphene.Schema(query=Query) else: gqlschema = graphene.Schema(query=Query, mutation=Mutation) return gqlschema This is the test case that fails, it's not verbose about why it failed, it just hangs for 60 seconds and then says that it timed out def _mock_user(user='test', **kwargs): return MagicMock(username=user, **kwargs) def _mock_info(**kwargs): infomock = MagicMock() infomock.context.user = _mock_user(**kwargs) return infomock class TestSignUrlQuery(TestCase): def setUp(self): self.query = ''' query { signedUrl( gcsUrl: "bucket/path/to/file", method: "PUT", contentType: … -
Django Database Routers "allow_migrate_model" throws the following: "TypeError: allow_migrate() missing 1 required positional argument: 'app_label'"
the "allow_migrate_model" function within my database routers keeps throw the following error when I try to run python manage.py makemigrations: ... File "C:\Users\...\lib\site-packages\django\db\utils.py", line 262, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() missing 1 required positional argument: 'app_label' My Routers look like this: class BaseRouter: route_app_labels = {} db_name = "" def db_for_read(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def db_for_write(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def allow_relation(self, obj1, obj2, **hints) -> Union[bool, None]: if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate( self, db, app_label, model_name=None, **hints ) -> Union[bool, None]: if app_label in self.route_app_labels: return db == self.db_name return None class DefaultRouter(BaseRouter): route_app_labels = {"auth", "contenttypes", "sessions", "admin", "myapp"} db_name = "default" class LibraryRouter(BaseRouter): """ separate router for backend stuff """ route_app_labels = {"library"} db_name = "library" The above is basically a slightly modified version found on the Django Docs. If I comment out the allow_migrate the makemigrations works, however, I would like to modify the allow_migrate further so that's not a convincing option rn. Ah also for some reason if a rewrite it … -
Google api, self project
I am trying to create a website using the google, place api and geocoding api, I'm am new to using Django as my backend. My get requests work, however i receive a 404 error saying pro access only. I have a pro account for the api, and on the api website it says these are enabled. Any help would be greatly appreciated. To be able to have users input a city (ex. Orlando And receive a list of bars in a radius within the city searched.) `This is my current view.py (omitted my api key and secret key for security but I have them defined in the beginning import requests from django.http import JsonResponse import hmac import hashlib import base64 def get_random_drink(request): try: url = 'https://www.thecocktaildb.com/api/json/v1/1/random.php' response = requests.get(url) response.raise_for_status() drink_data = response.json() return JsonResponse(drink_data) except requests.exceptions.RequestException as e: print(f"Error fetching random drink: {e}") return JsonResponse({'error': 'Failed to fetch random drink'}, status=500) def generate_signature(endpoint): string_to_sign = f"{API_KEY}{endpoint}" signature = hmac.new(SECRET.encode(), string_to_sign.encode(), hashlib.sha256) return base64.b64encode(signature.digest()).decode() def search_nearby_bars(request, city): try: location_data = get_city_coordinates(city) if not location_data: return JsonResponse({'error': 'City not found'}, status=404) lat, lng = location_data radius = 5000 # Set the radius for the nearby search in meters # Prepare the … -
Websocket Connection failing on Deployed Azure web app
I am running a nodeJs server, and serving a ReactApp from it. This is deployed and hosted in an Azure WebApp. I have container running a Django server, hosted on a separate Azure WebApp. I am trying to open a WebSocket connection from my React app directly to my Django server. I have tested this locally by deploying my Django app to azure, and then building my NodeJs & ReactApp LOCALLY and opening the wss:// connection and it works on my machine. But the after deploying the Node/React application to Azure the websocket connection fails with errorcode: 1006 I'm not sure what information settings would give more assistance in solving the issue. I'm completely new to WebSockets as a whole. I'm hoping it's something to do with headers or protocols being stripped/changed as mentioned at the end of this article. But I cannot see anything in my Azure app configuration. I can provide any further information (code or Azure configuration), I just don't know exactly what would help troubleshoot. (My WS connection code, just for transparency) export const awaitWsPing = () => { const socket = new WebSocket('wss://myDjangoApp.azurewebsites.net/my/ws/url'); socket.onmessage = (e) => { const data = JSON.parse(e.data); console.log({data}); notificationContext.setMessage('Received ping … -
How to get authorized in Microsoft AD using curl?
I have a django project which uses Azure Active directory for the authentication and I have set up its API using rest_framework. At the moment, I am trying to access this API using curl. I am able to generate an access token, but when I send a request using it, I get the Microsoft Login Page, as if I do not have any access token. I generated an access token using the following code: curl -X POST https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token -H "Content-Type: application/x-www-form-urlencoded" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "grant_type=client_credentials" -d "redirect_uri=https://{my_domain}/oauth2/callback" -d "scope=api://{tenant_id}/.default openid profile email" Then, using the jwt token that I recieved, I did: curl -X GET -L https://<my_domain>/api/benches/1/status/ -H "Authorization: Bearer <token>" And what I get, is the Microsoft login page, which its first few lines look like this: <!-- Copyright (C) Microsoft Corporation. All rights reserved. --> <!DOCTYPE html> <html dir="ltr" class="" lang="en"> <head> <title>Sign in to your account</title> . . . Also, the result of the -v (verbose) looks like this: Note: Unnecessary use of -X or --request, GET is already inferred. * Host <my_domain>:443 was resolved. * IPv6: (none) * IPv4: ip * Trying ip:443... * Connected to <my_domain> (ip) port 443 * schannel: disabled automatic … -
AWS: How to let a S3 frontend (React, Axios) communicate with an EC2 backend (python3/Django, DjangoREST, corsheaders)
I followed a tutorial for creating a basic To-Do app (so CRUD) with a React+Axios frontend (ServiceWorker, bootstrap) and Django backend (DjangoREST, corsheaders), and would like to put it on AWS's free tier for job-finding purposes. I got the app running fine locally using localhost, and even able to get the server running on EC2 and the frontend hosted on S3 using various other tutorials. Now i'm stuck on how to get them to communicate without them being on the same machine. I had hoped I could just change some lines relating to localhost to their IP's and Ports, but that hasn't worked. Since this is a fairly simple example program I tried to keep security to a minimum throughout setup to help communications, and have allowed HTTP and HTTPS and anything I could * in my security settings. In settings.py I have: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ['http://frontend-IP:3000'] and in my frontend package.json I have: "proxy": "http://backend-IP:80", to tunnel the API to the backend so my axios commands look like: axios .get("/api/todos/") Rather than the whole address. I also am not sure how to make React use something other than localhost:3000 or if i need to change that if … -
How to render Markdownx content as HTML in a Django blog project?
I did all the installation of markdownx steps as stated. I've installed the django-markdownx package using pip install django-markdownx. I've added 'markdownx' to my INSTALLED_APPS in settings.py. I've defined a MarkdownxField in my blog post model to store the Markdown content. but my problem is I'm unsure about the correct template tag usage to render the Markdown content as HTML. this is my models.py: from django.db import models from markdownx.models import MarkdownxField class Article(models.Model): title = models.CharField(max_length=200) content = MarkdownxField() def __str__(self): this is my viwes.py: from .models import Article def post_list(request): articles = Article.objects.all() return render(request, 'blog/post_list.html', {'articles': articles}) this is my admins.py: from django.contrib import admin from .models import Article from markdownx.admin import MarkdownxModelAdmin admin.site.register(Article, MarkdownxModelAdmin) this is my urls.py of project(not app): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('markdownx/', include('markdownx.urls')), path('', include("blog.urls")), ] in the admin it shows the preview correctly but I used many tags to convert the markdownx to html but I'm not successfull. I used: {% for article in articles %} <article> <h1>{{ article.title }}</h1> <div>{{ article.content|markdown|safe }}</div> </article> {% endfor %} but I got TemplateSyntaxError. I used: {% for article in articles %} <article> <h1>{{ … -
Where to write validation in django?
Any one can you suggest me about which is the best practise to write the validation in django project. Writing validation in serializer is better or in models is better. I have try both for writing validation but still I am unable to choose where to write validation is more better. Can any one suggest me ? If you guys have a experience of working in real world project then also share where you have written this validation.