Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
render a markdown file to pdf with rmarkdown::render() and adjust page margins and font
I'd like to render a simple markdown file, that has been created by another process before, into a pdf file. The command: rmarkdown::render(input = "my_report.md", output_format = rmarkdown::pdf_document(latex_engine = "xelatex")) just does this job. However I would like to change the margins and the main font. With an .Rmd file one would define these settings in the Yaml header like this: --- output: pdf_document: latex_engine: xelatex mainfont: LiberationSans geometry: "left=5cm,right=3cm,top=2cm,bottom=2cm" --- But the markdown files I'd like to convert don't have a Yaml header. Is there a way to pass these Yaml options to the render function as function parameters or in an indirect way? -
How to add multiple command with DOCKER to run FASTAPI & CRON job togather
I have a docker file that can run fast API and CRON jobs scheduler separately very well. But I want to run them together how can I do it? Folder Structure: Docker File FROM python:3.8 RUN apt-get update && apt-get -y install cron vim WORKDIR /opt/oracle RUN apt-get update && apt-get install -y libaio1 wget unzip \ && wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip \ && unzip instantclient-basiclite-linuxx64.zip \ && rm -f instantclient-basiclite-linuxx64.zip \ && cd /opt/oracle/instantclient* \ && rm -f *jdbc* *occi* *mysql* *README *jar uidrvci genezi adrci \ && echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf \ && ldconfig WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY crontab /etc/cron.d/crontab COPY hello.py /app/hello.py RUN chmod 0644 /etc/cron.d/crontab RUN /usr/bin/crontab /etc/cron.d/crontab EXPOSE 8000 # run process of container CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"] CMD ["cron", "-f"] -
How to add reply-to address to curl::send_mail?
To be able to receive replies on emails send through a relay, I would need to be able to specify a reply-to address. How can this be done with curl::send_mail? How can I add the Reply-To header? -
Keras loss value very high and not decreasing
Firstly, I know that similar questions have been asked before, but mainly for classification problems. Mine is a regression-style problem. I am trying to train a neural network using keras to evaluate chess positions using stockfish evaluations. The input is boards in a (12,8,8) array (representing piece placement for each individual piece) and output is the evaluation in pawns. When training, the loss stagnates at around 500,000-600,000. I have a little over 12 million boards + evaluations and I train on all the data at once. The loss function is MSE. This is my current code: model = Sequential() model.add(Dense(16, activation = "relu", input_shape = (12, 8, 8))) model.add(Dropout(0.2)) model.add(Dense(16, activation = "relu")) model.add(Dense(10, activation = "relu")) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(1, activation = "linear")) model.compile(optimizer = "adam", loss = "mean_squared_error", metrics = ["mse"]) model.summary() # model = load_model("model.h5") boards = np.load("boards.npy") evals = np.load("evals.npy") perf = model.fit(boards, evals, epochs = 10).history model.save("model.h5") plt.figure(dpi = 600) plt.title("Loss") plt.plot(perf["loss"]) plt.show() This is the output of a previous epoch: 145856/398997 [=========>....................] - ETA: 26:23 - loss: 593797.4375 - mse: 593797.4375 The loss will remain at 570,000-580,000 upon further fitting, which is not ideal. The loss should decrease by a few more orders of magnitude … -
Package glib-2.0 was not found in the pkg-config search path in RHEL8
Package glib-2.0 was not found in the pkg-config search path. Perhaps you should add the directory containing `glib-2.0.pc' to the PKG_CONFIG_PATH environment variable Package 'glib-2.0', required by 'virtual:world', not found cc -std=c99 -Os -Wall -Wextra -Werror -DVERSION="2.1.5" -DGIT_COMMIT=""6686b9342d73c56a55574700be9814ea46a3ed35"" -o src/conmon.o -c src/conmon.c In file included from src/conmon.c:8: src/utils.h:9:10: fatal error: glib.h: No such file or directory #include <glib.h> ^~~~~~~~ compilation terminated. make: *** [Makefile:71: src/conmon.o] Error 1 -
Yandex Disk api image link gets 403 error when the image is added from javascript
I have a python script that uploads images to Yandex Disk using the yadisk module. The script looks like this: def uploadYandexDisk(path, filename): try: y.upload(filename, path) y.publish(path) # I don't know if this is necessary return y.get_download_link(path) except Exception as e: print(e) return None I get a link that looks similar to this: https://downloader.disk.yandex.ru/disk/bfa79f689c05d8baadcf95f4d3ed8fbb29c6cfa9f6e0204a27bfe58bf4ecf1b4/63c85be8/dxysKH9-IRe0fopHnDA9GGf54mxrEpFtdH4pyMm2uqkUclp7t5xT1rW_NQ-wSsohWwsfbUVUDT5YqkHthwEj4g%3D%3D?uid=1070951606&filename=apple-xxhkw-caquk.png&disposition=attachment&hash=&limit=0&content_type=image%2Fpng&owner_uid=1070951606&fsize=675526&hid=a49cfeb39e5819728ee8221f113b4fbd&media_type=image&tknv=v2&etag=0eb79b7987ca12d70612a2c581c6239d When I open the link in my browser and even in incognito mode where I'm not logged in to Yandex, it works. And it also works when I directly put the link in the html without any javascript. But when I try to put the link in the src of an img using javascript I get a 403 not authorized error in the console. Is there a way to fix this or any workarounds? -
Unable to fix Node Path in packaged Electron App
I'm building a simple Electron app for MacOS (using React as the frontend). The purpose of the app was to make executing certain terminal commands a lot easier. Primarily I am interested in using the sfdx Salesforce CLI commands. When I run the app in dev, everything works fine. However when I package the app, the PATH variable gets changed and I'm no longer able to locate the sfdx library. (*note it is still able to find git commands though). I found a very similar issue here and a bug report in GitLab, both of which recommend the use of the fix-path package. This is where I run into another issue. According to the docs, I should import the package like this: import fixPath from 'fix-path'; However when I do that inside of my electron.js file I get this error: SyntaxError: Cannot use import statement outside a module. I've seen other resources that use require to bring in the package: const fixPath = require('fix-path'); But again, when I do that I get this error require() of ES Module not supported. I tried adding "type": "module" to my package.json file, but that breaks my app as well. I feel like there … -
Django custom HTML template not returning any values to the admin.py
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page. The value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none The Html template {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %} {{ media }} {% endblock %} {% block content %} <form class="change_superprofile_parent_form" met`your text`hod="POST" class="change_superprofile_parent_form">{% csrf_token %} {% for superprofile in superprofiles %} <input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br> {% endfor %} <input type="submit" value="Submit"> </form> {% endblock %} Django admin.py ''' def change_superprofile_parent(self, request, queryset): """ Action to change the superprofile of the selected """ queryset = queryset.values_list("id", flat=True) if request.method == 'POST': selected_value = request.POST.getlist('superprofile_selected') eligible_superprofiles = SuperProfile.objects.filter(status='Active') return render( request, 'admin/auth/user/change_superprofile_parent.html', context={ 'superprofiles': eligible_superprofiles, } ) ''' -
React + django, not being able to render detail view
I'm having some trouble fetching data from my modules when it comes to detail views. Basically I have news that are displayed, and then I want the user to be able to click the news and get to a detail view of that news. The fetching works fine when the url is just localhost/Nyheter (news in swedish) but not when I add an id after (localhost/Nyheter/10). This is the relevant code (I hope). I might be missing something very basic, but I've looked around for a while and it can't make it make sense, thanks in advance! NewsItemPage.js class NewsItem extends Component{ state={ item: {} } id = this.props.params.match.id; async componentDidMount(){ try { const res = await fetch("http://localhost:8000/api/news/"+this.id); const item = await res.json(); console.log(item); this.setState({ item }) }catch(e){ console.log(e); } } App.js function App() { return ( <Router> <Navigation /> <Routes> <Route path="/" element={<Home />}> Hem </Route> <Route path="/Nyheter" element={<News/>}>Nyheter</Route> <Route path="/Nyheter/:id" element={<NewsItemPage/>}>Nyheter-detaljer</Route> <Route path="/om-oss">Om oss</Route> <Route path="/kontakt">Kontakt</Route> </Routes> <Footer /> </Router> ); serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' lookup_field = 'id' views.py @api_view(['GET']) def news_list(request): if request.method == 'GET': data = News.objects.all() serializer = NewsSerializer(data, context={'request': request}, many=True) return Response(serializer.data) urls.py from hemsida import … -
Comparing numbered urls in django template
In urls.py I have: path("viewer/<str:case>", views.viewer, name="viewer"), This works when I go to the viewer: <a class="nav-link dropdown-toggle {% if request.resolver_match.url_name == "viewer" %}active{% endif %}"> Now, there is a menu in nav bar that lists cases. I need to know which specific page I'm on to make one of menu items active: {% for item in cases %} <li> <a class="dropdown-item {% if request.get_full_path == "/viewer/{{ item.id }}" %}active{% endif %}" href="/viewer/{{ item.id }}">{{ item.patient_name }}</a> </li> request.get_full_path returns /viewer/47 for example and one of the items is 47. I've tried different combinations instead of "/viewer/{{ item.id }}, nothing works. -
Extra Cruft in Django URLs
I have a project that is over ten years old. I recently upgraded it to Django 4.1.x. I have a url that looks like this: re_path( r"^author/([a-z-]+)/post/([a-z0-9-]+)/$", research_views.display_article, name="display_article", ), This is what I want to see in the browser's URL bar: http://localhost:8000/author/hank-johnson/post/guam-tips-over/ But if I add extra cruft to the URL it gets displayed and never gets trimmed out of the URL bar. http://localhost:8000/author/hank-johnson/post/guam-tips-over/?---adf That's a problem because Google is now accumulating malformed URLs in its index. How do I ensure that the final "/" is indeed the final slash and no extra cruft can be appended to the URL? -
Meta class: indexes vs ordering
I've encountered with below fields in Meta class. According to author the 'indexes' of the 'created' field is for optimazing the query, but isn't 'ordering' for that? class Image(models.Model): ... created = models.DateField(auto_now_add=True) class Meta: indexes = [ models.Index(fields=['-created']) ] ordering = ['-created'] -
Django-restframework - use the same value on differents fields
I'm building an API using Django-restframework. models.py class Researches(models.Model): research_id = models.BigAutoField(primary_key=True) I would like to use the same value on two differents fileds, like: [ { "research_id": 1, "id": 1 }, ] Is it possible? -
Django Rest Framework - How can I get the unlimited depth of a specific field in a serializer
I have posts and replies to posts. Replies can have parents unless the reply is the top reply. Like twitter you can reply to a reply and if you click on a reply you can see the reply and the parents of the reply so there is a hierarchy of replies. I have two questions please. ONE: How can I display the hierarchy in an endpoint so it goes as far as the rabbit hole goes? At the moment I only see the reply and then the parent of that reply. I cannot see the parent of the parent of the reply. It stops on the first level upwards? I don't want to make the depth setting to be more than 1, so looking for an alternative way or maybe the better or correct way. Here is my post serializer: class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) profile = serializers.SerializerMethodField() replies = PostRepliesSerializer(many=True, read_only=True, required=False) class Meta: model = Post fields = [ "id", "can_view", "can_comment", "category", "body", "images", "video", "profile", "published", "created_at", "updated_at", "replies", ] depth = 1 def get_profile(self, obj): profile_obj = Profile.objects.get(id=obj.user.profile.id) profile = ShortProfileSerializer(profile_obj) return profile.data def create(self, validated_data): user = User.objects.get(id=self.context['request'].data.get('user')) category = Category.objects.get(id=self.context['request'].data.get('category')) new_post … -
How to change Q from AND to OR - Python with Django
I have a simple E-commerce where I want a product filter for users. In this case I want to filter the cars by color through a checkbox form. But when I do the for on the selected colors, it creates a Q(AND: ) filter, and I wanted it to be a Q(OR: ) filter. How do I change it ??? Index.html: <div class="widgets-area mb-9"> <h2 class="widgets-title mb-5">Cores</h2> <div class="widgets-item"> <form id="widgets-checkbox-form" action="{% url 'carro_filtro' %}" method="GET"> <ul class="widgets-checkbox"> {% for cor in cores %} <li> <input class="input-checkbox" type="checkbox" id="color-selection-{{ cor.id }}" name="termo" value="{{ cor.nome_cor }}"> <label class="label-checkbox mb-0" for="color-selection-{{ cor.id }}"> {{ cor.nome_cor }} </label> </li> {% endfor %} </ul> <input type="submit" class="btn btn-custom-size lg-size btn-primary w-100 mb-5 mt-5" value="Filtrar"> </form> </div> </div> Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.CarView.as_view(), name='shop'), path('filtro/', views.CarroFiltro.as_view(), name='carro_filtro'), ] Views.py: class CarView(ListView): model = Car template_name = 'shop/index.html' paginate_by = 12 context_object_name = 'cars' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['personalizacoes'] = Shop.objects.filter( publicado_shop=True).order_by('-id').first() context['categorias'] = Categoria.objects.all() context['cores'] = Cor.objects.all() return context def get_queryset(self): qs = super().get_queryset() categoria = self.kwargs.get('nome_categoria', None) if not categoria: qs = qs.filter(publicado=True).order_by('-id') return qs qs = qs.filter( categoria_carro__nome_categoria__iexact=categoria, publicado=True).order_by('-id') return qs class … -
How do I create a ManyToMany field that is based on another field?
Suppose I have the following models: class ProductFamily(models.Model): family = models.CharField(primary_key=True, max_length=200) class SubFeature(models.Model): # this is all the subfeatures across all products tag = models.CharField(primary_key=True, max_length=64, verbose_name="tag") label = models.CharField(max_length=64, verbose_name="label") description = models.CharField(max_length=256, verbose_name="description") configurable = models.BooleanField(default=False) class Product(models.Model): product_name= models.CharField( primary_key=True, max_length=64, verbose_name="product") family = models.ForeignKey( ProductFamily, on_delete=models.CASCADE) core_subfeature = models.ManyToManyField( SubFeature, blank=True, related_name="core") optional_subfeature = models.ManyToManyField( SubFeature, blank=True, related_name="optional") class Meta: constraints = [models.UniqueConstraint(fields=['product_name', 'family'], name='unique_products'), models.UniqueConstraint( fields=['product_name', 'core_subfeature'], name='unique_core_subfeatures'), models.UniqueConstraint(fields=['product_name', 'optional_subfeature'], name="unique_optional_subfeatures")] class ProductOrders(models.Model): customer = models.CharField(max_length=400) product_family = models.ForeignKey( ProductFamily, on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) product = models.ForeignKey( Product, on_delete=models.PROTECT, blank=True, null=True) Note that the first three models will contain data about the products and the ProductOrders model will get fed data when a form is filled in. Now, I want to add the fields "core_subfeature" and "optional_subfeature" to ProductOrders, but I want to make sure that the user only gets presented optional subfeatures that are available for that Product (core subfeatures will be pre-filled for the user, as these are fixed to a product). I have tried ForeignKey (to Product table) but that requires the fields to be unique across the table I think, but one subfeature can be part of many products, so … -
Django Model Query (Getting Categories based on posts)
Please I need help with a django model query. I am working on a blog app, with a model for posts and a model for categories. In my categories page I want to show all my categories but with a single post from each of those categories. e.g enter image description here I want a card with a single post from each category I tried running a loop but I'm getting confused Please help 🙏🙏 enter image description here I tried running the loop like this but it brings no results in the template -
how can I activate the cancel button in the confirm dialog with Django?
I am using javascript with the Django framework to show the confirmation dialog message before submitting the blog. But the problem is when the user clicks the cancel button, it still performs and posts the blog. <body> <form method="POST" enctype="multipart/form-data" class="new-qiestion-form" id="FormConfirmation"> {% csrf_token %} <div class="fieldWraber"> <label for="{{form.title.id_for_label}}">Title</label> {{form.title}} <span style="text-align: right;" class="error">{{form.title.errors}}</span> </div> <div class="fieldWraber"> <label for="{{form.body.id_for_label}}"><bdi> Tags </bdi></label> <input type="text" data-role="tagsinput" class="form-control" name="tags" required> </div> <div class="fieldWraber"> <label for="{{form.body.id_for_label}}">Content</label> <bdi dir="rtl" style="text-align: right;"> {{form.body}} <span style="text-align: right;" class="error">{{form.body.errors}}</span> </bdi> </div> <div class="fieldWraber"> <label for="{{form.body.id_for_label}}"><bdi>اضافة مرفق:</bdi></label> {{form.attach}} </div> <div> <button type="submit" onclick="clicked();" class="submit-button" style="color: aliceblue;"> <i class="fa fa-paper-plane" aria-hidden="true"></i> Submit </button> </div> </form> </div> </div> <script type="text/javascript"> function clicked() { if (confirm('Do you want to submit?')) { document.getElementById("FormConfirmation").submit(); } else { return false; } } </script> </body> {% endblock %} -
Django model get current user without request
I am trying to get a user inside the django_filter model, can anyone help me with how to do that? import django_filters from .models import AgentVoucher from django_filters import DateFilter, ChoiceFilter, DateFromToRangeFilter, widgets, ModelChoiceFilter from agent.models import Agent from django import forms from company.models import Employee from django_currentuser.middleware import ( get_current_user, get_current_authenticated_user) class AgentVoucherFilter(django_filters.FilterSet): date = DateFromToRangeFilter(widget=widgets.RangeWidget(attrs={'class':'form-control', 'type':'date','placeholder': 'd/m/Y'})) agent = ModelChoiceFilter( queryset =Agent.objects.filter(company = "1"), #here I want company = request.user.company widget = forms.Select(attrs={'class': 'form-control select2'}) ) class Meta: model = AgentVoucher fields = ['date', "agent" ] I am trying to use company = request.user.company class AgentVoucherFilter(django_filters.FilterSet): date = DateFromToRangeFilter(widget=widgets.RangeWidget(attrs={'class':'form-control', 'type':'date','placeholder': 'd/m/Y'})) agent = ModelChoiceFilter( queryset =Agent.objects.filter(company = request.user.company), widget = forms.Select(attrs={'class': 'form-control select2'}) ) class Meta: model = AgentVoucher fields = \['date', "agent" \] -
providing the user a map to select a location on a map
So the thing I'm looking for is a way to get a location from user on the map. and store the lat and long in a model for later use. I couldn't find any solutions googling. Thx! -
How do I change input type of form field in django forms?
I have a form class in my form.py file where I initiated properties of form fields. I want to change my 'Description' field from an input field to a textarea field of height 5 lines. Also want to change my 'Deadline' field to a date input field because at the moment it's an input text field. class JobPost_form(ModelForm): class Meta: model = Job_post fields = "__all__" def __init__(self, *args, **kwargs): self.fields['Job_role'].widget.attrs.update( {'class': 'form-control Password2', 'id': 'form3Example1c', 'placeholder': 'Job role'}) self.fields['Company'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Company'}) self.fields['Deadline'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'YYYY-MM-DD HH:MM:SS'}) self.fields['Description'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Description'}) -
Selenium thread only works once
I have a dockerized Django app with some threads. Those threads perform periodic tasks, and use Selenium and Beautiful Soup to scrap data and save it to the database. When initializing one thread, the first scrap goes well, data is checked and the function sleeps. However, when the sleep finishes the next scrap isn't performed. This is the thread head code: def thread1(): time_mark = 0 while True: print('Thread1 START') op = funct_scrap(thread1_url) ... sleep(60) The funct_scrap scrapes the web using Selenium, works for the first time but it stops after that. I'd need it to check periodically. In development server works well, but now on Docker there is this problem. What's going on? -
Apex charts only shows latest django value as opposed to latest 12 results
I am trying to get Apex Charts to log values from my django view but I am only getting the most recent value as opposed to the latest 12 values. I may need to do something in javascript to get this to work (like map), but I am struggling to think of what to try next... My Django Model: from django.db import models from datetime import datetime class Telemetry(models.Model): building_name = models.CharField(max_length=200) space_type = models.CharField(max_length=200) reference_point = models.CharField(max_length=100, help_text='eg: ASP') temperature_value = models.DecimalField(max_digits = 5, decimal_places = 2) people_sensor_value = models.IntegerField() humidity_value = models.DecimalField(max_digits = 5, decimal_places = 2) co2_value = models.DecimalField(max_digits = 5, decimal_places = 2) voc_value = models.DecimalField(max_digits = 5, decimal_places = 2) time_stamp = models.DateTimeField(default=datetime.now, blank=True) class Meta: verbose_name = 'Console Value' verbose_name_plural = 'Console Values' def __str__(self): return self.space_type My Django View: def chart_view(request): if not request.user.is_authenticated: return HttpResponseRedirect('/') else: console_points = Telemetry.objects.all()[:12] context = { 'console_points': console_points } return render(request, 'charts/line_charts.html', context) My HTML Template: {% load static %} {% load humanize %} {% block content %} {% for console_point in console_points %} {{ console_point.voc_value }} {{ console_point.time_stamp|naturaltime }} {% endfor %} <section class="row gap-1 justify-center"> <div class="col-1-xs"> <div class="card bg-white"> <div class="card-body"> <h3>Office Temperature</h3> … -
How to save a unique search result in django
I want the user to save individual search result when they click on the star button as shown below in the SS: figure 1 This results are not from the database but rather they are collected from an API.When the user clicks on the "star" button beside each search result,I want this data to be saved in the database.When the star button is pressed,I want this entire piece of data to be passed on to an approrirate function to save it in the database.I need help in forming the url when the button is pressed.Given below is the html part for the "star" button: <a href="#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" class="feather feather-star" > <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon> </svg> </a> </div> ` ` I was thinking of generating unique id for each search result and then pass this along with the url.But dont know how to create the url pattern. -
Can I add search field more than one in django admin
I want to know about can I add another search field more than one. If it can't how can I do for this action I use a long time to solve this problem