Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rest Framework `to_representation()` must be implemented
This issue has similar headings to other threads on this forum, but I'm sure this is not a duplicate because I didn't overwrite my pagination details or anything (which turned out to be the cause in other questions). Anyways, Django raised to_representation() must be implemented. I'm completely stuck as there are no relevant documentation regarding this (please comment if you have some) and my case didn't fit in with other people's. Code: settings INSTALLED_APPS = ['rest_framework',] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_SERIALIZER_CLASS': 'todo.pagination.CustomPaginationSerializer', 'PAGE_SIZE': 10 } view from rest_framework import viewsets from .models import Todo from .serializers import TodoSerializer class TodoViewSet(viewsets.ModelViewSet): queryset = Todo.objects.all() serializer_class = TodoSerializer serializers from .models import Todo from rest_framework import serializers class TodoSerializer(serializers.BaseSerializer): class Meta: model = Todo fields = ['title', 'desc', 'level', 'created'] urls from django.urls import path, include from rest_framework import routers router = routers.DefaultRouter() router.register(r'todos', views.TodoViewSet) urlpatterns = [ path('api/', include(router.urls)), ] Many thanks in advance. Note: in case you're wondering is this all, this IS all as I jus started to learn drf a few moments ago. -
Code splitting React app cdn architecture
So, I'm running a django server and serving the frontend of my application (React SPA) through Cloudfront using an S3 bucket to store the react bundle. I want to split my code using React.lazy and Suspense. In development I am running 2 separate applications (1 django server, 1 react app), and as the browser uses the django server location, when react wants to fetch a bundle uses the baseUrl of the server (window.origin) and never gets to fetch the bundle that I'm lazy loading. Is there a way to fix this? And if in development I'm having this issue, I will have it as well in production, given that my bundles live in Cloudfront URLs, and not in the same baseurl where the server is going to be running. I'll explain here a little bit of my architecture: Django server in port 8000. When a user looks for the route localhost:8000/new it's going to return an HTML file with the bundle URL linked on a script tag. In development that will point to localhost:8081/bundle.js (port where react app is running) and in production to the URL from cloudfront where the production bundle lives. React application in port 8081. A user … -
index page redirecting to default django page after deployment
project url: path('',include("mainpage.urls")), mainpage url: path('', views.index, name= "index"), This works fine on local server and http://127.0.0.1:8000/ opens the mainpage, but when deployed 00.000.000.000/ just opens the default django page with the rocket picture that indicated url configuration is not done, meanwhile all other pages are available. -
'float' object has no attribute 'set' in Django
am new to django & python. Im trying to build a site where users can leave bids on items. The amount they leave bidded is registered as floats. When trying to save the bid, i get the error 'float' object has no attribute 'set'. Why is that? Im not sure how to fix it. models.py, Bid has a manytomany field. class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=True, upload_to='media', default="noimage.jpg") content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) categories = models.CharField(blank=False, max_length=25, choices=category, default="Others") seller = models.ForeignKey(User, on_delete=models.CASCADE) ## min_bid = models.FloatField(blank=False, validators=[MinValueValidator(0)]) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(300, 150)], format='JPEG', options={'quality':100}) image_thumbnail1 = ImageSpecField(source='image', processors=[ResizeToFill(1200, 500)], format='JPEG', options={'quality':100}) def get_absolute_url(self): return reverse('listing-detail', kwargs={'pk': self.pk}) class Bid(models.Model): bid = models.FloatField(validators=[MinValueValidator(0)]) bidder = models.ManyToManyField(User, default=None) listed_item = models.ForeignKey(Listing, on_delete=models.CASCADE, default=None) def get_absolute_url(self): return reverse('listing-detail', kwargs={'pk': self.pk}) views.py: method_decorator(login_required, name='post') class ListingDetailView(DetailView): model = Listing def post(self, request, pk): user = request.user bidder = User.objects.filter(username=user) #gets the amount from form new_bid = float(request.POST["user_bid"]) item = Listing.objects.get(pk=pk) try: bid = Bid.objects.get(listed_item=item) highest_bid = bid.bid except Bid.DoesNotExist: bid = None highest_bid = item.min_bid if new_bid < highest_bid: messages.add_message(request, messages.WARNING, "Bid is too low.") else: #error highlights this try: line try: bid = Bid.objects.get(listed_item=item, bidder=user) bid.bid … -
How to write generic views inside views.py for nested serializers
Here's models.py Class Customer(models.Model): ... Class Project(models.Model): ... customer = models.ForeignKey('Customer', on_delete=models.CASCADE) Class MonitoringDevice(models.Model): ... project = models.ForeignKey('Project', on_delete=models.CASCADE) Class Inverter(models.Model): ... project = models.ForeignKey("Project", on_delete=models.CASCADE) Here's the serializers.py class ProjectListSerializer(serializers.ModelSerializer): customer = CustomerSerializer(many=True) monitoring_device = MonitoringDeviceSerializer() inverter = InverterSerializer() class Meta: model = Project and my views.py class ProjectList(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer The view is acting as if it is a non-nested serializer. How to display the whole contents of the serializer? If I do print(repr(ProjectList())) , It is displaying exactly the format I want. I am new to this platform, please comment if I can improve the question. -
Django psycopg2.InterfaceError: connection already closed
The unit tests started to crash with django.db.utils.InterfaceError: connection already closed. After I switched to Postgres. I found a few solves in at https://www.djangoproject.com/ page but it did not help. . Python 3.6 Django 3.0.7 Postgres 10.12 Test case : class TestLogin(TestCase): def setUp(self): self.client = RequestsClient() self.url = HOST + '/api/token/' self.headers = {} self.user = User.objects.create_user(**random_user) def test_login_correct(self): try: r = self.client.post(self.url, data={ 'email': random_user['email'], 'password': random_user['password'] }).json() except JSONDecodeError: self.fail("/api/token endpoint for POST request not implemented correctly") self.assertTrue('access' in r) self.assertTrue('refresh' in r) Trace : Traceback (most recent call last): File "E:\Work\FarmerRest\venv\lib\site-packages\django\db\backends\base\base.py", line 238, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "E:\Work\FarmerRest\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "E:\Work\FarmerRest\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 231, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\Work\FarmerRest\accounts\tests\tests.py", line 141, in setUp self.user = User.objects.create_user(**random_user) File "E:\Work\FarmerRest\accounts\models.py", line 33, in create_user **extra_fields) File "E:\Work\FarmerRest\accounts\models.py", line 28, in _create_user user.save(using=self._db) File "E:\Work\FarmerRest\venv\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save super().save(*args, **kwargs) File "E:\Work\FarmerRest\venv\lib\site-packages\django\db\models\base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "E:\Work\FarmerRest\venv\lib\site-packages\django\db\models\base.py", line 784, in save_base force_update, using, update_fields, File "E:\Work\FarmerRest\venv\lib\site-packages\django\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) … -
Django csrf token does not work in mobile
Hi I am using Django to build a webapp. I am using Vue JS as the frontend. From Django documentation I got know how to get the csrf token in JS which was written something like this. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); So I used it in my JS file : Vue.component("login-form", { data() { return { username: "", password: "", csrftoken : csrftoken }; }, methods: { validate: function () { var usernameError = document.getElementById("usernameErrors"); var username = document.getElementById('id_username').value; var password = document.getElementById('id_password').value; axios('/accounts/validate_credentials_ajax/', { params: { username: username, password: password } }) .then(function (res) { if (!res.data) { usernameError.innerHTML = "Please enter a correct username and password. Note that both fields may be case-sensitive."; } else { usernameError.innerHTML = ""; document.getElementById("loginForm").submit(); } }); }, toggleShow: function () { var passwordField = document.getElementById("id_password"); if (passwordField.type … -
How to fix Missing CSRF token in sentry
After fighting with sentry when installing it on openshift i got it up and running only to discover that when sending an event to my server it will throw this error: 12:30:59 [WARNING] django.request: Forbidden (CSRF cookie not set.): /api/1/envelope/ (status_code=403 request=<WSGIRequest: POST u'/api/1/envelope/'>) 10.125.2.1 - - [20/Jul/2020:12:30:59 +0000] "POST /api/1/envelope/ HTTP/1.1" 403 6059 "-" "sentry.native/0.3.4" If I send a curl request to the API i get a neat HTML webpage that shows the csrf error. Anyone got an idea what might be the problem here? -
REST Framework Retrieved Wrong Data
I was just getting started on using Django's rest framework. The problem I faced is that Rest Framework didn't fetch from the right URL: I want it to get the list of Todos but it returned the URL where the API was located. (Might be easy for many of you, but I am completely fresh to drf) serializers from .models import Todo from rest_framework import serializers class TodoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Todo fields = ['title', 'desc', 'level', 'created'] urls from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'todos', views.TodoViewSet) urlpatterns = [ path('', views.IndexView.as_view(), name='todo_all'), path('api/', include(router.urls)), ] views from django.views.generic.base import TemplateView from rest_framework import viewsets from .models import Todo from .serializers import TodoSerializer class IndexView(TemplateView): template_name = "todo/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['todos'] = Todo.objects.all() return context class TodoViewSet(viewsets.ModelViewSet): queryset = Todo.objects.all() serializer_class = TodoSerializer What I want Rest to get: What Rest actually displayed: Like, I want the data of the todos, not the URL. Thanks in advance. -
Django Models - Link types specific to a business, only one link type per business?
How can I modify the following models, such that each business is allowed only one social media link of each type: class Business(models.Model): business = models.CharField(max_length=60) class SocialLinkType(models.Model): FB = 'FB' TWTR = 'TWTR' PIN = 'PIN' INST = 'INST' MEMBERSHIP_CHOICES = ( (FB, 'Facebook'), (TWTR, 'Twitter'), (PIN, 'Pinterest'), (INST, 'Instagram'), ) business = models.ManyToManyField(Business) class SocialLink(models.Model): link_url = models.TextField() link_type = models.ForeignKey(SocialLinkType, on_delete=models.CASCADE) business = models.ForeignKey(Business, on_delete=models.CASCADE) -
DRF perform_create set m2m field depend on FK
I got models: USER class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Product Product can be in dif companies. company = models.ManyToManyField(Company, blank=True) My case is , When I create product I want to set M2M field depend on my user.company (FK) def perform_create(self, serializer): company = self.request.user.company serializer.save(company=company) Got error now: TypeError 'Company' object is not iterable -
How to Dislay Relation value in Django?
I am working with the Django admin Panel, and I am doing setup for product variations for an eCommerce website, I created multiple tables in my database for variations, which is related to each other. Now I want to display size and flavour in the admin panel, suppose there are 3 types of size small, medium and large then it should be shown in Size dropdown in my Django admin panel, and the same process for flavours, but right now all sizes and `flavours and coming in the single dropdown, please check my code and let me know how I can solve this issue. Here are my models.py file class Variants(models.Model): name=models.CharField(max_length=285, default=None) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is variationoption code, it will store variation table id class VariantOptions(models.Model): variant=models.ForeignKey('Variants', related_name='var_option', on_delete=models.CASCADE, null=True, blank=True) name=models.CharField(max_length=285) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name and here are my skuoption table code class SkuOption(models.Model): product = models.ForeignKey('Product', null=True, blank=True, on_delete=models.CASCADE) variantoption=models.ForeignKey('VariantOptions', related_name='sku_option', on_delete=models.CASCADE, null=True, blank=True) sku=models.CharField(max_length=285, null=True, blank=True) price=models.CharField(max_length=285, null=True, blank=True) qty=models.CharField(max_length=285, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.sku Here is my admin.py file code, where I am registering models for the relationship class SkuOptionAdmin(admin.TabularInline): fieldsets = [(None, {'fields':['sku','price','qty','variantoption']})] model … -
How to conditionally include different serializer in django rest framework view
So i'm new to django rest framework and currently i have built a registration view for 1 specific serializer which is RegistrationSerializer. Then i wanna make my view to be able to handle another serializer for staff which has different field so i overidde using def get_serializer_class(self) to determine which serializer_class value to use the code is like this: class RegistrationView(CreateAPIView): permission_classes = (AllowAny,) def get_serializer_class(self): if self.request.user.is_authenticated or self.request.user.is_staff: return TutorRegistrationSerializer return RegistrationSerializer def post(self, request,format=None): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() status_code = status.HTTP_201_CREATED password = request.data.get('password') if password is not None: user = authenticate(email =serializer.data['email'],password=password) if user is not None: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) response = { 'success' : True, # 'status_code' : status_code, # 'message': 'User registered successfully', 'username': user.id, 'token':jwt_token, } return Response(response, status=status_code) but with my current code the returned serializer_class doesn't seem to be included in post method Help :(( -
Django AbstractUser password is not hashing
I've used as a model AbstractUser extended by custom fields, created form automatically by ModelForm. The problem is that, users except superuser cannot log in to system. I think it's reason, their passwords are not hashing. Where should I make it ? Here are my codes. forms.py: class CustomUserSignUpForm(ModelForm): class Meta: model = CustomUser fields = ['username', 'password', 'user_image', 'role', 'branch', 'license_number', 'fin_number', 'first_name', 'last_name', 'patronymic', 'phone_number', 'email', 'voen_number', 'is_active'] views.py: def sign_up(request): if request.method == 'POST': form = CustomUserSignUpForm(request.POST) if form.is_valid(): form.save() else: form = CustomUserSignUpForm() context = { 'form': form, } return render(request, 'sign_up.html', context) models.py: class CustomUser(AbstractUser): patronymic = models.CharField(_('Ata adı'), max_length=150, blank=True) role = models.ForeignKey(Role, on_delete=models.CASCADE, blank=True, null=True) user_image = models.FileField(_('Profil şəkli'), upload_to='static/assets/images/user-images', blank=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True) phone_number = models.CharField(_('Telefon'), max_length=20, blank=True) voen_number = models.CharField(_('VÖEN'), max_length=30, blank=True) fin_number = models.CharField(_('FİN'), max_length=20, blank=True) license_number = models.CharField(_('Lisenziya'), max_length=40, blank=True) def __str__(self): return self.username -
How to connect a django app in heroku to mongodb atlas?
how can i connect my django app in heroku to mongodb atlas without installing the mLab add-on ? i have tried to add a config var of my mongo database but it doesn't work maybe because its not a link of mLab and its a django app not nodejs. and mLab did not accept creating accounts anymore. is there any solution for that ? -
Grouping aggregations in Django
For reporting I want to group some counts together but still have access to the row data. I feel like I do this a lot but can't find any of the code today. This is in a B2B video delivery platform. A simplified version of my modelling: Video(name) Company(name) View(video, company, when) I want to show which companies viewed the most videos, but also show which Videos were the most popular. +-----------+-----------+-------+ | Company | Video | Views | +-----------+-----------+-------+ | Company E | Video 1 | 1215 | | | Video 2 | 5 | | | Video 3 | 1 | | Company B | Video 2 | 203 | | | Video 4 | 3 | +-----------+-----------+-------+ I can do that by annotating views (to get the right to a company order, most views first) and then looping companies and performing a View query for each company, but how can I do this in in O(1-3) queries rather than O(n)? -
Django makemigrations takes storage attribute of ImageField into consideration
I've been trying to integrate Azure Storage to store email files/images inside Django project. Thanks to django-storages after one hour I've managed to connect it without any major problems. However, on local setup I would want to use simple django.core.files.storage.FileSystemStorage instead of Azure Storage. Unfortunately changing storage attribute on ImageField inside model definition generates new migration file. Here's the code: from django.conf import settings from django.core.files.storage import get_storage_class from django.utils.functional import LazyObject class DefaultEmailStorage(LazyObject): def _setup(self): self._wrapped = get_storage_class(settings.DEFAULT_EMAIL_FILE_STORAGE)() email_storage = DefaultEmailStorage() # and the simplified model definition class MyModel(models.Model): img = models.ImageField(null=True, blank=True, storage=email_storage) Changing DEFAULT_EMAIL_FILE_STORAGE inside settings.py creates new migration whenever makemigrations runs. Is there any way to avoid generating such a migration? -
Hi i am working with atom minicoda django.when i try creating new project i get following error ,Please help me
I am getting the following error when i try creating a new project in Atom.Before using django-admin startproject ABC command i installed miniconda activated virtual environment installed django and python. Please help. File "C:\Users\DELL\miniconda3\envs\MyEnv\Scripts\django-admin-script.py", line 9, in sys.exit(execute_from_command_line()) File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_lin e utility.execute() File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management_init_.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management_init_.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 985, in _gcd_import File "", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management\commands\startproject.py", line 1, in <module> from django.core.management.templates import TemplateCommand File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management\templates.py", line 14, in <module> from django.core.management.utils import handle_extensions File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\core\management\utils.py", line 7, in <module> from django.utilenter code heres.crypto import get_random_string File "C:\Users\DELL\miniconda3\envs\MyEnv\lib\site-packages\django\utils\crypto.py", line 6, in <module> import secrets ImportError: No module named 'secrets' -
how to render html files and define functions in django's admin.py
I am trying this code of django but i dont know why it is not working here is my code for admin.py admin.site.site_header = 'MyShop Administration' sctgs = sub_categorie.objects.all() for s in sctgs: print(s.id) class ProductsAdmin(admin.ModelAdmin): fieldsets=( (None,{ 'fields':('Product_Name','price','Description', 'ctg') }), ) change_form_template = 'admin/categories.html' def sub_ctg(self,request): sctg = sub_categorie.objects.all() return render(request, 'admin/categories.html',{'sctg':sctg}) admin.site.register(sub_categorie) admin.site.register(categorie) admin.site.register(Products,ProductsAdmin) I wrote this function sub_ctg but in my categories.html but sctg is not coming in categories.html here is my categories.html {% extends 'admin/change_form.html' %} {% block custom_field%} <fieldset class="module aligned "> <div class="form-row field-sub_category"> <div> <label class="required" for="id_sub_category">Sub category:</label> <div class="related-widget-wrapper"> <select name="sub_category" required="" id="id_sub_category"> {% for s in sctg %} <option value="{{s.catagory_name_id}}" >{{s.sub_name}}</option> {% endfor %} </select> <a class="related-widget-wrapper-link change-related" id="change_id_sub_category" data-href-template="/admin/mystore/sub_categorie/__fk__/change/?_to_field=id&amp;_popup=1" title="Change selected sub_categorie" href="/admin/mystore/sub_categorie/1/change/?_to_field=id&amp;_popup=1"><img src="/static/admin/img/icon-changelink.svg" alt="Change"></a><a class="related-widget-wrapper-link add-related" id="add_id_sub_category" href="/admin/mystore/sub_categorie/add/?_to_field=id&amp;_popup=1" title="Add another sub_categorie"><img src="/static/admin/img/icon-addlink.svg" alt="Add"></a> </div> </div> </div> </fieldset> {%endblock%} here these s.catagory_name_id and s.sub_name is not coming -
Post multiple checkbox data of Datatable checkbox on button click on javascript
This is the datatable script that creates the datatable. Checkbox target is 0, so the first column of each row is always a checkbox. That checkbox inherits an {{id}} that was sent via django views. I want to somehow send those ids back via URL to a view, so i can see the student Ids I have seleced in datatable. It would be really great if someone knows how to get this done in Javascript. The Ids are currently printed-> console.log(PostData) when the button is clicked. Help much apprecciated!:) {% block js %} <script type="text/javascript" src="https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script> <script> var PostData; $(document).ready( function () { var table = $('#table_id2').DataTable({ "ajax": "{% url 'table_list_addStudents' %}", "columnDefs": [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], select: { style: 'multi', }, order: [[ 1, 'asc' ]], }); var buttons = new $.fn.dataTable.Buttons(table, { buttons: [ { text: 'Add Students', action: function () { var data = table.rows( { selected: true } ).data().pluck(0).toArray(); if(data.length > 0){ PostData = data console.log(PostData) } } }, ] }).container().appendTo('#buttons') }); </script> {% endblock %} -
Can i make answer options random each refresh
Hi am putting together a personality quiz with with 10 questions each question has 5 answer (openness,conscientiousness,extraversion,agreeableness,neuroticism) everything is working but the only problem am having is i get all of my openness answers as the first option, and all of my conscientiousness answers as the second option and so on . here is my code <form method="POST"> {% for question in questions %} <div class="container"> {% csrf_token %} <h3>{{ question.Question }}</h3> <p> <input type="checkbox" name="poll" value="openness"> {{ question.openness }} </p> <p> <input type="checkbox" name="poll" value="conscientiousness"> {{ question.conscientiousness }} </p> <p> <input type="checkbox" name="poll" value="extraversion"> {{ question.extraversion }} </p> <p> <input type="checkbox" name="poll" value="agreeableness"> {{ question.agreeableness }} </p> <p> <input type="checkbox" name="poll" value="neuroticism"> {{ question.neuroticism }} </p> <hr> </div> {% endfor %} <input type="submit" value="submit"> </form> is there a way to randomize the inputs ? -
Error: matching query does not exist, but object does indeed exist in db
Aight so im new to django. Im trying to build a modest site where users can leave bids on items. When a user leaves a bid for the first time, it is registered succsessfully. When they leave a bid on the same item a second time, i get the error "matching query does not exist" which doesnt make sense to me, because my query seems right & the bid does exist. I can see it in the admin interface models.py: class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=True, upload_to='media', default="noimage.jpg") content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) categories = models.CharField(blank=False, max_length=25, choices=category, default="Others") seller = models.ForeignKey(User, on_delete=models.CASCADE) ## min_bid = models.FloatField(blank=False, validators=[MinValueValidator(0)]) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(300, 150)], format='JPEG', options={'quality':100}) image_thumbnail1 = ImageSpecField(source='image', processors=[ResizeToFill(1200, 500)], format='JPEG', options={'quality':100}) def get_absolute_url(self): return reverse('listing-detail', kwargs={'pk': self.pk}) class Bid(models.Model): bid = models.FloatField(validators=[MinValueValidator(0)]) bidder = models.ManyToManyField(User, default=None) listed_item = models.ForeignKey(Listing, on_delete=models.CASCADE, default=None) def get_absolute_url(self): return reverse('listing-detail', kwargs={'pk': self.pk}) views.py: @method_decorator(login_required, name='post') class ListingDetailView(DetailView): model = Listing def get_context_data(self, **kwargs): def post(self, request, pk): user = request.user new_bid = float(request.POST["user_bid"]) item = Listing.objects.get(pk=pk) try: #if there is a current bid bid = Bid.objects.get(listed_item=item) highest_bid = bid.bid except Bid.DoesNotExist: bid = None highest_bid = 0 #check … -
how to fetch data of login user in django
I am using a custom user model and I have anther Enquiry model. I want that is the login user type is_service_provider I want to fetch data of service provider who had login in the panel. I don't know how to do this. here is my models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254,unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_Customer = models.BooleanField(default=False) is_Service_Provider = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_username(self): return self.username class Enquiry(models.Model): name = models.CharField(max_length=254 , null=False) email = models.EmailField(max_length=254, null=False) phone_no = models.IntegerField(null=False) service_requied = models.ForeignKey('accounts.Category', on_delete=models.CASCADE, null=False) subcategory = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE, null=False) country = models.ForeignKey('accounts.Country', on_delete=models.CASCADE, null=False) state =models.ForeignKey('accounts.State', on_delete=models.CASCADE, null=False) city = models.ForeignKey('accounts.City', on_delete=models.CASCADE, null=False) address = models.CharField(max_length=254, null=False) defects = models.TextField(max_length=254, null=False) service = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=False) def __str__(self): return self.service.username Here is my views.py @login_required def enquiry(request): user = Enquiry.objects.all() data = request.user return render(request, 'service-provider-panel/enquiry.html', {'user' : user, 'data':data}) -
"ProgrammingError at '/blog/'" on Heroku
Finished an app and was about to deploy on Heroku before I realized I could have worked with a Virtual Env earlier. I created Virtualenv anyway and deployed on Heroku. Everything works well except for the blog page. I keep getting: ProgrammingError at '/blog/' relation 'blog_post ' does not exist". Meanwhile it works just fine on the local server. I don't know if this is an Sqlite-Heroku bug or a Django version thing (App is written in the local django 3.0 but 3.0.8 is installed in the virtual env). -
Can I query from Dependent model in Django graphene Dynamically?
I have a model like class Project(models.Model): status = models.CharField(max_length=50) class Goal(models.Model): goal_id = models.CharField(max_length=50, blank=True, null=True, default="default") status = models.CharField(max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) class Issue(models.Model): issue_id = models.CharField(max_length=50, blank=True, null=True, default="default") status = models.CharField(max_length=50) goal = models.ForeignKey( Goal, null=True, blank=True, on_delete=models.CASCADE ) project = models.ForeignKey( Project, null=True, blank=True, on_delete=models.CASCADE ) class Task(BaseEntityBasicAbstract): task_id = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=50) goal = models.ForeignKey( Goal, null=True, blank=True, on_delete=models.CASCADE ) project = models.ForeignKey( Project, null=True, blank=True, on_delete=models.CASCADE ) Can I write a Dynamic Query function where I can filter the status of the dependent model dynamically? Like where I can apply join operation from provided arguments. def DynamicQuery(Module, Model, status, dependentModel, dependentModelID): . . . DynamicQuery(App, Goal, "Open", Project, 1)