Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django object multilevel filtering
Hi Everyone I want to filter object which is in the form of tree class UserModel(model.Model): created_by = models.ForiegnKey('self',on_delete=model.SET_NULL,null=True) name = model.CharField(max_length = 50) the relation will be userModel A,B... represent UserModel, A -> B,represent B is child of A A -> B -> C -> D -> E -> F-> and so on I want to filter Object where A able to see its child and grandchild but not its GrandParent A is able to see UserModel Objects created by B C D E so on but B is only able to see User created by C D E F, not for A; -
How I can use json object from file (e.g text.json) for my email template to read from in Django
I am using Django to send email templates to user. I want to store all the text show ins the HTMl template in json object and reference the text as variable, double {{}} in the html email template -------> util.py def send_reset_password_email(user: User): reset_token = create_user_reset_password_token(user) reset_password_url = '{}/account/password/reset/{}'.format(settings.CLIENT_URL, reset_token) params = { 'reset_password_url': reset_password_url, 'textdata': ### how I can reference my json file here } send_template_email(user.email, 'Reset Password','reset_password.html', params) ------->text.json file { "forget_password_email_template": { "title": "This is title", "sub_title": "This is Sub title", "support": "This is title", "help_message": "This is help message" }, "confirmation_email_template": { "title": "This is title", "sub_title": "This is Sub title", "support": "This is title", "help_message": "This is help message" } } -------> reset_password.html <html> ....... <p style="margin: 0;" class="forget-password-text"> Forgot your password? Let’s get you a new one! {{params.textdata}}</p><br> ..... <<html/> I have tried import json but it didn't work. Thanks, and if there is other any better way to achieve this?? -
Django REST API get only auth user datas
I am new Django, I try make REST API. Now face one issue. I created 2 models Account & Transaction class Account(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) user = models.ForeignKey(User,on_delete=models.CASCADE) account_name = models.CharField(max_length=100) Account have ForeignKey with user model class Transaction(models.Model): id = models.UUIDField(default=uuid.uuid4(),primary_key=True,editable=False) account = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='account') transaction_no = models.CharField(default=str(uuid.uuid4())[:8],max_length=100) Transaction have ForeignKey with Account model. then get JWT token & pass on API. In view.py I filtered by requested user @api_view(['GET']) @permission_classes([IsAuthenticated]) def getAccount(request,pk): account = Account.objects.filter(user=request.user).get(id=pk) serializer = AccountSerializer(account, many=False) return Response(serializer.data) now how will filter Transaction only by auth User @api_view(['GET']) @permission_classes([IsAuthenticated]) def getTransactions(request,account_id): transactions = Transaction.objects.filter(account=account_id) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) -
CSS alternative to "display:inline-block" for email
I have to send emails to customers when they perform various actions on my website. Obviously, I want these emails to look good and to contain an selection of images, links and other features. I have built an HTML version of the email I wish to send and my Django app converts it to a nice email that really gets the job done. The problem I have is that there seems to be no standard for what is supported by different email providers. My email looks perfect on browser, Gmail and Android, but when I open it up in the Outlook app on my Microsoft, suddenly some CSS properties are not supported. I have this website which tells me what CSS attribute are supported and which ones aren't: https://www.caniemail.com/search/?s=display From that website I understand that the "display" attribute is not supported by the Outlook app. That is very unfortunate because I don't know any alternative for essential stuff like "inline-block" or how to center my images. Would anybody know how to replace these attributes (most important of all 'inline-block') so that I can send these emails to any platform my clients might use? -
Do you think this is the right way to rename a django app?
I read different threads and tutorials on renaming and migrating a Django app (How to rename a Django app and migrate data from an app to the other for instance), I also tried to use the django package called django-rename-app but it didn't work at all. I'm going to explain the way I renamed my app in my development environment and I would like to know if you expect troubles, as apparently everything is working just as it did before so I'm considering doing the same in production. Here are the steps I took inside my root project directory and my virtualenv activated, using Django 3.2: Create the destination app django-admin startapp app2 Copy these files and directories cp app1/*.py app2/ mkdir app2/templates mkdir app2/static cp app1/templates app2/templates in this case I had a sub-folder named after the app so I renamed it like this mv app2/templates/app1 app2/templates/app2 cp app1/static app2/static Models.py Change the related_name attributes of all ForeignKeys in my new models.py and update all their references inside my views, admin, form and templates Activate the new app Add my app2 to the list of the enabled apps of settings.py Delete pycache Find and delete or empty all the … -
Django user manager overriding create()
I ran into an issue that was solved in the following way. # models.py class CustomUserManager(SafeDeleteManager,UserManager): def create(self, username, email=None, password=None, **extra_fields): return super().create_user(username, email, password, **extra_fields) class CustomUser(AbstractBaseUser): # other fields are omitted for brevity. objects = CustomUserManager() Is overriding create method in the custom user manager ok, or it can cause problems in the future? -
List of connected users in a room with django channels
How can we get the list of connected users to a room within channel with Django Channels? I know this question has been asked many times, but honestly, I've scoured all over the internet and I'm very surprised there isn't a conventional way of doing so. According to this answer, Django Channels have avoided this scenario, however, there is another package, Django Presence, that can cater for it. So far, I've got a very simple app where a websocket broadcasts data that is sent from each client, so that each connected client in a room receives that data. I've also got a simple authentication so that only authenticated users can connect. This is what I have: routing.py application = ProtocolTypeRouter( { "websocket": TokenAuthMiddleware( URLRouter([ re_path(r'ws/(?P<room_name>\w+)/$', consumers.MyConsumer.as_asgi()), ]) ) } ) middleware.py from urllib.parse import parse_qs from django.contrib.auth.models import User from django.contrib.auth.models import AnonymousUser from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, send): # Get the token token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] #custom code to validate token if token_is_valid: # assign scope['user'] = user else: scope['user'] = AnonymousUser() return await super().__call__(scope, receive, send) consumer.py def connect(self): user = self.scope["user"] if user.is_anonymous: self.close() … -
modèle d’utilisateur personnalisé en cours de projet - django [closed]
j'ai voulu mdifier le modele User de mon projet aprés deploiement.En raison des limites de Django liées à la fonctionnalité de dépendance dynamique pour les modèles remplaçables , je n'ai pas voulu prendre le risque d'avoir des erreurs de migrations ou des erreurs liées a la base de donnée. Ce que je voulais c'est mettre le champ email de User a unique et d'enlever le blank=True et ensuite creer un moteurs d’authentification basée sur le champ email et mot de passe. Ce que j'ai fais c'est de modifier le code source de models.py dans "virtual_env_name/lib/python3.8/site-packages/django/contrib/auth." Dans le champ email j'ai enlevé blank=True et j'ai mis unique=True et cela a marcher. Ma question est : est ce une bonne idee de modifier le code source de models.py dans lib/python3.8/site-packages/django/contrib/auth -
IntegrityError at UNIQUE constraint failed: sales_salesitem.product_id django
Hello there anyone and everyone! I'm stuck at a point and getting the error: IntegrityError at /meet/report_meeting/sales_person/1/customer/1/product/1/meeting_request/1/ UNIQUE constraint failed: sales_salesitem.product_id I'm getting this error when trying to use the create() method in the following snippet, like the following: def report_meeting(request, product_id, customer_id, sales_person_id, request_id): form = ReportMeetingForm() sales_person = Sales_person_profile.objects.get(id=sales_person_id) customer = Customer_profile.objects.get(id=customer_id) product_under_discussion = Product.objects.get(id=product_id) if request.method == "POST": form = ReportMeetingForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.sales_person = sales_person instance.customer = customer instance.product_under_discussion = product_under_discussion sales_person.consulted_cases += 1 cd = form.cleaned_data if cd['sale_closed'] == False and cd['follow_up'] == True: instance.number_of_follow_ups += 1 instance.save() elif cd['sale_closed'] == True and cd['follow_up'] == False: sales_person.sales_completed += 1 instance.save() sales_item = SalesItem.objects.create( product= product_under_discussion, meeting= instance, quanity= cache.get('quantity') ) else: print(form.errors) return redirect("accounts:dashboard") else: form = ReportMeetingForm() context = { 'form': form, } return render(request, 'chat/report_meeting.html', context) Now the funny thing is, I think, instance is being saved flawlessly, which means that the product_under_discussion has the product object. But when the same is delivered to the create method, it gives me the error. According to my experience, this will error will raise if I'm not giving a Product instance. Maybe I'm wrong with my concept somewhere. Anyhow, this is the SalesItem … -
GeoDjango Admin Widget for GeometryCollection?
Is it possible to have an editable widget in the GeoDjango Admin for a GeometryCollectionField? Consider the following code: models.py: from django.db import models from django.contrib.gis.db import models as gis_models class MyModel(gis_models.Model): name = models.CharField(max_length=64, blank=False, null=False) point = gis_models.PointField(blank=False, null=False) polygon = gis_models.PolygonField(blank=False, null=False) geometry = gis_models.GeometryField(blank=False, null=False) geometry_collection = gis_models.GeometryCollectionField(blank=False, null=False) admin.py: from django.contrib import admin from django.contrib.gis import admin as gis_admin from my_project.models import MyModel @admin.register(MyModel) class MyModelAdmin(gis_admin.GeoModelAdmin): fields = ( "name", "point", "polygon", "geometry", "geometry_collection", ) This gives me editable widgets for all fields except for geometry_collection: Any hints? -
Django using 2 different databases during tests
Using: Django 4.0.4 Python 3.9.13 Running: python ../../manage.py test website.functional_tests.test_loggedOutUser.HomePageTest.test_user_email_registration Files: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'ProdComment': 'This is the PROD DB.', 'TEST': { 'NAME': BASE_DIR / 'TEST_.db.sqlite3', 'MIRROR': 'default', 'COMMENT': "This is the TEST DB.", }, } } test_loggedOutUser.py content: from selenium import webdriver from django.test import TestCase as TC from django.db import connections as DBC from django.db import connection as DBCON from allauth.utils import get_user_model as getusermodel import time from django.core.exceptions import ObjectDoesNotExist allUsersALLAUTH = getusermodel() # Method used to check if a test user exists in the DB and then delete this user # Test if account creation works. # Returns 1 if user does not exist, 0 if deleted successfully. def delTestUser(): username = 'TheTester' allUsersALLAUTH = getusermodel() print("DELTESTUSER, allUsersALLAUTH.objects.all(): ", allUsersALLAUTH.objects.all()) print("DELTESTUSER, Testing if we can delete the test user.") try: userToDelete = allUsersALLAUTH.objects.get(username=username) print("DELTESTUSER, usertodelete: ", userToDelete) except ObjectDoesNotExist: print("DELTESTUSER, The user you tried to find does not exist.") # Trying to see which DB is used to no avail. print("DELTESTUSER: ", DBC.databases['default']['NAME']) return 1 else: print("DELTESTUSER - ELSE: ", DBC.databases['default']['NAME']) print("DELTESTUSER, We found the user and can delete him.") userToDelete.delete() print("DELTESTUSER, The user has now been … -
Bad Request Django upload CSV by chunks
I'm trying to upload a csv to an endpoint using Django. The csv is not linked to any Model, just is needed to trigger a celery task. The thing is that I'm getting a Bad Request and django is not providing me any more information. The uploaded file needs to be done in chunks and the code to upload is the following using the python requests library import os import requests import pdb def read_in_chunks(file_object, chunk_size=1024): while True: data = file_object.read(chunk_size) if not data: break yield data def main(file, URL): content_name = str(file) content_path = os.path.abspath(file) content_size = str(os.stat(content_path).st_size) f = open(content_path) index = 0 offset = 0 headers = {} for chunk in read_in_chunks(f): offset = index + len(chunk) headers['Content-Type'] = 'application/octet-stream' headers['Content-length'] = content_size headers['Content-Range'] = 'bytes %s-%s/%s' % (index, offset, content_size) index = offset file = {"file": chunk} try: r = requests.put(url, files=file, headers=headers) except Exception as e: print(str(e)) if __name__ == '__main__': url = 'http://127.0.0.1:8000/task/upload' main('test_upload.csv', URL) And executing like this: python3 test_upload.py Here is the view: class TaskUploadView(APIView): def put(self, request): ## NOT TESTED CODE, SINCE IT DOES NOT REACH THIS POINT parser_classes = (FileUploadParser,) f = request.FILES['file'] with open('test.csv', 'wb+') as destination: for chunk … -
Django third party authentication with Okta not changing users between logout and login with new user
I'm creating an app with Django v. 4.0.3 and using third party authentication with Okta. I have used the package django-okta-auth to aid with the connection to Django's built in authentication. The issue I have encountered is when a user logs out and a new user logs in, it is still the original user that is logged into the system. I have followed this tutorial exactly: https://pypi.org/project/django-okta-auth/ How can I add onto the logout function within the package django-okta-auth to ensure users are logged out correctly? Is this an issue with cookies needing to be cleared upon logout? There will be multiple users using the same browser (not concurrently but after login and out) so this is a necessity in the app. -
How to optimize a server request that has to send back several items with dynamic attributes that need to be calculated every time a user requests it?
I have an Angular UI app connecting to a Django API that uses GraphQL (using Graphene) and Postgres for DB. My application has many courses and each course can have several chapters. The users signing in can see access courses and not others because a course could have a prerequisite. So they will see a course listed but it will be "locked" for them and a message will say that they need to complete the particular prerequisite before it can be accessed. Like this, we need some other attributes to be sent along with the list of courses:- 'locked' - Boolean - whether a course is locked for the current logged-in user or not. 'status' - ENUM - Pending/Completed 'completed' - Boolean - whether the course is completed or not When a user requests the list of courses, these 3 attributes are calculated for each item in the list before it is compiled and sent back to the user. And this is done for each of the chapters inside the course too. And the chapter might contain upto 30 chapters or so. So this really takes a LOT of time! I've implemented caching as well, but because these values change … -
How to define a field of a model to have a choice from another field of another model of another app?
I have two models defined in two different apps. I want to have a choice option for a particular field in a model, which is deriving those attributes from another field of a model in another app. eg: I have a model "Inventory" that has a field 'title'. class Inventory(models.Model): title = models.CharField('Title', max_length=120, default='') .... I also have another model 'Invoice' that has a field 'line_one'. Both these models are located in different apps. class Invoice(models.Model): line_one = models.CharField('Line 1', max_length=120) .... I created a Django form for adding the Invoice details. I want a choice option for line_one that has all the values stored in the Inventory.title field so that the user can only select those values from a dropdown menu. How can I implement this? Thanks. -
Venda matching query does not exist
ês I don't know how to fix this little problem, I tried to change and change the form, but I still don't understand why it is not reading froms=sales , and when I looked for the error in depth it gave: order_forms Error in formatting: TypeError: unsupported format string passed to NoneType.format> ** MY models ** numero_ven = models.AutoField('Número sequencial da venda',primary_key=True) data_ven = models.DateTimeField('Data e hora da venda',auto_now_add=True,auto_now=False) nf_ven = models.IntegerField('NF',null=True,blank=True) cliente_ven = models.ForeignKey('core.Customer',db_column='cliente_ven',related_name='customer_sale',on_delete=models.CASCADE) formapag_ven = models.ForeignKey(CondPag,db_column='formapag_ven',related_name='forma_pag',on_delete=models.CASCADE) usuario_ven = models.ForeignKey('users.User',db_column='usuario_ven',related_name='usuario_sale',on_delete=models.CASCADE) desconto_ven = models.DecimalField('Desconto',max_digits=7,decimal_places=2,null=True,blank=True) condicao_ven = models.IntegerField('Condição',null=True,blank=True) obs_ven = models.TextField('Observações',blank=True,null=True) frete = models.DecimalField('Frete',max_digits=7,decimal_places=2,null=True,blank=True) seguro = models.DecimalField('Seguro',max_digits=7,decimal_places=2,null=True,blank=True) despesas_acess = models.DecimalField('Despesas acessórias',max_digits=7,decimal_places=2,null=True,blank=True) codigo_transport = models.IntegerField('Código Transporte',null=True,blank=True) placa_veic = models.CharField('Placa veículo',max_length=10,null=True,blank=True) uf_veic = models.CharField('UF veículo',max_length=2,null=True,blank=True) frete_por_conta = models.CharField('Frete por conta',max_length=1,null=True,blank=True) marca = models.CharField('Marca',max_length=10,null=True,blank=True) especie = models.CharField('Espécie',max_length=10,null=True,blank=True) numeracao = models.CharField('Numeração',max_length=10,null=True,blank=True) prev_entrega = models.DateTimeField('Data e hora da previsão de entrega',auto_now_add=True,auto_now=False) setor_ven = models.IntegerField('Setor',null=True,blank=True) precosetor_ven = models.IntegerField('Preço setor',null=True,blank=True) datanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) horanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) imprime_romaneio_ven = models.CharField('Imprime romaneio',max_length=1,null=True,blank=True) cupom_impresso_ven = models.CharField('Cumpom Impresso',max_length=1,null=True,blank=True) prestador_serv_ven = models.IntegerField('Prestador serviço',null=True,blank=True) usuario_atu_ven = models.IntegerField('Usuário atual',null=True,blank=True) data_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) hora_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) cupom_ven = models.IntegerField('Cupom',null=True,blank=True) qtd_vol_ven = models.IntegerField('Quantidade volume',null=True,blank=True) num_venda_antecip_ven … -
Error with form.non_field_errors are not displayed
I try show errors without fieldname identifier. For this i run in template {{ form.non_field_errors }}. But error not displayed. If i run with form.errors the erros are displayed, but with fieldname too, it's not what i want. I use AbstractBaseUser like: models.py class User(AbstractBaseUser): username = models.CharField( verbose_name = u'Nome', max_length=33 ) #identifier email = models.EmailField( verbose_name = u'Email', max_length=255, unique=True, ) phone = models.CharField( verbose_name = u'telefone', max_length=12 ) #... forms.py class SignupForm(UserCreationForm): username = forms.CharField( label=False, max_length=100, required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Nome', 'autocomplete':'off', } )) email = forms.EmailField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Email'} )) email_confirmation = forms.EmailField( required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Confirme o email', 'id': 'email_confirmation', 'class': 'input cemail-cad' } )) phone = forms.CharField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Telefone'} )) password1 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Senha'} )) password2 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Confirme sua senha'} )) class Meta: model = User fields = ['username', 'email', 'phone', 'password1', 'password2'] def clean_username(self): # mínimo 2 caracteres máximo 150 caracteres if not re.compile(r'^\S*[\w\.\-\_\d]{3,150}').match(str(self)): raise ValidationError("Nome inválido: Mínimo 3 caracteres, somente letras, números e '.', '-' ou '_' especiais") def clean_email(self): cleaned_data = super(SignupForm, self).clean() email = cleaned_data.get('email') email_confirmation = cleaned_data.get('email_confirmation') if email != email_confirmation: … -
run initial commands in a docker-compose service
I followed this tutorial to run my django web-app locally, apart for the web-app the only service is a postgres db. I wrote a simple script entrypoint.sh to automate the initial operations needed by a django app, like migrate, makemigrations, collectstatic, createsuperuser; Everything works fine, except that entrypoint.sh runs everytime I use docker-compose up, performing initial operations that should only run once. How can I set up my Dockerfile or docker-compose.yml so that entrypoint.sh is run just the first time and not everytime I docker-compose down and then docker-compose up again? Dockerfile # importing base image FROM python:3.9 # updating docker host or host machine RUN apt-get update \ && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # changing current working directory to /usr/src/app WORKDIR /usr/src/app # copying requirement.txt file to present working directory COPY requirements.txt ./ # installing dependency in container RUN pip install -r requirements.txt # copying all the files to present working directory COPY . . # informing Docker that the container listens on the # specified network ports at runtime i.e 8000. EXPOSE 8000 ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml version: '3.7' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres app: … -
OrgChart in Django and JQuery
I have an app that I created in Django and OrgChart jQuery that displays an organizational workchart. I have UserProfile model that I create every time when user is created so it updates automatically. Right now, I am working on a script that would allow me to add 2 people to the same position and level of hierarchy. For instance, I want to add 2 CEO's on the top of the hierarchy but the function is giving me an error that: MultipleObjectsReturned at /organizational-chart/ get() returned more than one UserProfile -- it returned 2! views.py def work_organizational_chart(request): def recursion(data, profile_id): new_child_list = [] ro = data.filter(supervisor=profile_id) for j in ro: temp = {'profile_id': j.profile_id, 'user_full_name': j.user.get_full_name(), 'email': j.user.email, 'team': j.team.title, 'job_position': j.job_position, 'phone': j.phone_number, 'photo': j.photo.url } temp['children'] = recursion(data, temp['profile_id']) if len(temp['children']) == 0: del temp['children'] new_child_list.append(temp) return new_child_list data_list = UserProfile.objects.filter(profile_id__gte=1) categories = Category.objects.exclude(title="optimazon") final_json = {} cs = data_list.get(team=5) final_json['profile_id'] = cs.profile_id final_json['user_full_name'] = cs.user.get_full_name() final_json['email'] = cs.user.email final_json['team'] = cs.team.title final_json['job_position'] = cs.job_position final_json['phone'] = cs.phone_number final_json['photo'] = cs.photo.url final_json['children'] = recursion(data_list, final_json['profile_id']) return render(request, 'organizational_chart/org_chart.html', {'a_staff': final_json, 'categories': categories}) models.py class UserProfile(models.Model): profile_id = models.IntegerField(primary_key=True) user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE, null=True) body = models.TextField(verbose_name='Job description', … -
How to create Reactive Dropdowns using django to Rank Criteria
I have 4 different Criteria which I need to rank using django forms. something like this Priority 1 : Dropdown (Criteria 1/2/3/4 as different options) Priority 2 : Dropdown (criteria 1/2/3)[basically removes the criteria that they have selected in prority 1) same for priority 3 and 4. I am using django.. Any help -
Getting ImportError: cannot import name 'total_budget_left' from 'walletapp.views' in Django
I am working on one Django web application. And getting the ImportError: cannot import name 'total_budget_left' from 'walletapp.views'. I want to import total_budget_left this variable from one function of walletapp's views.py to another app's views.py 's function. My walletapp.views.py def budgetView(request): preference = UserPreferences.objects.get_or_create(user=request.user) if preference: prefered_currency = UserPreferences.objects.get(user=request.user) budgets = Budget.objects.filter(owner=request.user) total_budget = sum(budgets.values_list('amount', flat=True)) if budgets: for bud in budgets: cdate = bud.created_date edate = bud.end_date expenses = Expense.objects.filter(owner=request.user, date__gte=cdate, date__lte=edate) total_expense = sum(expenses.values_list('amount', flat=True)) total_budget_left = total_budget - total_expense I want to import the variable total_budget_left into another app function myapp.views.py My myapp.views.py from walletapp.views import total_budget_left def index(request): print(total_budget_left) Even after trying multiple ways, I am not able to proceed, please help me with this. Thanks in advance. -
How I do convert an md file to HTML
Here is my code: def title(request, title): try: html = markdown.markdown(util.get_entry(title)) return render(request, "encyclopedia/title.html", { "html": html }) except: return render(request, "encyclopedia/error.html") The issue: The above function convert the content of md file to html and save it into a variable called 'html' and it works. The problem comes when I use this variable in my html file: when I open the html file it displays for example: <h1>Hello World</h1> instead of heading that says Hello World. Thank You -
returning more than one variable in render of django
I define home request in views.py, db=client.inventory_data def home(request): collection_data_1 = db['orders'] mydata = list(collection_data.find()) return render(request,'home.html',{'mydata': mydata}) The above function works fine but when I try to return one more list, it does not work. def home(request): collection_data_1 = db['orders'] collection_data_2 = db['product'] mydata = list(collection_data_1.find()) product_data = list(collection_data_2.find()) return render(request,'home.html',{'mydata': mydata},{'product_data':product_data}) I want to return both the list, how can we achieve this? looking for kind help. -
Axios error when using catch for error processing
I'm using React + Django. Simple backend with one button on frontend handling POST requests: function handleSubmit(e){ e.preventDefault(); axios.post(API_URL, { forklift, battery }).then((response) => { console.log(response) }).catch((error) => { console.log(error.response) }); } The problem is when I try to submit the form while including .catch it always throws an 404 error on first request and then my development server on django crashes on second request (stops). When I delete catching error it works perfectly. function handleSubmit(e){ e.preventDefault(); axios.post(API_URL, { forklift, battery }).then((response) => { console.log(response) }); } My Django API_VIEW @api_view(['POST']) def start_charging(request): if request.method == 'POST': print('test') forklift_ean = request.data['forklift'] battery_ean = request.data['battery'] try: forklift = Forklift.objects.get(for_ean=forklift_ean) battery = Battery.objects.get(bat_ean=battery_ean) except Forklift.DoesNotExist or Battery.DoesNotExist: return Response({'error_message': "No object error"}, status=status.HTTP_404_NOT_FOUND) return Response({"message": "OK"}) Main url.py file urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')) ] App url.py file urlpatterns = [ path('charging/', views.start_charging, name='start_charging'), ] Error on first request: xhr.js:220 POST http://127.0.0.1:8000/api/charging/ 404 (Not Found) Error on seconds request (server crashes): xhr.js:220 POST http://127.0.0.1:8000/api/charging/ net::ERR_CONNECTION_REFUSED Any idea why might be the reason for .catch to act that way? -
{'sub_categories_name': [ErrorDetail(string='This field may not Internal Server Error: /sub_categories/insert_sub_categories/
Hi I am new to DJango nad html,I am making a CRUD on models products ,categories,subcategories,SIze,colors. below is my views function of showing the data of subcategories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) insert function def insert_sub_categories(request): category = ['9-6wear', 'Bridal-Wear', 'desi_swag', 'fusion_wear'] context = {'context': category} if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return render(request,'polls/insert_sub_categories.html',context) else: print(form.errors) return render(request,'polls/insert_sub_categories.html',context) else: return render(request,'polls/insert_sub_categories.html',context) yet when I submit the data which I want to add there is nothing in the show webpage what could be the problem?it isnt visible even in the database