Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to relate models effectively using Django Rest Framework
I am trying to create an application to keep the accounts of a store. Each time an invoice is uploaded to the system it must create the products in another table called "products" but if the product already exists, only the price and quantity must be updated. Each invoice can have several products How should I propose the relationship between the tables?. One to many, one to one, many to many? Is there any way to represent the relationship in a way that creates a list of products on each invoice?. A supplier can bring more than one product. Is there a way in which you can create the records in the product table without creating duplicates?. It is not necessary to have the same product more than once if the price and quantity in the inventory were updated when entering a new invoice. For example, the invoice to be entered has the following information: Number List item Provider Products: (list) Product a Product b Product c Total Date If product A exists, the invoice must update the price and quantity in the inventory. If product C does not exist, the invoice must create the product. Until now, this is … -
DJANGO , how to convert django app in exe
I try to convert django app with pyinstaller but the app.exe wont start. Have some idea or some guide tutorial for do that. Thanks -
What's the equivalent of Django extends base.html in .net c#?
In Django I can do something like this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Favorite Books</title> </head> <body> {% block content %} {% endblock content %} </body> </html> And in the other html file I can have {% extends __base.html %} {%block content%} Some html here {% endblock content%} I'm learning c#.net now. What's the equivalent of that in this framework? -
Reload Database Objects without reloading entire Page
I have a django project with two main templates. One will post stuff to a database and the other one will display the stuff in the database. Is there any way that the display template could reload the database objects without reloading the entire page? -
DRF how to make a PATCH request with file upload
So there are lots of questions about PATH in DRF (Django Rest Framework) but no one actually talks about how to actually send the request. I have a PATCH method that I want to use to modify an object and add another image. How do I do that? Here's what it looks like: def get_object(self, pk): return Attendance.objects.get(pk=pk) def patch(self, request, pk): testmodel_object = self.get_object(pk) file_serializer = AttendanceSerializer(testmodel_object, data=request.data, partial=True) # set partial=True to update a data partially if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # I got this code from another question on here and made a few changes of my own. # Please let me know if I'm doing something wrong As you can see, the way we choose the object we want to modify is by giving it's primary key BUT where do put this primary key? Is there a special param? Do we need to make a param or is there an other way? I am using the python requests library and I normally do the following when I need to create a new object (NOTE that my post method is pre-configured for image upload with multiparse and stuff.) like this response = … -
I am trying to create django rank model field which depends on score
class Sport(models.Model): score = models.PositiveIntegerField() rank = models.PositiveIntegerField() If the score is high rank is 1 and if the score is low rank is also low.not able to write a model for this can anyone help me with this -
how to pass django variable inside quotes?
I would like to change the photo on the sliders and for this I created the SliderImage model, in index.html I want to pull out the pictures using a loop, but it uses an unfamiliar tag for me and tried to pass the variable in quotes inside STATIC, but to no avail, I get this /static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D" style="background-image: url("/static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D");"> index.html {% for slider in slider %} <div class="hs-item set-bg" data-setbg="{% static '{{ slider.get_absolute_image_url }}' %}"> <div class="container"> <div class="row"> <div class="col-xl-6 col-lg-7 text-white"> <span>New Arrivals</span> <h2>denim jackets</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quis ipsum sus-pendisse ultrices gravida. Risus commodo viverra maecenas accumsan lacus vel facilisis. </p> <a href="#" class="site-btn sb-line">DISCOVER</a> <a href="#" class="site-btn sb-white">ADD TO CART</a> </div> </div> <div class="offer-card text-white"> <span>from</span> <h2>$29</h2> <p>SHOP NOW</p> </div> </div> </div> {% endfor %} models.py from django.conf import settings from django.db import models class SliderImage(models.Model): img = models.ImageField(upload_to='media/slider_photo/', verbose_name='Photo') @property def get_absolute_image_url(self): return "{0}{1}".format(settings.MEDIA_URL, self.img.url) def __str__(self): return "{}".format(self.img) views.py def index(request): slider = SliderImage.objects.all() return render(request, 'main/index.html', {'slider': slider}) -
Uploading images without ModelForm
I am creating a page for adding products to the web shop by the user, and I am having troubles with uploading images. I have a form with an <input type="file"> and after selecting the files, the files (images) should be temporarily uploaded to the server. After the upload is complete, image preview should be displayed. During the upload, loading spinner GIF with client-side progress indication should be displayed too, along with the option to cancel the upload. Each uploaded image should have an option to be deleted, once uploaded. Because of all this and other reasons, I'm not using a ModelForm, but creating everything manually. So, my plan is to attach an onchange listener to that input, and upon files selection, a POST XMLHttpRequest would be sent from JavaScript, which would call a view that would save the images into some kind of table for temporarily uploaded images, and the ID of the row would be something like request.session.session_key, but a little bit different. My issue with this approach is generating that session key, which should be unique and it should last as long as the page is opened. So, refreshing the page would mean generating a new key. … -
Getting data from a POST request
POST data not always making to my logic, despite updating the django model properly def new_record(request): form = RecordForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect('/new_record') else: form = RecordForm() item1 = request.POST.getlist('checkbox_1') item2 = request.POST.getlist('checkbox_2') item3 = request.POST.getlist('checkbox_3') print(item1) print(item2) print(item3) if 'on' in item1: print("Checkbox 1 is true") write_pdf_view(textobject='textobject', exam_record_number='123') else: print("Checkbox 1 is False") if 'on' in item2: print("Checkbox 2 is true") else: print("Checkbox 2 is False") if 'on' in item3: print("Checkbox 3 is true") else: print("Checkbox 3 is False") return render(request=request, template_name='main/new_record.html', context={"form": form} ) What I'm hoping to do is basically check if a checkbox is selected and pass a value into a function if this is true, for now I've fixed y write_pdf_view values to something I know exists and that's not working either (I imported that above) I feel like this might be trivial for someone with experience, I'm a new hobbyist just looking to learn! Any help much appreciated. -
How to effectively sort or filter objects on a site page?
I have an online store website written in django. I want to add sorting (and filters) to the product page by various parameters. How to do it effectively? 1) Store several databases already sorted (by date, by popularity, etc.). 2) Sort when prompted from the database. -
What is a good User content management system for both Backend & Frontend?
For a school project, we are doing a website (React & Django Rest Framework) where any user can upload content (audio / picture) inside Albums that they created in first place. Currently, we use DigitalOcean Spaces as Django Storage Backend as our provider. Which works well, but when we load the images on the Front (React), it's SUPER SLOW which is why I'm adressing you this message right now. So, my question is, what would be the strategy, on the backend first (provider, endpoints, urls, ...) and then on the frontend (request placeholder after having the first URL returned by our backend ? ). The ideal goal is to have the same experience than Pinterest but with Medium-like loading state (small image, expanded and blurred while loading the full res one) ? Thanks in advance ! -
Running integration tests separately from unit tests in django
The convention for creating tests in django is to place tests in modules named tests_*.py and to run then as python manage.py test. This will run all tests defined tests in all modules named tests. The challenge I have come across is that integration tests may require significant setup of resources e.g. connection to external services. I would imagine mocking out those services in integration tests would cause integration tests to loose their meaning. I am inquiring therefore of the best practice in running only unit tests and only run integration tests when unit tests are running properly. The only way I can imagine is to place integration tests in files named with a different pattern such as integration_*.py and then use the pattern parameter when running integration tests as specified by the django documentation Like this python manage.py test --pattern="integration_*". In this way when python manage.py test is called integration tests will be ignored. Does anyone have a suggestion or recommendation. -
How can I make a view for a section of Index.html separately?
So, I have a website where the user clicks "my blog" on the navbar, which scrolls down to that section of the index.html (ex. 8000/#blog-section). I already have the Contact form working on the index page. Now I am trying to create the blog logic to render out three blog posts, but it is showing up blank? Can I create a separate view for the same "index.html" page? Views.py def index_view(request): posts = Post.objects.all().order_by('-created_on') context ={ 'posts': posts, 'name': name, } form = ContactForm if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): # Send email goes here name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('message') template = get_template('contact_form.txt') context = { 'subject': subject, 'email' : email, 'message' : message } content = template.render(context) email = EmailMessage( "Message from Portfolio", content, "New inquiry | Portfolio" + '', ['myemail@gmail.com'], headers = {'Reply to': email} ) email.send() return HttpResponseRedirect("/") return render(request, 'index.html', {'form': form}, context) Urls.py /blog from django.urls import path from . import views urlpatterns = [ path("", views.blog_index, name="blog_index"), path("<int:pk>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ] Urls.py /portfolio from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from … -
What can cause MultiValueDictKeyError in Django?
i almost finished my register form, but something went wrong and i totally don't know what. It is a little difficult to describe but i will try. So, as you can see here is login form: login.html <h1>login page</h1> <table> <tr><a href="register.html">return to register page</a><br> </tr> <tr><a href="index.html">return to home page</a> </tr> </table> <br> <div> <form method="post"> {% csrf_token %} <div> <div><label>Login/Email </label><input type="text" name="login_name" placeholder="Login/Email"></div> <div><label>Password </label><input type="password" name="login_password" placeholder="enter password"></div> <div><input type="submit" value="Login"></div> </div> </form> </div> and here is register form: register.html <h1>Register page</h1> <table> <tr><a href="login.html">return to login page</a> <br></tr> <tr><a href="index.html">return to home page</a> </tr> </table> <br> <div> <form method="POST"> {% csrf_token %} <div> <div><label>Name </label><input type="text" name="registerFrom_name" placeholder="Enter the name"></div> <div><label>Surname </label><input type="text" name="registerFrom_surname" placeholder="Enter the surname"></div> <div><label>Login/Email </label><input type="text" name="registerFrom_login" placeholder="Login/Email"></div> <div><label>Password </label><input type="registerForm_password" name="registerFrom_password" placeholder="Enter password"></div> <div><label>Email </label><input type="text" name="registerForm_email"></div> <div><input type="submit" value="Register"> </div> </div> </form> </div> Bellow my own backend to handle froms: view.html # BACKEND from django.shortcuts import render from django.views import View from . import ValidateUser, RegisterUser # Create your views here. CSRF_COOKIE_SECURE = True class WebServiceView(View): # INDEX - MAIN PAGE def indexPage(self, request): return render(request, "index.html") def register(self, request): res = RegisterUser.RegisterUser("user", "user", "login", "test", "emai@email") res.createUser() return … -
Heroku error code H10, not sure what's going on
I'm still a newbie at all this, so I'm not sure what's going on. Been going through the PCC book by Eric Mathes, which is great, but, I've run into some errors here and there even when following the book to a tee due to perhaps using version 1 of the book and not the newest, version 2. Anyhow, I've been trying for days now to figure this h10 error out and I don't understand what's going on here. When I do 'Heroku open', I get an application error and when I investigate, this is what I get: Thanks in advance! (11_env) Rezas-MacBook-Pro:learning_log papichulo$ heroku logs --tail 2019-10-04T09:29:06.956667+00:00 heroku[web.1]: Process exited with status 3 2019-10-04T09:41:27.299718+00:00 heroku[web.1]: State changed from crashed to starting 2019-10-04T09:41:32.445405+00:00 heroku[web.1]: Starting process with command `gunicorn learning_log.wsgi --log-file -` 2019-10-04T09:41:35.802943+00:00 heroku[web.1]: State changed from starting to up 2019-10-04T09:41:35.155219+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-10-04T09:41:35.157841+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Listening at: http://0.0.0.0:11830 (4) 2019-10-04T09:41:35.158031+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Using worker: sync 2019-10-04T09:41:35.163938+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [10] [INFO] Booting worker with pid: 10 2019-10-04T09:41:35.181361+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [11] [INFO] Booting worker with pid: 11 2019-10-04T09:41:36.545969+00:00 heroku[web.1]: State changed from … -
Access to Postgres DB within container not working from localhost
Below is my docker-compose file. I'm not sure what I'm missing. But I'm not able to connect to the postgres from my localhost dev_db: image: postgres volumes: - ./db_data/postgres:/var/lib/postgresql/data expose: - "5432" ports: - "5433:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5 logging: driver: "json-file" options: max-size: "100m" max-file: "3"``` psql cmd fom loclhost ``` sitharamk$ psql -h localhost -p 5433 -U postgres -W Password: psql: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5433?``` -
How can I call the same methode calling different class inheritence in django?
I think my title might not be very clear but i don't know how to articulate it. I am using Django I have a class "spending" with different inheritance class "vehicules" and "products". I have an other class "project" that has a method callin the "spending" class to kwow what i have been spending on and how much. can i use this same method "vehicule" or "products" to get the same information but just for theese classes? -
Django rest framework ```TypeError: type object argument after ** must be a mapping, not int``` being thrown
I have a SMSMessages model that will contain all the sms sent.I'm trying access via the django-rest-framework ListCreateAPIView class, but I keep on hitting error when I try to do an OPTION request on the api via Insomnia, TypeError at /smsmessages/ type object argument after ** must be a mapping, not int. I searched on SO and found similar errors but they were caused b/c of a filter() argument, which doesn't apply to this. I'm using django 2.2.5, python 3.6.8, django-rest-framework 3.10.3 and a mysqlclient 1.4.4. this is the model of SMSMessages from django.db import models from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token class SMSMessages(models.Model): sms_number_to = models.CharField(max_length=14) sms_content = models.CharField(max_length=160) sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1) sent_date = models.DateTimeField(auto_now=True) delivery_status = models.BooleanField(default=False) class Meta: verbose_name_plural = "SMSMessages" def __str__(self): return self.sending_user and this is this the urls.py file: from django.urls import path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from notification.apiviews import SMSendView, SMSMessagesView app_name = "notification" router = DefaultRouter() urlpatterns = [ path("smsmessages/", SMSMessagesView.as_view(), name="sms_messages"), ] so the way I access it is by sending an OPTION request to http://localhost:8000/smsmessages/. This the SMSMessagesview class that is used for the api view: from rest_framework import generics, status, … -
Uses of for row loop in template
I searched in the docs but could not find tag mentioned below . I want to know where can we use it and Please provide link so i can read more about this tag. {% for row in qs %} {{ row.total_income }} {% endfor %} -
my django code displaying html tags as text
I have been developing an app using python django and beautifulsoup. I want show product data in a html page. but as I return the result with html tags in the html file it's display html tags inside of quotation. here is the image of result that I get I tried many different methods but result are same. I really don't figure out what's the issue maybe my methods are wrong, please help. my codes are below: #myscraper.py def prdTmplt(imgsrc, title, price, link): w = '' w += '<div class="search-img-div">' w += '<img src="'+imgsrc+'">' w += '</div><div class="search-info-div">' w += '<a href="'+link+'"><h3>'+title+'</h3></a>' w += '<span>'+price+'</span>' w += '</div>' return w def scrapeData(query): """ Some unnecessary codes..... """ items = soup.find('ol', {"class":"sku-item-list"}) prdList = [] for item in items.find_all("li", {"class":"sku-item"}): """ scarping data from soup..... """ prdList.append(Scraper.prdTmplt(imgsrc, title, price, link)) allProduct = prdList return HttpResponse(allProduct) #views.py def search(request): context = {} """ my other codes """ context['bb'] = Scraper.scrapeData(search_query) return render(request, 'pages/search.html', context) #views.html <div class="row mt-4"> {% for prd in bb %} {{prd}} {% endfor %} </div> I am beginner at python so, please help me to solve this. -
Retrieve record from two Django models in single template
I'm trying to retrieve the records from two Django models. The retrieval should be like all records from first model and then records from second models based on the username of first models's username. Models are: class Nodes(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, default=1) node_name = models.CharField(max_length=50) node_mob = models.PositiveIntegerField() node_image = models.ImageField(upload_to='nodes_pics/', blank=True) def __str__(self): return self.user.username class DocchainUser(models.Model): docchainuser = models.OneToOneField(User, on_delete = models.CASCADE) address = models.CharField(max_length=64,unique=True) def __str__(self): return self.address Views are: def universityUsers(request): queryset = Nodes.objects.all() context = { 'user_list': queryset, } return render(request,'universityUsers.html',context) Templates: {% for p in user_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ p.node_name }}</td> <td>{{ p.user.email }}</td> <td>{{ p.node_mob }}</td> <td> ADDRESS FROM DOCCHAINUSER MODEL </td> </tr> {% endfor %} I want to retrieve the address from DocchainUser model based on the username from Nodes model. Example: test username exists in both the models. I am supposed to retrieve the record from both the models for test user. And same for all the other users. How it can be done? I'm stuck here. Thanks in advance! -
Modify django admin form "save and add another" function
In my admin forms I have some default submit actions e.g. "save", "save and continue", "save and add another". I want to modify the last one adding some prepopulated fields, so the form will open with some fields filled according to the previous object. Is there a way to do so? -
Scrapy Item pipelines not enabling
I am trying to set up a Scrapy spider inside Django app, that reads info from a page and posts it in Django's SQLite database using DjangoItems. Right now it seems that scraper itself is working, however, it is not adding anything to database. My guess is that it happens because of scrapy not enabling any item pipelines. Here is the log: 2019-10-05 15:23:07 [scrapy.utils.log] INFO: Scrapy 1.7.3 started (bot: scrapybot) 2019-10-05 15:23:07 [scrapy.utils.log] INFO: Versions: lxml 4.4.1.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.7.0, Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)], pyOpenSSL 19.0.0 (OpenSSL 1.1.1c 28 May 2019), cryptography 2.7, Platform Windows-10-10.0.18362-SP0 2019-10-05 15:23:07 [scrapy.crawler] INFO: Overridden settings: {} 2019-10-05 15:23:07 [scrapy.extensions.telnet] INFO: Telnet Password: 6e614667b3cf5a1a 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled item pipelines: [] 2019-10-05 15:23:07 [scrapy.core.engine] INFO: Spider opened 2019-10-05 15:23:07 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2019-10-05 15:23:08 [scrapy.extensions.telnet] INFO: Telnet console … -
How to have a listbox with 'add' and 'remove' buttons as a field in Django admin panel
It is rather easy to store a list of strings (csv for example) in Django models using fields such models.TextField or models.CharField; but is there any module or method that can render that list as a listbox in Django admin panel (probably with add and remove button besides the listbox)? -
Vue Warn: property "search" is not defined on instance
i'm creating a web app with a Django server with api from rest_framework and Vue as frontend (Nuxtjs in particular). Trying to create a "search filter bar" i've got this error and i don't know why: ERROR [Vue warn]: Property or method "search" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. This is my file.vue <template> <div> <v-text-field v-model="search" label="search conditions" outlined dense></v-text-field> </div> <div> <v-list v-for="condition in filteredConditions" :key="condition.id" > <v-list-item> <condition-card :onDelete="deleteCondition" :condition="condition"></condition-card> </v-list-item> </v-list> </div> </div> </template> <script> import ConditionCard from "~/components/ConditionCard.vue"; export default { head() { return { title: "Conditions list", search: "" }; }, components: { ConditionCard }, async asyncData({ $axios, params }) { try { let query = await $axios.$get(`/conditions/`); if (query.count > 0){ return { conditions: query.results } } return { conditions: [] }; } catch (e) { return { conditions: [] }; } }, data() { return { conditions: [] }; }, ... ... computed: { filteredConditions: function(){ return this.conditions.filter((condition) => { return condition.name.toLowerCase().match(this.search.toLocaleLowerCase()) }); } } }; </script> <style scoped> </style> The api is: {"count":15, "next":null, "previous":null, …