Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered
view.py def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) context = {'wallpaper': wallpaper} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) wallpaper model class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) HTML <ul> <li>{{wallpaper.name}}</li> {% for i in wallpaper.tags_set.all %} <li>{{i.tags}}</li> {% endfor %} url.py path('<wallpaper_name>/', views.download, name="download"), Like example the wallpaper I have choosen to download has tags nature and ocean so I want all the wallpapers who have this tag -
How to do an category filter tab logic in django template with js or vue
I am working on categories and brands, one brand can have many categories and I am displaying a button for each category on a Django template and all the brands below but I want that when I press a button category only display the brands that have that category models.py class Filter(models.Model): text = models.CharField(max_length=20) def __str__(self): return self.text class Category(models.Model): filter = models.ForeignKey(Filter, on_delete=models.CASCADE, null=True) icon = models.FileField(upload_to='img', null=True) class Brand(models.Model): logo = models.ImageField(upload_to='img', null=True) url_logo = models.URLField(max_length=200, null=True) filters = models.ManyToManyField(Filter) views.py class HomePageView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'category_list': Category.objects.all(), 'brand_list': Brand.objects.all() }) return context index.html {% for category in category_list %} <a href="#"><i><img src="{{ category.icon.url }}" alt="{{ category.filter }}"></i>{{ category.filter }}</a> {% endfor %} {% for brand in brand_blocks %} <div> <a href="{{ brand.url_logo}}"> <img src="{{ brand.logo.url }}" /> </a> </div> {% endfor %} -
problems serving two django backend apps and two angular frontend app on the same ip address
i have a digitalocean ip address 143.20.20.14 ip set up with two domains members.com and sales.com to server two django app each with angular frontends. for each app i have setup separate files as follows: this is my members.com gunicorn socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target this is my sales.com gunicorn file gunicornsales.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicornsales.sock [Install] WantedBy=sockets.target this is my member.com gunicorn service gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/membersdir ExecStart=/home/webapps/membersdir/members_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ membersbackend.wsgi:application [Install] WantedBy=multi-user. this is my sales.com gunicorn.service file gunicornsales.service [Unit] Description=gunicorn daemon Requires=gunicornsales.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/salesdir ExecStart=/home/webapps/salesdir/sales_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicornsales.sock \ salesbackend.wsgi:application [Install] WantedBy=multi-user. my nginx files are as follows this is my members front end file membersfrontend server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html/membersfrontend; index index.html index.htm index.nginx-debian.html; server_name members.com; location / { add_header Access-Control-Allow-Origin *; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; try_files $uri $uri/ /index.html; } } this is my sales frontend file salesfrontend server { listen 80 … -
Can I use a single search bar for searching different things?
I'm trying to use a single search bar for searching different models. Is it possible to handle it with one view? my views.py file: class SearchResultsView(ListView): model = Food template_name = 'restaurant/food_search_results.html' context_object_name = 'data' def get_queryset(self): query = self.request.GET.get('search') if query is not None: return Food.objects.filter(name__icontains=query) else: return Food.objects.none() my models.py file: class Food(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_path) description = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) meal_category = models.ManyToManyField(MealCategory, related_name="meal") food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat") class Restaurant(models.Model): name = models.CharField(max_length=100) -
Prediction percent
I am searching to find solution. I can't make percent to my prediction. Here is only 0 for no risk and 1 - when pacient has heart disease. How can I upgrade my code and show percentage of risk? I've tried a lot of things, but it doesn't work. Still 0 and 1 predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True And here is my Logistic Regression example: from sklearn.linear_model import LogisticRegression classifier =LogisticRegression() classifier.fit(X_train,Y_train) y_Class_pred=classifier.predict(X_test) from sklearn.metrics import accuracy_score accuracy_score(Y_test,y_Class_pred) from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, y_Class_pred) from sklearn.metrics import classification_report print(classification_report(Y_test, y_Class_pred)) from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test)) fpr, tpr, thresholds = roc_curve(Y_test, classifier.predict_proba(X_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.savefig('Log_ROC') plt.show() Newdataset = pd.read_csv('newdata.csv') ynew=classifier.predict(Newdataset) -
Django code cannot install a pickled sklearn variable
I am building a Django site which contains a segmentation application. A difficulty I am having is importing the segmentation kmeans / hclusters variables which have been stored via joblib. To try to minimize the factors involved, I am building the clusters on the same machine (new M1 Macbook) as the machine I am loading the variables into. I have also utilized the same environment structure (both Python 3.10 environments) and synched the numpy, pandas and scikit-learn environments. I am unable to deduce what is preventing the joblib load in the Django environment. The error occurs when using pickle / pickle5 as well. Error message when attempting import: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 587, in load obj = _unpickle(fobj, filename, mmap_mode) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 506, in _unpickle obj = unpickler.load() File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1213, in load dispatch[key[0]](self) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1538, in load_stack_global self.append(self.find_class(module, name)) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1580, in find_class __import__(module, level=0) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/sklearn/cluster/__init__.py", line 6, in <module> from ._spectral import spectral_clustering, SpectralClustering File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module … -
get data from one column in db django
I have table in my db Users: id name last_name status 1 John Black active 2 Drake Bell disabled 3 Pep Guardiola active 4 Steven Salt active users_data = [] I would like to get all id and all status row from this db and write to empty dict. What kind of querry I should use? filter, get or smth else? And what if I would like to get one column, not two? -
Base "/" not found in Django
My django project ornaments has only one app called balls. I would like the server to point to its index when I do manage.py runserver. I changed urls.py as follows but I get this error: [![enter image description here][1]][1] from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('balls/', include('balls.urls')), path('admin/', admin.site.urls), ] urlpatterns += [ path('', RedirectView.as_view(url='balls/', permanent=True)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)``` I am also including the project structure. Please note that the string `ball` appears nowhere in my code (as per a search).[![enter image description here][2]][2] [1]: https://i.stack.imgur.com/6JL2c.png [2]: https://i.stack.imgur.com/1pjCg.png -
Get name of image when uploading
I am using this code to check the size of an image before uploading on the model. I would like to get the image name so I can communicate to the users what the offending file is. How would I go about this. def validate_image(image): file_size = image.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError("Max size of file is 3MB") image = models.ImageField(default='default.jpg',validators=[validate_image]) -
connect to rabbitMQ cloud using django and flas dockers
I am trying to follow a "Microservices Application with Django, Flask, Mysql" guide on youtube. In this example a Django app uses RabbitMQ (cloud version) to send the message that must be consumed. The following is the consumer.py import pika params = pika.URLParameters('amqps_key') connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='admin') def callback(ch, method, properties, body): print('Recevied in admin') print(body) channel.basic_consume(queue='admin', on_message_callback=callback, auto_ack=True) print('Started cosuming') channel.start_consuming() channel.close() I have an endpoint in the urls.py that calls the producer.py This is the docker-compose: version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db command: ["./wait-for-it.sh","db:3306","--","python","manage.py","runserver","0.0.0.0:8000"] db: image: mysql:5.7.36 restart: always environment: MYSQL_DATABASE: tutorial_ms_admin MYSQL_USER: ms_admin MYSQL_PASSWORD: ms_admin MYSQL_ROOT_PASSWORD: ms_admin volumes: - .dbdata:/var/lib/mysql ports: - 3308:3306 Now: if I start the docker-compose, then open a terminal, go inside the backend service and in the service shell type "python consumer.py", using Postman and enter the endpoint I can see the message being consumed (both in screen and in the rabbit cloud administration panel). If I tried to add the python consumer.py as a command after the "wait-for-it.sh.... " it does not work. Messages are stuck in the Rabbit cloud administration panel, as if nothing consumes them. … -
Ajuda em Django com Python Erro
Boa Tarde. Estou criando uma loja em Django (Estou aprendo ),tenho um erro que nao sei onde ele esta. Preciso de uma Luz.Ja verifique mas nao encontro o erro. O erro e este Agradeço desde ja pela Ajuda. (return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: lojaapp_pedido_order.carro_id). -
What kind of Authentification should I use for Django Rest? [closed]
I am trying to create a calendar mobile application which is being synchronised over multiple different devices using django Rest Api. I obviously have user specific data which is not supposed to be accessed by anybody else then the specific user. What is the best method of authentification for this kind of project? Also, could it be implemented, that the user does not have to sign in each time it opens the application again? -
JavaScript ajax call on page onload and retrieve data from views in Django
I wish to pass localStorage data to Django views and display the return record on page template on page load. I think it can be done with Ajax, but I have no Idea how I can pass specific localStorage variable to Django views on specific pageload and display the record on template as regular templating(not ajax html return) For example: If I load abcd.com/test URL, I want to pass an array of ids or something of a Variable, and return views on template according to passed values. Is there any better way of achieving this ? -
Trying to run task in a separate thread on Heroku, but no new thread seems to open
I have a Django app with a view in the admin that allows a staff user to upload a csv, which then gets passed to a script which builds and updates items in the database from the data. The view runs the script in a new thread and then returns an "Upload started" success message. apps/products/admin.py from threading import Thread # ... from apps.products.scripts import update_products_from_csv @admin.register(Product) class ProductAdmin(admin.ModelAdmin): # normal ModelAdmin stuff def upload_csv(self, request): if request.method == 'POST': csv_file = request.FILES['csv_file'] t = Thread(target=update_products_from_csv.run, args=[csv_file]) t.start() messages.success(request, 'Upload started') return HttpResponseRedirect(reverse('admin:products_product_changelist')) apps/products/scripts/update_products_from_csv.py import csv import threading from time import time # ... def run(upload_file): # print statements just here for debugging print('Update script running', threading.currentThread()) start_time = time() print(start_time) decoded_file = upload_file.read().decode('utf-8').splitlines() csv_data = [d for d in csv.DictReader(decoded_file)] print(len(csv_data)) for i, row in enumerate(csv_data): if i % 500 == 0: print(i, time() - start_time) # code that checks if item needs to be created or updated and logs accordingly print('Finished', time() - start_time) In development this works fine. The "Upload started" message appears almost immediately in the browser, and in the console it prints that it started on Thread-3 or Thread-5 or whatever, and then all the … -
Why keep getting SIGPIPE error after the page reloading several times ! using Django app with nginx for Bitcoin core gateway
I have Django app trying to make bitcoin payment page using local bitcoin core node but I keep getting ([Errno 32] Broken pipe) when the page refresh to check the incoming transactions the error looks like timeout error but I tried several methods to resolve timeout errors using uWsgi and Nginx params but didn't work and didn't got any benfet from logs only from journalctl got SIGPIPE: writing to a closed pipe/socket/fd The debug mode showing this Traceback (most recent call last): File "./wallet/models.py", line 235, in updatedeposit_btc unconf_amount = self.bitcoind.unconf_by_addr(address) File "./wallet/bitcoind.py", line 70, in unconf_by_addr return self.proxy.getreceivedbyaddress(addr, minconf=0) File "/project/env/lib/python3.9/site-packages/bitcoin/rpc.py", line 600, in getreceivedbyaddress r = self._call('getreceivedbyaddress', str(addr), minconf) File "/project/env/lib/python3.9/site-packages/bitcoin/rpc.py", line 231, in _call self.__conn.request('POST', self.__url.path, postdata, headers) File "/usr/lib/python3.9/http/client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1049, in _send_output self.send(chunk) File "/usr/lib/python3.9/http/client.py", line 971, in send self.sock.sendall(data) During handling of the above exception ([Errno 32] Broken pipe), another exception occurred: and I have in bitcoind connection setting .py from django.conf import settings from decimal import Decimal from .rates import rate import bitcoin import bitcoin.rpc from … -
list index out of range error from previous view when rendering a different view
Apologies if I'm missing something daft here but I'm new to Django and I can't work this out. I'm creating a basic reddit style app focusing on cryptocurrency. I have a view which gets price data from an API and displays it as well as any posts specific to that coin: views.py: def coin_posts(request, id): if request.method == 'GET': coin_display = {} post = Post.objects.filter(coin_name=id) api = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=%s&order=market_cap_desc&per_page=100&page=1&sparkline=false' % id response = requests.get(api) data = response.json() coin = data[0] coin_data = Coins( coin_id = coin['id'], coin_name = coin['name'], coin_price = coin['current_price'], market_cap = coin['market_cap'], rank = coin['market_cap_rank'], price_change = coin['price_change_24h'], slug = coin['symbol'], image_url = coin['image'] ) coin_data.save() coin_display = Coins.objects.filter(coin_id=id) return render(request, 'coins.html', { 'post': post, 'coin_display': coin_display, 'post_form': PostForm() }, ) I want to be able to click on each post to view any comments related to said post, as I haven't got that far yet I just wish to be able to view that single post on another page. So each post has the following link on the template: <a href="{% url 'coin_detail' slug=i.slug %}">Comments</a> and here are the corresponding URLs and view: urlpatterns = [ path('', views.index, name="index"), path('<str:id>/', views.coin_posts, name='coin_posts'), path('<slug:slug>/', views.post_detail, name='coin_detail'), ] def … -
Why is a check for an object passing through this if condition and then raising an AttributeError because it doesn't exist?
I've got models that look like this: class Agent(models.Model): pass # there's obviously more to this but for the sake of this question... class Deal(models.Model): agent = models.ForeignKey( Agent, on_delete=models.SET_NULL, null=True, blank=True ) Inside the save method of the Deal, I have some code that updates the metrics of the Agent that looks like this: class Deal(models.Model): agent = models.ForeignKey( Agent, on_delete=models.SET_NULL, null=True, blank=True ) # ... other code ... def save(self, *args, **kwargs): if (self.agent): try: self.agent.closing_success_rate = self.get_agent_closing_success_rate() except Exception as e: print(e) And when there is not an Agent connected to the deal, I get the error: "'NoneType' object has no attribute 'closing_success_rate'" How is the if condition that checks if the Agent exists passing only to later throw an error because it doesn't exist? -
Retrieving Hash (#) url-parameters in Django [duplicate]
I’m working with an Oauth integration and for the first time I’m experiencing that the callback from service uses a # instead of ? in the url params. What I’m used to: test.test/auth?token=123&timestamp=12345 This API: test.test/auth#token=123&timestamp=12345 (note the # between auth and token) So I figured the standard request.GET.get('token’) is not going to work here... well it doesn’t. Does Django have a way of dealing with # params or should write out my own function? Suppose this API is rather intended to be used by JS / Client Side apps, but would be nice to make use of that server side. Thanks! -
how can I separate the result of a query into groups - Django
I try to explain myself, I have the result of the events extracted from the db that have the sports league column. I would like to separate them in the loop so you have something like: League 1 => its events League 2 => its events League 3 => its events evenst list -
Can't pass a variable through my view to the html template
So I'm trying to: pass a variable owner_id in the view def new(request, owner_id) to render new.html that it will be used in the action of a form as a parameter/argument action="{{ url 'new' owner_id }}". Like This: def new(request, owner_id): # from here if request.method == 'POST': ... else: category = Category.objects.all() render(request, "auctions/new.html", { "category": category, "owner_id": owner_id # <--- to HERE }) view.py urls.py new.html Error detected in this file by django Layout.html template Could not parse the remainder ERROR screenshot It's driving me crazy... I can't understand why its not working. And the worst part is I already did it on another view and it WORKED! The only difference is here I use the same variable again inside in the form to "feed" it again, throught the same url, view... etc. Whether there (another url and view) I used it as a normal variable inside the brakets {{ }}. PD: I probably lack the basic understanding how django starts to process all this. -
ERROR: NotFoundError - Elastic Beanstalk can't find a platform version that matches "python-3.9"
I am trying to deploy Django project, but I am finding the below error ERROR: NotFoundError - Elastic Beanstalk can't find a platform version that matches "python-3.9" I am using python version 3.9, any suggestions will be highly appreciated -
problem with displaying ManyToMany Field in Dango templates
I have an app that for shopping list and I want to display values from my ingredients ManyToManyField but what I am getting instead is the name of the recipe that I created. Could you please advice me on how to correctly do it? models.py class Ingredients(models.Model): name=models.CharField(max_length=100, default='-', blank=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'składnik' verbose_name_plural = 'składniki' def __str__(self): return str(self.name) class Category(models.Model): name=models.CharField(max_length=250, default='-', blank=True, unique=True) slug = models.SlugField(unique=True, blank=True) class Meta: ordering = ('name',) verbose_name = 'kategoria' verbose_name_plural = 'kategorie' def get_absolute_url(self): return reverse("kategoria", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default='-') name = models.CharField(max_length=400, blank=False, unique=False) body = models.TextField(blank=True, default='') ingredients = models.ManyToManyField(Ingredients) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) date_created = models.DateTimeField('Utworzono', default=timezone.now) last_updated = models.DateTimeField('Ostatnia zmiana',auto_now=True) when_to_eat = models.DateField('Kalendarz', default=timezone.now) tags = TaggableManager() slug = models.SlugField(unique=True, blank=True) class Meta: ordering = ('name',) verbose_name = 'przepis' verbose_name_plural = 'przepisy' def get_absolute_url(self): return reverse("przepis", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) views.py class RecipeListView(ListView): model = Recipe template_name ='recipe_list.html' queryset = Recipe.objects.all() urls.py urlpatterns = [ path('przepisy/', views.RecipeListView.as_view(), name='recipe_list'), path('przepis/<slug:slug>/', views.RecipeDetailView.as_view(), name='przepis'), ] recipe_list.html <p class="card-text">Składniki:<br> {% for ingredient in object_list %} <li>{{ingredient.name}}</li> {% endfor %} </p> -
Python: Why wont CSS apply to Django?
I am working on a small Python + Django project, but for some reason the CSS wont apply. This is my folder structure: And this is how i implement the CSS, i have also added {% load static} at the top of my HTML file <link rel="stylesheet" href="{% static 'main/styles/base.css' %}"> The website doesn't crash or anything like that, the CSS simply is just not applied. Any ideas? -
Permissions In Django
Hello, Please am Trying to build a app which it has three user types 1. management 2. staff 3. accountant and the management user want to add and give certain permissions to a user of staff or accountant please help Models.py: class CustomUser(AbstractUser): user_type_data = ((1, "management"), (2, "staff"), (3, "finance")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) -
The file 'css/config/static/img/gallery/about-img2.png' could not bnde fou
Quien me puede ayudar con lo siguiente por favor. Esoty teniendo este error al subir mi proyecto Django a Heroku. por lo que entiendo y investigado la ruta esta mal, por lo cual me fui a la ruta donde estan llamando al respectivo archivo y la cambia como se registra en la imagen dos, pero el error sigue, como debo establecer las rutas donde estan esos archivos? en el css tambien tengo que utilizar url({% static 'ruta statica donde esta el archivo'%}) o como seria la estructuración? enter image description here enter image description here