Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework using Template to send an e-mail
I want to send a styled email using HTML tags. The mail is sent successfully but without style and the HTML tags are presented as a text in the email. handles.py @receiver(order_created) def on_order_created(sender, **kwargs): order=kwargs['order'] capture_email= order.customer.user.email name= order.customer.user.username title= 'Thank you ' + name order_items=OrderItem.objects.filter(order=order) template= render_to_string('index.html',{'order_items':order_items,'name':name}) # text_content = strip_tags(template) email =EmailMessage( title, template, settings.EMAIL_HOST_USER, [capture_email], ) email.fail_silently=False, email.send() -
What Causes 400 Bad Request In Django Graphene and NextJs Using The useMutation Hook?
I am trying to build a simple todo app using Django, Graphene and NextJs. I was able to create todos in graphiQL and postman, however when I try to create a todo in the NextJs, I get a 400 Bad Request from the server. I have tried to do same using plain ReactJs but I still get the same error. Below is the error This is my models.py file from django.db import models class Todo(models.Model): title = models.CharField(max_length=255) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my todos/schema.py file import graphene from graphql import GraphQLError from .models import Todo from graphene_django import DjangoObjectType class TodoType(DjangoObjectType): class Meta: model = Todo class Query(graphene.ObjectType): todos = graphene.List(TodoType) def resolve_todos(self, info): return Todo.objects.all() class CreateTodo(graphene.Mutation): todo = graphene.Field(TodoType) class Arguments: title = graphene.String() def mutate(self, info, title): user = info.context.user if user.is_anonymous: raise GraphQLError('Login to add a todo!') todo = Todo(title=title) todo.save() return CreateTodo(todo=todo) class Mutation(graphene.ObjectType): create_todo = CreateTodo.Field() this is my apollo-client.js file import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client"; const httpLink = createHttpLink({ uri: "http://localhost:8000/graphql", }); const client = new ApolloClient({ link: httpLink, credentials: "include", cache: new InMemoryCache(), }); export default client; This … -
Visual geograph map with coordinates using Django in html/js?
I made the following function in views.py to return a json response of coordinates. The function is: def dispatch(request): events = Event.objects.filter(description="Dispatch").values("element") starts = Start.objects.all() ends = End.objects.all() d_starts = { s['start_id']: s for s in start } d_ends = { c['end_id']: c for c in end } d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]], 'end': d_ends[e['element'][69:75]] } for e in events ] for d in d_start_end_ids: dispatch_data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])} JsonResponse(dispatch_data) The json response of coordinates with the following structure start -> end: [53.5011961270582, -1.12708338945015] -> [53.34474, -3.01101] [53.5011961270582, -1.12708338945015] -> [53.34474, -3.01101] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] Whats the best way of showing each line from start to end on a geomap ideally using OpenLayers? Is this a good way of going abuot it? Thanks! -
Trying to migrate an old project from python2 to python3 and got stuck in this error in urls.py
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) *File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 112, in format_suffix_patterns return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 59, in apply_suffix_patterns regex = urlpattern.pattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern AttributeError: 'tuple' object has no attribute 'pattern'* -
Need to override save method for image field and save it as base64 string using django
models.py class Organisation(models.Model): org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I need to save an image which I get in image field on org_logo as a base64 string and upload it to the s3 bucket which I have given as file storage using django storages. Note: File object will be the input I will be getting from the frontend(React). I need to override the save method to save it as base64 string. I have referred many data but I couldn't able to get it properly. Can anyone please guide me to what exactly needs to be changed and where so that I could understand better. -
Only accept 2 digits integer array in django model form
How to make a form field that accept 2 digit numeric array in frontend. if someone enter more then 2 digit or string then The input value is automatically validated to ensure it is a properly formatted 2 digit integer array. right wrong below My work models.py class Jodi(models.Model): numb = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True) forms.py from django import forms from .models import Jodi class MyModelForm(forms.ModelForm): class Meta: model = Jodi fields = ['numb',] views.py if request.method=='POST': fm = MyModelForm(request.POST) if fm.is_valid(): numbers = fm.cleaned_data['numb'] numbers1 = [] for x in numbers: if x: numbers1.append(x) X=Jodi.objects.create(numb=numbers1,) X.save() else: fm = MyModelForm() return render(request,'myapp/home.html',{'form':fm}) home.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} -
Get working link in 'currently' field of a file field django admin
I have a model with a FileField and when I go on the admin page and want to modify the file, this page show up. On the 'file' field there is a link which you'd think would either download the file or display its content, but by clicking on it, it tries to go to the displayed link instead of going to the actual file link : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/media/scripts/Script%20hello/hello.py Using the URLconf defined in Website.urls, Django tried these URL patterns, in this order: scripts/ admin/ __reload__/ The current path, media/media/scripts/Script hello/hello.py, didn’t match any of these. Is it possible to modify the link in order to download the file ? -
how to have multiple user types in django
this app is a school management system with django i have three types of user in my web app, my problem is how to authorize these and give them permissions. users are: teacher, student, school staff(admins) i need to have different pages(apps) for each of them, like: teacher -> login -> teacher_app. student -> login -> student_app. im new in django my models are something like this: class Student(models.Model) : national_id = models.CharField( max_length=50, unique=True, ) name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=50) class Teacher(models.Model) : personal_id = models.CharField( max_length=50, unique=True, ) name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField( max_length=50, unique=True, ) email = models.EmailField( max_length=250, unique=True, ) class Class(models.Model): name = models.CharField(max_length=50) start_time = models.TimeField( auto_now=False, auto_now_add=False, default=DEFAULT_START_TIME, ) end_time = models.TimeField( auto_now=False, auto_now_add=False, default=DEFAULT_END_TIME, ) # Relations teacher = models.ForeignKey( Teacher, on_delete=models.CASCADE ) students = models.ManyToManyField(Student) admins will create classes and add students and teachers. -
Can I change model admin verbose name based on user group login in django?
I am aware of the Model Meta tag to specify the verbose_name, verbose_name_plural. But require the verbose name in model admin based on user login based on the group he is in. How can we override this attribute? -
Selectively hit the update signal for a model
I have a model called as nodes: class node(models.Model): name = models.CharField(max_length=200) status = models.CharField( max_length=32, choices=[], # some list of choices ) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name A node has a status. There can be nodes which are dependent on the status of a particular node. For example: node B,C is dependent on node A. Node D is dependent on node B. I have a post_save signal which is triggered when the status of a particular node is changed. What I want: When I change the status of A, the status of B and C should also change accordingly. And since node D is dependent on node B, the status of D also should change as per the node B's new status. Problem: The post_save signal hits everytime the change of any of these nodes is changed. So for example, an update signal will be fired when status of A is changes. I would then want to change the status of B and C in this trigger. But as soon as the status of B changes, the post_Save signal will again be hit and the code would not even reach to … -
django not geeting ?next=/ without ?next=/ I couldn't get the same page that I want before
Hello everyone please help me to find out this problem I want a URL like http://127.0.0.1:8000/baseaccount/vender_login/?next=/login/ but I am getting http://127.0.0.1:8000/baseaccount/login/ basically, ?next=/ is missing that why after login I couldn't go to the same page that I want before. -
How to load data from multi-level nesting object
``` when i do the School.objects.filter() query , how to load student object in single query using School.objects.filter() ``` class School(models.Model): name = models.CharField(max_length=50) grade = models.ForeignKey(Grade) class Grade(models.Model): name = models.CharField(max_length=10) class Student(models.Model): name = models.CharField(max_length=50) grade = models.ForeignKey(Grade) when i try to load the student object using the school.objects.filter(), its load only school object, when i use select_related('grade'), its load grade object in single sql query how can i use select_related('student'), with school.objects.filter() -
decreasing values with loop in Django
in this code, I tried to decrease the quantity of products from the database when the user places the order, it is working but the problem is just decreasing from the first product in the cart? new_order_items = Cart.objects.filter(user=request.user) for item in new_order_items: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.selling_price, quantity=item.product_quantity ) # decrease the product quantity from table order_product = Product.objects.filter(id=item.product_id).first() order_product.quantity = order_product.quantity - item.product_quantity order_product.save() -
while hitting create api on postman "error": "hashpw() argument 1 must be str, not bytes" is coming
code for create user try: # If it's social login that is from Google, Facebook or Apple if 'social_login_id' in request.data and request.data['social_login_id'] != 0: schema = { "email": {'type': 'string', 'required': False, 'nullable': True}, "device_token": {'type': 'string', 'required': True, 'empty': False}, "device_type": {'type': 'number', 'required': True, 'empty': False}, "social_token": {'type': 'string', 'required': True, 'empty': False}, "social_login_id": {'type': 'number', 'required': True, 'empty': False} } else: # If email id already exist if User.objects(email=request.data.get('email').lower()).first(): return Response({'error': Messages.EMAIL_EXITS}, status=status.HTTP_200_OK) # If username already exist if User.objects(username=request.data.get('username')).first(): return Response({'error': Messages.USERNAME_EXITS}, status=status.HTTP_200_OK) schema = { "first_name": {'type': 'string', 'required': True, 'empty': False}, "last_name": {'type': 'string', 'required': True, 'empty': False}, "username": {'type': 'string', 'required': True, 'empty': False}, "email": {'type': 'string', 'required': True, 'empty': False}, "password": {'type': 'string', 'required': True, 'empty': False}, "device_type": {'type': 'integer', 'required': True, 'empty': False}, "device_token": {'type': 'string', 'required': True, 'empty': False}, "social_token": {'type': 'string', 'required': False, 'nullable': True}, "social_login_id": {'type': 'integer', 'required': True, 'empty': False}, } v = Validator() # validate the request if not v.validate(request.data, schema): return Response({'error': v.errors}, status=status.HTTP_400_BAD_REQUEST) # Create new user utility = hashingUtility() hashed_model = utility.getHashedPassword(request.data["password"]) User.objects.create( first_name=request.data["first_name"], last_name=request.data["last_name"], username=request.data["username"], email=request.data["email"], password=str(hashed_model.Password, 'utf-8'), password_salt=str(hashed_model.Salt, 'utf-8'), device_type=request.data["device_type"], device_token=request.data["device_token"], social_token=request.data["social_token"], social_login_id=request.data["social_login_id"], is_active=1, is_deleted=0 ) # Get inserted user … -
Docker Container not loading static files from Django-React Project
I've been trying to get my main.js file and css static files to load in my container and on google cloud for the past 4 days. Here is my file tree: main/ - frontend/ - node_modules/ - src/ -components/ - index.js - static/ - frontend/ - css/ - main.js - templates/ - frontend/ - index.html - package.json - pack-lock.json - nginx/ - main_project/ - Dockerfile - docker-compose.yml - requirements.txt My docker file has the following: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /pathfinder COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY ./entrypoint.sh / ENTRYPOINT ["sh", "entrypoint.sh"] RUN apk update RUN apk add RUN apk add npm COPY ./frontend/package.json /frontend/package.json COPY ./frontend/package-lock.json /frontend/package-lock.json RUN cd frontend/ && npm install my docker-compose.yml folder looks like the following: version: "3.8" services: pathfinder_gunicorn: build: context: . volumes: - static:/static - ./frontend/static/:/pathfinder/frontend/static/ ports: - "8080:8080" image: pathfinder_gunicorn:v1 container_name: pathfinder_gunicorn nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - pathfinder_gunicorn volumes: static: Can someone please tell me what is going on and why can't I load my js and css files onto my index.html page? -
Integrating Scrapy into Django/React application
I'm trying to build a site with Django and React, where you can create watchlists with companies. If you view the watchlist, you'll be able to see the price of given companies. In Django I have a model for the companies, but these are without price (since it has to be reasonably up-to-date). So you'll load a list of companies using their models, then use the symbol to get the price from somewhere else. I've looked into API's, but I couldn't find an API (for free) where a can get an variable list of companies with their price. So I thought maybe getting the data myself by scraping it would be an option. Haven't done much scraping, but is it possible to scrape data on the client side (implementing it in React)? And/or how would you approach this? -
How do I whitelist this URL on pythonanywhere
please how can I add below website endpoints to whitelist, thank you https://kingsvtu.com/app/api/v1/products/airtime https://kingsvtu.com/app/api/v1/products/data https://kingsvtu.com/app/api/v1/products/cable https://kingsvtu.com/app/api/v1/products/exam https://kingsvtu.com/app/api/v1/products/power this is the link to the API documention below https://documenter.getpostman.com/view/12161048/Tzm3oxwr#d5672aa5-32ad-4118-bd46-080799fbfd68 -
In a learning example: Djangos DRF can't get parameters when vue AXIos uses POST? thank you
vue.js code: enter image description here django drf: enter image description here -
Integrating Django with AG Grid
Good evening folks, I am trying to represent a relatively simple excel document as part of a grid using the plain JavaScript version of AG Grid community. I have a couple functions to get the header row and the data, as below: def get_excel_data_headers(): path = Path("/Users/excel_doc.xlsx") df = pd.read_excel(path, header=0) return df.columns def get_excel_data(): path = Path("/Users/excel_doc.xlsx") df = pd.read_excel(path, header=0) cell = [] for rowIndex, row in df.iterrows(): #iterate over rows for columnIndex, value in row.items(): #print(value, end="\t") cell.append(value) return cell and my views.py class excel(ListView):#The project detailed view of all submitted info model = Project template_name = "home/grid_upload.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['headers'] = get_excel_data_headers() context['row_data'] = get_excel_data() return context However I am unsure how to represent this in the template. I can get the header row to work however I don't know the best approach to add the data as the argument requires the header row to be specified for each row data item but this is set as part of a different for loop, below is my current template code however it docent render correctly and I am lost in the direction to properly implement this, <script type="text/javascript" charset="utf-8"> // specify the columns … -
Do I need to install MySQL Server for each of my pipenv virtual Environments?
I have installed mysql in my ubuntu 22 and it is running, when I try to install msqlclient in my virtual environment, it gives the following error. error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-rsjsl_3h/mysqlclient_0fd0dd46119841d69cac324129f28afd/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-rsjsl_3h/mysqlclient_0fd0dd46119841d69cac324129f28afd/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-rsjsl_3h/mysqlclient_0fd0dd46119841d69cac324129f28afd/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] Is it because I didnt install mysql in the active virtual environment? -
Ad security checks in graphene resolver
I am using Django and Graphene to serve a graphql endpoint and I have hit a bit of a Problem I cant seem to figure out. I have following resolver: class Query(ObjectType): trainingSession = Field(TrainingSessionType, id=graphene.ID()) trainingSessions = DjangoFilterConnectionField(TrainingSessionType) @staticmethod def checked_trainingsession(trainingsession,info): # returns the trainingsession if a certain logic is fulfilled # else None def resolve_trainingSessions(root, info,**kwargs): ids= kwargs.get('discipline__id') all = TrainingSession.objects.all() result = [] for trainingSession in all: trainingSession = Query.checked_trainingsession(trainingSession,info) if trainingSession != None: result.append(trainingSession) return result together with the Objects types and Filters: class TrainingSessionFilter(FilterSet): discipline__id = GlobalIDMultipleChoiceFilter() class Meta: model = TrainingSession fields = ["discipline__id"] class TrainingSessionType(DjangoObjectType): class Meta: model=TrainingSession fields="__all__" filterset_class = TrainingSessionFilter interfaces = (CustomNode,) class CustomNode(graphene.Node): """ For fetching object id instead of Node id """ class Meta: name = 'Node' @staticmethod def to_global_id(type, id): return id however when I try to execute a query query Sessions{ trainingSessions(discipline_Id:[2,3]){ edges{ node{ dateTime, discipline{ id } } } } } I get the Error: Traceback (most recent call last): File "D:\Ben\GitHub-Repos\dojo-manager\env\lib\site-packages\promise\promise.py", line 489, in _resolve_from_executor executor(resolve, reject) File "D:\Ben\GitHub-Repos\dojo-manager\env\lib\site-packages\promise\promise.py", line 756, in executor return resolve(f(*args, **kwargs)) File "D:\Ben\GitHub-Repos\dojo-manager\env\lib\site-packages\graphql\execution\middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "D:\Ben\GitHub-Repos\dojo-manager\env\lib\site-packages\graphene_django\fields.py", line 176, in connection_resolver iterable = queryset_resolver(connection, … -
Where to Host Django Rest API
I am having a Django Rest API for my Business and I want to host it live. I am getting confused with AWS or GCP or Heroku paid services. I need something easy to use like Heroku and Robust like GCP. What do the you recommend? also how can I get the best deal in no time??? -
Django / OnetoMany relation within the same class
Here is my models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) previous = models.OneToOneField( 'self', blank=True, null=True, related_name='next', on_delete=models.SET_NULL ) I have started with one instance : Scene1 The problem is I want to have on to many choices and not one to one like explained below Nevertheless, When I change to previous = models.ManyToManyField( Then I also get an error about on_delete : TypeError: init() got an unexpected keyword argument 'on_delete' What would be the best djangonic way ? -
IntegrityError NOT NULL constraint failed: even though I have already overriden the form_valid?
So I'm trying to create a simple Comment feature for a blog app. In the Class-based views, if you are using a Foreign Key in your model, I know that you have to override the def form_valid: in order for the Comment to be posted by the current logged-in User. If you don't, you get the IntegrityError I did this for the Blog model in my app, and it works just as intended, however, when I try to do the same with the CommentCreateView, I get the error. Here's my code so far views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['title', 'content'] template_name = 'issues/add_comment.html' def form_valid(self, form): form.instance.name = self.request.user return super().form_valid(form) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, null=True) content = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) class Issue(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) What did I do wrong? -
Django: Permission denied when loading a Font using xhtml2pdf
An error occurs when trying to load a TTF font within an HTML file that is to be converted to PDF using xhtml2pdf. The error only occurs when loading fonts, and doesn't occur with other types of static files. I need to load a font because I'm using Arabic in my PDF and it is appearing as blocks instead (English is fine). The error is coming from the "reportlab" portion of the plugin. The Error: TTFError at /ar/task/statements/preview/1 Can't open file "C:\Users\DESTRO~1\AppData\Local\Temp\tmpq5b82hlj.ttf"` Screenshot of the error: Screenshot Screenshot of why I need to install another font (if you have an alternative solution): The blocks are Arabic characters incorrectly displayed