Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sempre que tento dar push no meu projeto em django me da esse erro
enter image description here ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python /app/.heroku/python/lib/pyt hon3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmp23725z14 Check the logs for full command output. -
Relate one table to two tables in Django
I have 'Table1' and `Table2. Both of them of them need to have a one-to-many relationship to 'Table3' ('Table1'/'Table2' one to many 'Table3'). Each row in 'Table3' should have only one relationship field to that can point to 'Table1' or 'Table2' (will be defined in the creation of each row). I thought of implementing this by using a through table that will have 3 relationship column for 'Table1', 'Table2', 'Table3'. Table1: * table1_id Table2: * table2_id Table3: * table3_id ThrougTable: * col1 = ForeignKey(table1_id, null=True) * col2 = ForeignKey(table2_id, null=True) * col3 = OneToOneField(table3_id) What is the best way to make this in Django? -
Having trouble saving an object with a foreign key in Django
This is my first question in the forum. I'm new to Django and making progress slow. The code I'm working on now throws an error when saving with an object as a foreign key reference. My code as below two models class Make(models.Model): name_text = models.CharField(max_length=100) def __str__(self): return self.name_text class Autos(models.Model): nickname = models.CharField(max_length=100) make = models.ForeignKey(Make, on_delete=CASCADE) milage = models.IntegerField(default=0) comments = models.CharField(max_length=1000) HTML form that sends the data to the view <form action="{% url 'auto:addauto' %}" method="post"> {% csrf_token %} <p> <label for="nickname">Nickname : </label> <input type="text" name="nickname" id="nickname" value="{{ autodetails.nickname }}"> </p> <p> <label for="make">Make : </label> <select name="make" id="make"> {% for item in make %} <option value="{{ item.name_text }} ">{{ item }}</option> {% endfor %} </select> </p> <p> <label for="milage">Milage : </label> <input type="text" name="milage" id="milage" value="{{ autodetails.milage }}"> </p> <p> <label for="comments">Comments : </label> <input type="textarea" name="comments" id="comments" value="{{ autodetails.comments }}"> </p> <input type="submit" name = "buttonsubmit" value="Add"> </form> View where the problem exists def addauto(request): if request.method == 'POST': obj = Autos() obj.nickname = request.POST['nickname'] name_text1 = request.POST.get('make') make = Make.objects.get(name_text = name_text1) obj.make = make obj.milage = request.POST['milage'] obj.comments = request.POST['comments'] obj.save() return redirect('/autos/listautos') else: make = Make.objects.all() context = { 'make': … -
Editing the Form in _Django_ creates new instance
I am editing the form , it loads data correctly buy when i hit save it creates new entry in database. Here is the view functions @login_required def post_edit(request, username, post_id): is_edit = True post = get_object_or_404(Post, author__username=username, id=post_id) if post.author == request.user: form = PostForm(request.POST or None, instance=post) if form.is_valid(): post = form.save() return redirect('posts:profile', username, post_id) form = PostForm(instance=post) return render(request, 'posts/post_create.html', {'form': form, 'is_edit': is_edit, 'post': post}) else: return redirect('profile') urls: path('posts/<int:post_id>/edit/', views.post_edit, name='post_edit'), post_create.html: <div class="card-body"> <form method="post" action="{% if is_edit %}{% url 'posts:post_edit' post.author.username post.id %}{% else %}{% url 'posts:post_create' %}{% endif %}"> {% csrf_token %} -
Django DRF BDD - How to properly implement Behave with DRF?
As the title suggests, and since the documented instructions are not working out of the box. I have the following environment.py file, exactly from Behave Documentation and the referenced blog # tests/acceptance/environment.py import os from behave import fixture, use_fixture import django from django.test.runner import DiscoverRunner from django.test.testcases import LiveServerTestCase from rest_framework.test import APIClient from fixtures.users import UserTestHelper os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings.test-settings' # django related fixtures @fixture def django_test_runner(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() yield context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() @fixture def django_test_case(context): context.test_case = LiveServerTestCase context.test_case.setUpClass() yield context.test_case.tearDownClass() del context.test_case def before_all(context): context.test.client = APIClient() use_fixture(django_test_runner, context) def after_all(context): context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() def before_scenario(context, scenario): use_fixture(django_test_case, context) def after_scenario(context, scenario): context.test.tearDownClass() del context.test When executing $ behave on the project root, I get the following django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Even though my first line in environment.py sets the OS environment variable of DJANGO_SETTINGS_MODULE. Then I tried to bypass that error by executing the following: $ DJANGO_SETTINGS_MODULE=core.settings.test-settings behave I get the AppRegistryNotReady: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Question What am I missing to get this to run properly, doesn't seem like behave is picking … -
Why model text is not displayed in html?
The problem is that the text of the model description_text is not displayed. And sorry for my english. This is code of html {% for description_text in context_object_name %} <h1 class="description"><a href="/Homepage/{{ goods.id }}/">{{goods.description_text}}</a></h1> {% endfor %} This is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods.description_text' def description(self): return self.description_text def price(self): return self.price_text def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] And this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) def __str__(self): return self.description_text def __str__(self): return self.price_text -
Using name in dropdown
i want to use the dropdown menu in the request POST query, but I cannot define the name for the dropdown menu options, how can I do this? Is there a chance to do if else according to value with POST in this query? my ex. view; def list(request): if 'Storefront' in request.POST: filtre=Alarmlar.objects.filter( Ekip__contains="Storefront" ) elif 'CAC' in request.POST: filtre=Alarmlar.objects.filter ( Ekip__contains="Cac") else: filtre=Alarmlar.objects.all() members_list=filtre paginator = Paginator(members_list, 100) page = request.GET.get('page') try: members = paginator.page(page) except PageNotAnInteger: members = paginator.page(1) except EmptyPage: members = paginator.page(paginator.num_pages) return render(request, 'list.html', {'members': members}) html; <select class="form-control" id="adsoyad" name="adsoyad" style="text-align:center" required> <option value="" disabled selected >Choose...</option> <option value="all">ALL</option> <option value="Cac">Cac</option> <option value="Storefront">Storefront</option> </select> -
How can i save external kraken API json info in my Django database?
The context I want to save json data from an external public kraken API in my Django database My view.py from rest_framework import generics from .serializers import KrakenSerializer from kraken.models import Kraken import requests class KrakenList(generics.RetrieveAPIView): serializer_class = KrakenSerializer queryset = Kraken.objects.all() def get_object(self): url = 'https://api.kraken.com/0/public/Time' r = requests.get(url, headers={'Content-Type': 'application/json'}) kraken = r.json() return kraken def seed_kraken(): for i in kraken: krakenss = Kraken( unixtime=i["unixtime"], ) krakenss.save() My urls.py from .views import KrakenList from django.urls import path app_name = 'kraken' urlpatterns = [ path('', KrakenList.as_view(), name='listkraken'), ] My serializers.py from rest_framework import serializers from kraken.models import Kraken class KrakenSerializer(serializers.ModelSerializer): class Meta: model = Kraken fields = ('unixtime',) My models.py from django.db import models class Kraken(models.Model): unixtime = models.IntegerField(default=0) This the Django REST framework with wrong empty json answer: This is how the json unixtime answer should look like in my Django REST framework The issue Do you have any suggestion of (i) how can i get the json info working accordingly, and (ii) how can i afterwards save it in my django database? -
I get a 502 Bad Gateway error with django app on AppEngine
I'm deploying a django app on Google app engine (flexible environment). The app works fine locally and the deployment (using gcloud app deploy) goes well. While the homepage loads well, I get a 502 Bad Gateway nginx error when I load some binary data (about 40Mo) using pickle from a directory in the same app directory (through a POST request). I've tried many proposed solutions (change the PORT to 8080, add the gunicorn timeout or add --preload, change n° of workers..), but still have the problem. I think that the problems comes from the fact that I load a heavy file, since I can access the django admin on the deployed version.. I'm not really knowledgeable in gunicorn/nginx (the first time I deploy an app). I'll be very thankful if you have some ideas after so much time spent on this! The log file doesn't show any error: 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Starting gunicorn 19.9.0 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [DEBUG] Arbiter booted 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Using worker: sync 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [10] [INFO] … -
Handle select multiple on django
I have this on template <select name="document" id="document" multiple=""> <option value="2">test 1</option> <option value="3">test 2</option> </select> When I select two options when I accept the request in views.py I got correctly 2 options selected self.request.POST // It prints 'document': ['2', '3'] But when I try to select the field like this self.request.POST['document'] // It prints only '3' How can I select 2 options? Thanks -
How to restrict a Django model to a single one-to-one relation?
I am currently building a Django app that requires two different user types and I know that storing authentication information across multiple models/tables is a bad idea. As such, I have created a User model to handle the authentication information (username, password, etc.). I have then created two different models, one for the buyers and one for the sellers, each with their own unique fields and one-to-one relationship to the User model. Now, I thought this would work, but the problem is that it is still possible for a different buyer and seller to have the same User relation. How can I prevent this and restrict the User model to only a single one-to-one relation? -
Django Pass more complex python types into template
I'm creating a Car Shop web application using Django. Here is my index view: def index(request): cars = Car.objects.filter(brand=request.user.preferred_brand) return TemplateResponse(request, "main/home.html", {"cars": cars}) This shows the list of all cars which currently authenticated user has set a preferrence for. In my database, I also have the following model: class Interest(models.Model): repair_company_name = models.CharField(max_length=200) car_id = models.IntegerField() Each car has a set of companies that are willing to provide repair support for specific car. I would like to show this information on user's home page as well - so that he will not only see the list of his preferred cars, but each car will have information about repair companies next to it too. Here comes my problem - how to pass such a complex type into django template, as I'm not able to do there complex operations like indexing or so. I could imagine creating something like dictionaries containing these information groupped (so that each dictionary would contain everything about car and also the list of strings of names of all repair companies that belong to it). But how to access such a dictionary and its values from template? Is there any better way to do this? -
In django How do I insert ckeditor value inside CKEditorUploadingWidget and display it in templates?
What should I do in order to insert html content inside ckeditor uploading widget? I already have html content in my database field, and I am trying to create UpdateView page and inside ckeditor I want to insert html content. I am using CKEditorUploadingWidget in forms but I don't know how to insert html content django-ckeditor==6.1.0 Django==3.2.6 python 3.9 my code (forms) my html template my template code my UpdateView -
How to optimize Default Django oscars App Views Especially the catalogue App Views?
I am using Django oscar(2.1.1), and I want do to query optimization on Django Oscars default Apps Views specially the catalogue view for class ProductDetailView(DetailView). and class ProductCategoryView(TemplateView). and in App 'Offer' class RangeDetailView(CoreRangeDetailView):. I know that using select_related() and prefetch_related() I can optimize the views but what I am not understanding is which specific function I will have to override in order to optimize these views Especially for the Product Table. I dug into Django Oscars catalog App and found major roles and queries are being done by managers.py so I tried to override it like this but which method do I need to overwrite here any examples? what I tried is overriding this method: def base_queryset(self): """ Applies select_related and prefetch_related for commonly related models to save on queries """ Option = get_model('catalogue', 'Option') product_class_options = Option.objects.filter(productclass=OuterRef('product_class')) product_options = Option.objects.filter(product=OuterRef('pk')) return self.select_related('product_class', 'mtg_card')\ .prefetch_related('attributes','categories','children', 'product_options', 'stockrecords', 'images') \ .annotate(has_product_class_options=Exists(product_class_options), has_product_options=Exists(product_options)) def public(self): """ Excludes non-public products """ return self.filter(is_public=True).select_related('product_class', 'mtg_card')\ .prefetch_related('attributes','categories','children', 'product_options', 'stockrecords', 'images') is that the right way of doing it in a generic manner? and in catalogue/views.py found this class ProductDetailView(CoreProductDetailView): def get(self, request, **kwargs): product = self.get_object() . . def get_object(self, queryset=None): return get_object_or_404(Product.objects.prefetch_related('attributes' , … -
Manipulate strings in Django template
I have following string in my template documents/maca.pdf How can I output only 'maca.pdf' Thanks a lot -
TypeError at /login/user login() takes 1 positional argument but 2 were given
im trying to login using django.contrib.auth it giving me error whenever im trying to login it gives me error below TypeError at /login/user login() takes 1 positional argument but 2 were given this is my login template and url work perfectly from login/user <div class="container border border-2 border-info rounded-2 p-3" style="width: 400px;margin-top: 100px; margin-bottom: 200px;"> <form action="user" method="post"> {% csrf_token %} <h3 class="p-3"> <small class="text-muted">Login To Your Account</small> </h3> <div class="mb-3 form-floating"> <input type="text" class="form-control" id="InputUsername" aria-describedby="emailHelp" name="username" placeholder="Enter Username"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> <label for="InputUsername" >Username</label> </div> <div class="mb-3 form-floating"> <input type="password" class="form-control" id="InputPassword" name="password" placeholder="Enter Password"> <label for="InputPassword" class="form-label">Password</label> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Remember me</label> </div> <button type="submit" class="btn btn-primary">Login</button><a href="/register" class="streched-link p-3">Create Account</a> </form> </div> urls.py look like this from store.settings import MEDIA_ROOT, MEDIA_URL from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name="home"), path('login/',views.login,name="login"), path('register/',views.register,name="register"), path('register/user',views.registeruser,name="registeruser"), path('login/user',views.handlelogin,name="loginuser"), path('/user/logout',views.handlelogout,name="logout") ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py my handle login function def handlelogin(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. return redirect('') else: # Return an 'invalid … -
Django input field
I am making a project in Django which takes an equation having some variables and then perform mathematical function on it using python. Right now, I have CharField as an input field for entering equation but the problem is that it returns string which I can't use for calculation purpose. For eg. The user inputs an equation $x^2 + $y^2. Now I want to substitute value of x and y but the equation is in the form of string and I cannot calculate the value. So, is there any input field in Django which can take equation in a particular form so that I can input value in those variables? -
Iterating over the data received from ajax / json
Below is the type of data I am getting via ajax. [{"model": "blogapp.articles", "pk": 1, "fields": {"title": "Rainbow Buildings in Tokyo", "slug": "Rainbow-Buildings-in-Tokyo"}}, {"model": "blogapp.articles", "pk": 2, "fields": {"title": "4 Cool Cube Facades", "slug": "4-Cool-Cube-Facades"}}] How can I iterate over this data using .each to get the title and the slug for each entry? The below code gives me a syntax error on the data. app.js $(document).ready(function () { $(".tag-nav-links").on("click", function (e) { e.stopPropagation(); return $.ajax({ type: "POST", url: "", dataType: "json", data: { filter: `${e.target.textContent}` }, success: function (data) { var html = ""; $(data).each(function (index, value) { html += "<h4>{{" + value.title + "}}</h4>"; }); $("trial").append(html); }, }); }); }); -
Anti spam in django
Do you have a solution to deal with spam in Python? Should i use a library? I want to use it in "Django". I studied different sources, but I did not reach the desired result. Thanks for help!! -
How to set up optional demo data for a django project
I'm building a django app for making a family tree website, either from scratch or from importing a Gedcom file. In addition to the people/family records that make up the tree, you can add custom html files for stories and family history. First I've been building it out for my own family tree, and next I'm working on improving the setup process, with the goal of making this useful for others. Currently it's public on GitHub: the source code but also the custom files I'm using on my tree. Then my understanding is the 'official' way to make it available when it's ready is to make a package on pypi. I'd like to provide some optional demo files: demo gedcom import for families and people, and demo stories and family history html files. This will give people samples and help them see how it can look once set up. What's the right way to have these demo files available in the code, but optional to include? I've read about github's experimental sparse checkout and setup tools' data files support, but I'm not clear: what's the typical way that people approach this? Is there a standard way to let someone choose … -
Setting dynamic urls for django filter
I have little experience with Django and it's dynamic urls. I used django-filter package to filter items in the database. I'm using Django restframework. In the models.py I have some charfields (owners, item, category...). Using filterset, I want to set a dynamic url. Using the URL path('item**/categories=categoryname**', items-view.as_view(), name='category') I need to specify the category name in the browser search box before I get the items in a named category. That's the way I'm testing it on the browser and by using the category name, I get all the items in that category being returned. I want to use the url in a react application. Will it be a good practice to fetch that API as it is since I'm equating the category to the name of the category to obtain the list of items in that particular category? Or is there a way to set the url dynamically? For instance, when using lookup_field for the product id I can set the url dynamically using path('item/**<int:id>**', items-view.as_view(), name='category') without hard coding the id in the URL. -
Requested setting TEMPLATES, but settings are not configured
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I try to run migrations I got this error. Can someone help me please? -
inpage.js:1 MetaMask no longer injects web3
I am implementing the web3.py with Django and python. But I fail to link with web3.py Here is the error; inpage.js:1 MetaMask no longer injects web3. For details, see: https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3 Uncaught TypeError: Cannot read properties of undefined (reading 'contract') at login.js:192 ncaught ReferenceError: Web3 is not defined at login.js:176 Here is the code:: window.addEventListener('load', () => { if (window.ethereum) { web3 = new Web3(window.ethereum) return true } else if (window.web3) { web3 = window.web3 return true } return false }); -
How to optimize Django oscars Search View?
I am using Django oscar(2.1.1), and I want to optimize Django Oscars default search view i.e class ESProductSearchHandler(CoreESProductSearchHandler). I know that using select_related() and prefetch_related() I can optimize the views but what I am not understanding is which specific function I will have to override in order to optimize the default Django-Oscars search view for Product Table only. I dug into Django Oscars search App and found FacetedSearchView() but which method do I need to overwrite here? I am unable to see any get_queryset() function here then I looked into search_handlers.py in catalog model there i guess I need to override this function def get_search_queryset(self): sqs = super().get_search_queryset() if self.categories: for category in self.categories: sqs = sqs.filter_or(category=category.full_name) return sqs and in facets.py found this def base_sqs(): """ Return the base SearchQuerySet for Haystack searches. """ sqs = SearchQuerySet() for facet in settings.OSCAR_SEARCH_FACETS['fields'].values(): options = facet.get('options', {}) sqs = sqs.facet(facet['field'], **options) for facet in settings.OSCAR_SEARCH_FACETS['queries'].values(): for query in facet['queries']: sqs = sqs.query_facet(facet['field'], query[1]) return sqs what are facets here and how can I make use of it to optimize the search view? Let me know if I am right or not? and if yes how can I optimize it? As you … -
Async functions in Django
I'm trying to use django admin for administrate my Telegram bot. I have an async function called mailing, how can i start this function in django admin actions? I can make it sync but i don't know how make a pause to my bot will be no banned when it send many massages, and continue to answer users. This is my first question on Stackowerflow. Sorry for my english. admins.py @admin.action(description='mailing') def mailing(modeladmin, request, queryset): pass @admin.register(Publish) class PublishAdmin(admin.ModelAdmin): list_display = ('name', 'created_at') actions = [mailing] async def mailing_start(text, url, user_id=None): users = db.select_user_list() count = 0 receivers_count = 0 markup = '' if url: pass #markup = await create_link_button(url) for user in users: try: if user_id != user[0]: if url: await bot.send_message(user[0], text, reply_markup=markup) else: await bot.send_message(user[0], text) count += 1 if count == 18: await asyncio.sleep(3) count = 0 receivers_count += 1 except Exception as err: print(f'id - {user[0]}, bot is stopped \n{err}') receivers_count -= 1 return f'{emoji.emojize(":white_check_mark:", use_aliases=True)}, ' \ f'message recieved {receivers_count}'