Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pine Script capture 24hrs Change
I'm currently coding a Pinescript Strategy for my AutoTrading but I need just one more condition and that is the 24hrs change. Is it possible to meaure the change or price on 24hrs on Pinescript on any timefram? If now, Can it be like past 100 bars then calculate the data of change? It's my first question here and thank you very much for the future respondents! I would like to know If it's possible to have the 24hrs change in Pine -
Jenkins Email SMTP server errors
So having some issues in Jenkins while setting up E-Mail notification. Using these settings which work fine in code on my websites and azure pipelines smtp: tulip.specialservers.com port: 25 EnableSsl: false user: xxxxxx@xxxxx.com password: xxxxxxx As I say these cred's work elsewhere, howverever on Jenkins I have tried smtp: tulip.specialservers.com port: 25 EnableSsl: false user: xxxxxx@xxxxx.com password: xxxxxxx jakarta.mail.AuthenticationFailedException: 535 Invalid Username or Password ?? smtp: tulip.specialservers.com port: 465 EnableSsl: false user: xxxxxx@xxxxx.com password: xxxxxxx jakarta.mail.MessagingException: Got bad greeting from SMTP host: tulip.specialservers.com, port: 465, response: [EOF] ??? smtp: tulip.specialservers.com port: 25 EnableSsl: true user: xxxxxx@xxxxx.com password: xxxxxxx javax.net.ssl.SSLException: Unsupported or unrecognized SSL message ??? smtp: tulip.specialservers.com port: 465 EnableSsl: true user: xxxxxx@xxxxx.com password: xxxxxxx jakarta.mail.AuthenticationFailedException: 535 Invalid Username or Password ?? When I last set this up a couple of years ago there was no issue, can anyone provide me with some ideas please. Ta -
In R, how can I create a new column with values 1/0, where the value in the new column is 1 only if values in two other columns are both 1?
I have two columns within a DF, "wet" and "cold", with values of 1 and 0 respectively, e.g: Wet Cold 1 1 0 1 0 1 1 0 1 1 0 0 I would like to create a new column, wet&cold, where only if wet=1 and cold=1, then wet&cold=1. If any or both of them are 0 or not matching, then wet&cold=0. I tried to work around with grepl, but without success. -
No gradients provided for any variable:
I am getting this error in tensorflow while using gradient tape on this function. I have done everything but still not getting the output. `with tf.GradientTape() as tape: critic_value = -agent.critic(state_batch, old_actions) actor_loss = tf.math.reduce_mean(critic_value) actor_grad = tape.gradient(actor_loss, agent.actor.trainable_variables) agent.actor.optimizer.apply_gradients(zip(actor_grad, agent.actor.trainable_variables))` -
How to find the subimage in a large image using python cv2
Main image with sub-image I have a image with sub-images inside how to find the sub-images in a main image without template method and using python code or is there any software to find the sub-image. import cv2 # Load the image image = cv2.imread("img_2.jpg") # Define the callback function for the threshold slider def threshold_callback(threshold): # Perform Canny edge detection edges = cv2.Canny(image, threshold, threshold*2) # Display the edges cv2.imshow("Edges", edges) # Create a window to display the original image cv2.namedWindow("Original", cv2.WINDOW_NORMAL) cv2.imshow("Original", image) # Create a trackbar for adjusting the threshold cv2.createTrackbar("Threshold", "Original", 0, 255, threshold_callback) # Wait for the user to press a key cv2.waitKey(0) # Close all windows cv2.destroyAllWindows() i try this but it not working. -
How to make a timer reset
I just started teaching myself front end coding and was wondering how to make a timer that when ends makes a button go to a random position across the screen. Here's the code I wrote(stole). Here's the code I wrote(stole) but the timer doesn't restart when it ends. I need it to move the button after resetting the timer. var h3 = document.getElementsByTagName("h3"); h3[0].innerHTML = "Countdown Timer With JS"; var sec = 5, countDiv = document.getElementById("timer"), secpass, countDown = setInterval(function () { "use strict"; secpass(); }, 1000); function secpass() { "use strict"; var min = Math.floor(sec / 60), remSec = sec % 60; if (remSec < 10) { remSec = "0" + remSec; } if (min < 10) { min = "0" + min; } countDiv.innerHTML = min + ":" + remSec; if (sec > 0) { sec = sec - 1; } else { clearInterval(countDown); var b = document.getElementById("thing"); var i = Math.floor(Math.random() * 800) + 1; var j = Math.floor(Math.random() * 600) + 1; b.style.left = i + "px"; b.style.top = j + "px"; } }; -
How do I clear the view cache for a single file in express.js?
when i render my homepage like this: router.get('/', function(req, res, next) { res.render('../_cache/homepage-1.hbs', { title: 'Home', style: 'home-new', projectSlug: 'homepage', }); }); it seems to cache the way homepage-1.hbs was when the first started. if i then edit the file, it will still show the old one until i reboot the server. but only in production, it does not happen in development. How can i clear this cache? -
Getting <__main__.Email object at 0x000001C114A1BF10> error when trying to print emails [duplicate]
I am trying to simulate email message whereby the user can select either send, read, mark as spam or quit. When I run the code, I can send an email and quit however, when I select read or mark as spam, I am picking up the following email object errors: What would you like to do - read/mark spam/send/quit?read List of emails <main.Email object at 0x00000230D6036F10> <main.Email object at 0x00000230D64325D0> <main.Email object at 0x00000230D6432510> <main.Email object at 0x00000230D6432650> Enter number of email you want to read: 3 <main.Email object at 0x00000230D6432510> What would you like to do - read/mark spam/send/quit?mark spam List of emails <main.Email object at 0x00000230D6036F10> <main.Email object at 0x00000230D64325D0> <main.Email object at 0x00000230D6432510> <main.Email object at 0x00000230D6432650> This is my code: # Defining class for Email as per instructions on task class Email: # Creating functions for Email classs def __init__(self, email_contents, from_address): self.from_address = from_address self.is_spam = False self.has_been_read = False self.email_contents = email_contents def mark_as_read(self): self.has_been_read = True def mark_as_spam(self): self.is_spam = True # Creating list for emails inbox = [] # Creating method 'add_email' def add_email(contents, email_address): email = Email(contents, email_address) inbox.append(email) # Creating method 'get_count' def get_count(): return len(inbox) # Creating method 'get_email' … -
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