Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python / Django / Postgres Get Sample of Database
Looking to utilize either python and psycopg2 or django ORM to get a sample of a postgres database. Seeing pg_dump as a way to get the entire database but I would only want about 10% of the data, centering around a particular table. There are foreign key relations between all objects. What is the best way to do this? -
how to use select2 with dynamic form
I'm trying to add select2 for a dynamic form which is a modelformset_factory, but it doesnt work as i expect, it only works after the first add new row button! and after the third forms it create an extra drop down field! here is what im tried const addNewRow = document.getElementById('add-more-invoice') const totalNewForms = document.getElementById('id_imei-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_imeiforms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-imeilists') const empty_form = document.getElementById('empty-imei-invoiceform').cloneNode(true); empty_form.setAttribute('class','child_imeiforms_row') empty_form.setAttribute('id',`form-${countForms}`) const rgx = new RegExp('__prefix__','g') empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countForms) totalNewForms.setAttribute('value',countForms + 1) formCopyTarget.append(empty_form) $('.choose').select2(); } $('.choose').select2(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> <label>customer name</label> {{ main_form.customer | add_class:'form-control' | append_attr:'onchange:currentBalance();' }} </div> </div> <div class="col-md-2"> <div class="form-group"> <i class="fas fa-box-usd"></i> <label>balance</label> <input type="number" disabled class="form-control" id="balance_cus"> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <i class="far fa-clock"></i> <label>date</label> {{main_form.created | add_class:'form-control text-center'}} </div> </div> </div> {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control choose' | append_attr:'onchange:imeiPlusInfo();'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | add_class:'price'}} </div> </div> <div class="col-md-1"> … -
Field 'id' expected a number but got '{{\r\n choice.id }}'
I am learning from Django documentation but in part 4 of the tutorial I am getting this error: ValueError at /polls/1/vote/ Field 'id' expected a number but got '{{\r\n choice.id }}'*. polls/views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) polls/urls.py path('/<int:question_id>/vote/', views.vote, name='vote'), detail.html <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> -
How to define the apscheduler to execute everyday?
This is my function: def start(): scheduler = BackgroundScheduler(timezone="America/Sao_Paulo") scheduler.add_job(send_daily_report, 'cron', hour='0') scheduler.start() It's worked at the first day, but didn't repeat itself. I'm executing this at the background of my principal Django application (and I'm not using django-apscheduler). May I forgot something? -
Django + MongoDB connection error after deployment to Heroku
I'm using Django(djongo) + MongoDB Altas(pymongo). So I developed this web app locally where I use Javascript's fetch method to read and write data to MongoDB. Example code: fetch("https://127.0.0.1:8000/api/fetchValues") .then(response => response.json()) .then(data => { //do something Everything works fine locally, but when I deployed it to Heroku (and hardcoded the 127.0.0.1:8000 part with <appname>.heroku.com) the same fetch method returned [ ] instead of the actual values stored in MongoDB, although I got 200 OK code from it. My settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://<username>:<pass>@cluster0.74bck.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', 'authMechanism': 'SCRAM-SHA-1', } } } I've also used import django_heroku and django_heroku.settings(locals()) on top and bottom of my settings.py respectively. I've migrated both using python manage.py and heroku run python manage.py (makemigrations/migrate of course). I believe that it comes down to Heroku config vars and specifically DATABASE_URL which I cannot remove/edit. I've tried these steps: Destroying a Postgres DB on Heroku How to change DATABASE_URL for a heroku application but nothing worked. I've also made my own MONGODB_URI config var but at no use. A fun fact is that when I used the Javascript fetch method above after deploying to Heroku (but with 127.0.0.1:8000) it … -
Loading module from “https://app.herokuapp.com/assets/index.1ab7e925.js” was blocked because of a disallowed MIME type (“text/html”)
index.html <!DOCTYPE html> <html lang="en"> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <base href="./"> <title>PzCompare</title> <script type="module" crossorigin src="/assets/index.1ab7e925.js"></script> <link rel="modulepreload" type="text/javascript" href="/assets/vendor.d0b4acaa.js"> <link rel="stylesheet" href="/assets/index.e7475acf.css"> </head> <body> <div id="root"></div> </body> </html> All of the css and js files are not being loaded because of this error 'blocked because of a disallowed MIME type (“text/html”)', no idea how to fix this, any help is appreciated! -
IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id
I am working with a blog project where I am trying to add profile picture of the user. whenever I submit the picture It gives me UNIQUE constraint failed:authentication_userprofile.user_id. views.py from .forms import ProfilePic def add_pro_pic(request): form= ProfilePic() if request.method=='POST': form=ProfilePic(request.POST,request.FILES) if form.is_valid: user_obj=form.save(commit=False) user_obj.user=request.user user_obj.save() return redirect('profile') return render(request,'profilePic.html',{'form':form}) models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User,related_name='user_profile',on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics') forms.py from. models import UserProfile from django import forms class ProfilePic(forms.ModelForm): class Meta: model=UserProfile fields=['profile_pic'] here comes profilePic.html {% extends 'base.html' %} {% block content %} <h2>Add Profile Pic</h2> <form method="POST" enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button type="submit" name='button' class="btn btn-success btn-sm">Add</button> {% endblock %} But the server shows me this UNIQUE constraint failed: authentication_userprofile.user_id IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id Request Method: POST Request URL: http://localhost:8000/authentication/addProfilePic/ Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: authentication_userprofile.user_id Exception Location: C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\ITS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\ITS\\Desktop\\blog_project\\blogproject', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 14 Dec 2021 19:40:04 +0000 where is the problem? thanks in advance. -
Add model methods to Django model on a per-app basis? Model shared among apps
I am curious as to how best to handle this situation: I've got an app that has a User model (AbstractUser); it includes all the usual attributes (username, is_superuser, is_staff, etc.) This app is shared among multiple projects (which all have their own apps) The structure looks like something like this: Project X App A App B Project Y App A App C App D Project Z App A App E App F I'm at a point where I need to add a model method on that User model in Project Z to make life easier. It would do some business logic involving other models from the other related apps. Filtering stuff from App E and App F and what not. I can't add that method directly to the User model, because then the other projects would fail since they don't have access to those other projects. What is the best way to accomplish this in Django? -
Django - resource was not found on this server on production
I am trying to access these files used from the django-import-export-celery module: I am able to see my view on local: But its not showing on my production server: This is my urlpattern: urlpatterns = static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + [ # favicon path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/Dalmore-Group-16-16.png'))), # debug path('__debug__/', include(debug_toolbar.urls)), url(r'^', admin.site.urls), ] And my settings.py has: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to deal with circular relationship in Django models?
I'm trying to write a basic DB to offer my photographs. It seemed so simple, but I just can't wrap my head around this, despite thinking for a couple of weeks. I'm trying to combine multiple models that link to each other. Photo: Files with some stored dataPerson: Data about a person that appears in a photo / has mad a Quote Quote: Something a Person has said and needs to be attached to Photos (the quote does not belong to all photos of that person, but rather a specific set) Offer: An overview that has all the quotes with one Photo as a thumbnail and all the Photos (some photos might have the same quote, but it should only appear once) As a mockup and because people here really love to see some code first I made this: class Quote: person = models.ForeignKey("Person") photos = models.ManyToManyField("Photo") class Person: photo = models.ForeignKey("Photo") class Photo: pass class Offer: quotes = models.ManyToManyField("Quote") photos = models.ManyToManyField("Photo") Please take the code above as an illustration, because I already don't know how to tackle this. I tried multiple different versions, but there is always some case that doesn't get covered. In the above example the … -
How to Ignore Required Fields when updating user account details Django-Rest, ReactJS
I have made a field for profile image in database: serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model=User fields=('id','username','email','password','first_name','last_name','profile_image') models.py I have made the following function for upload def upload_path(instance, pos, filname): return '/'.join(['profiles', filname]) User Class class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255, unique=False, default='') last_name = models.CharField(max_length=255, unique=False, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserAccountManager() profile_image = models.ImageField( blank=True, null=True, upload_to=objects.upload_path) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] views.py My post method is: def post(self, request): serializer = PostCreateSerializer(data=request.data) if serializer.is_valid(): serializer.save() items = Post.objects.all() serializer = PostCreateSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializer_class = UserCreateSerializer if serializer_class.is_valid(): serializer_class.save() queryset = User.objects.all() profile_image = request.data['profile_image'] User.objects.create(queryset, profile_image=profile_image) return HttpResponse({'message':'profile image uploaded'}, status = 200) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) On my ReactJS frontend, I am doing the following: I have made the following axios post method: export const uploadProfile = (profile_image, id) => async (dispatch) => { const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ profile_image }); alert("1234"); console.log(body) try { await axios.post( `${process.env.REACT_APP_API_URL}auth/users/`, body, config ); console.log(Response); dispatch({ type: UPLOAD_SUCCESS, }); } catch (err) { dispatch({ type: UPLOAD_FAIL, }); } }; This is the form … -
Count how many times value appears in table
Within my app, I have some forms that allow the user to select from a dropdown and I'm trying to count how many times RED, GREEN and AMBER have been selected across 20 different fields. I was looking at from django.db.models import Count queryset = MyModel.objects.all().annotate(count = Count('my_charfield')) But I'm not sure how to count the values rather than the field type? Thanks -
Django not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
UUID fails unit pytest due to formatting?
I am returning a user's UUID in my serializier and this works fine. However, when writing a unit test to test this return the test fails despite them being called the same way. Below is a simplified version of my code. My serializers.py: class UserSerializer(serializers.ModelSerializer): user_sso = serializers.SerializerMethodField("get_user_sso") class Meta: model = get_user_model() fields = ( "user_sso", ) def get_user_sso(self, user): return user.profile.sso_id My unit test in test_views.py class TestUserAPIView(BaseAPIViewTest): factory = factories.UserFactory def expected_response(self, user): return { "user_sso": user.profile.sso_id, } The failed test message (the user generated from a factory is the top one): E - 'user_sso': UUID('f696d740-bdd5-43a3-8f58-406b7a1e117d')}, E ? ----- - E + 'user_sso': 'f696d740-bdd5-43a3-8f58-406b7a1e117d'}, How do I make this test pass? I do not have the word 'UUID(' at the begining of my current output which looks to be the problem but I'm not sure how to remove this without everything a string? Many thanks. -
Why is Elastic beanstalk app creation failing at [InstallDependency] python3.8
I've rebuilt the requirements.txt multiple times, and removed and re-created pipenv, but still every time I build the deployment package for elastic beanstalk, the deployment fails giving this error: 2021/12/14 18:31:40.411896 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with Pipfile file with error Command /bin/sh -c /usr/bin/python3.8 -m pipenv install --skip-lock failed with error exit status 1. Stderr:Warning: Your Pipfile requires python_version 3.8, but you are using unknown (/var/app/s/.venv/bin/python). $ pipenv --rm and rebuilding the virtual environment may resolve the issue. $ pipenv check will surely fail. Error while executing command /var/app/staging/.venv/bin/python -c import sysconfig, distutils.sysconfig, io, json, sys; paths = {u'purelib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=0)),u'stdlib': u'{0}'.format(sysconfig.get_path('stdlib')),u'platlib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=1)),u'platstdlib': u'{0}'.format(sysconfig.get_path('platstdlib')),u'include': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=0)),u'platinclude': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=1)),u'scripts': u'{0}'.format(sysconfig.get_path('scripts')),u'py_version_short': u'{0}'.format(distutils.sysconfig.get_python_version()), }; value = u'{0}'.format(json.dumps(paths));fh = io.open('/tmp/tmpn2omzq7a.json', 'w'); fh.write(value); fh.close():Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 513, in _create_subprocess c = _spawn_subprocess( File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 190, in _spawn_subprocess return subprocess.Popen(cmd, **options) File "/usr/lib64/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib64/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 8] Exec format error: '/var/app/staging/.venv/bin/python' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/contextmanagers.py", line 205, in spinner yield _spinner File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 618, in run … -
Django Serializer only serializing objects with many=True
I am trying to make a serializer class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = '__all__' and in the viewset, def list(self, request, *args, **kwargs): obj = Store.objects.first() ser = StoreSerializer(data=obj) if ser.is_valid(): pass print(ser.data) return Response(ser.data) this method is returning just an empty dict {} as the response. When defining the serializer as ser = StoreSerializer(data=[obj], many=True) the object is getting serialized. What am I doing wrong here? -
Django-import-export-celery Import error [Errno 13] Permission denied
I have a minor issue where I always see an error 13: Import error [Errno 13] Permission denied: '/_/_/_/media/django-import-export-celery-import-change-summaries' I can still import but I cannot see the end HTML template. It's supposed to look like this (on my windows localhost): I believe this is an Ubuntu file permission issue but I do not want to do anything because as I understand it, granting permissions on a production server is dangerous. Any help is appreciated. Thanks! -
OperationalError: no such table: users_profile in Django
I am trying to create an extend User model but when I start the server I get an OperationalError: no such table: users_profile. Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates │ └───users │ login.html … -
Add some data to extra_context in response_change
I have some model: from django.db import models class Deviation(models.Model): name = models.CharField(max_length=100) def calc(self): # some calculation return 1 Then I added a button that runs calc method (overrided change form): {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Calculate" name="calc"> </div> Calculation result: {{ result }} {% endblock %} This model is registered in admin with handling calc button submit (pass result in extra_context): @admin.register(Deviation) class DeviationAdmin(admin.ModelAdmin): change_form_template = 'admin/deviations_change_form.html' list_display = '__str__', def response_change(self, request, obj): if "calc" in request.POST: obj.save() result = obj.calc() return self.change_view(request, str(obj.id), form_url='', extra_context={'result': result}) return super().response_change(request, obj) Here problem happening. I cannot render change view with result through extra_context. How can I pass extra_context to change view? -
ModuleNotFoundError: No module named 'api' (heroku)
tree ├───pzApi │ │ asgi.py │ │ db.sqlite3 │ │ manage.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───api │ │ apps.py │ │ funcs.py │ │ urls.py │ │ views.py │ │ __init__.py Procfile release: python pzApi/manage.py migrate web: gunicorn --bind 127.0.0.1:8000 pzApi.wsgi:application I'm still trying to deploy this web app and after fixing the wsgi.py not found error by putting it in the same dir as manage.py, now I have another problem where the 'api' folder is not being found, any help is appreciated! -
How to clear a ManyToMany Field in a patch request?
My ManyToMany Relationship doesn't reset. I'm doing a patch requests that translates into djrf's partial_update. But afterwards RecordUsersEntry still has the same users saved it got from setup_entry. I've tried a put request with field and record, and then the many to many relationship is resetted, but I want to reset it with a patch request. Might be related to: https://github.com/encode/django-rest-framework/issues/2883, however I'm going to use JSON Requests and at the moment I'm only concerned about how to get this test green. I've written the follwing test: def test_entry_update(self): self.setup_entry() view = RecordUsersEntryViewSet.as_view(actions={'patch': 'partial_update'}) data = { 'users': [] } request = self.factory.patch('', data=data) force_authenticate(request, self.user) response = view(request, pk=1) self.assertEqual(response.status_code, 200) entry = RecordUsersEntry.objects.first() self.assertEqual(entry.users.all().count(), UserProfile.objects.none().count()) # <-- The test fails here with def setup_entry(self): self.entry = RecordUsersEntry.objects.create(record=self.record, field=self.field) self.entry.users.set(UserProfile.objects.all()) and the model looks like this: class RecordUsersEntry(RecordEntry): record = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='users_entries') field = models.ForeignKey(RecordUsersField, related_name='entries', on_delete=models.PROTECT) users = models.ManyToManyField(UserProfile, blank=True) class Meta: unique_together = ['record', 'field'] verbose_name = 'RecordUsersEntry' verbose_name_plural = 'RecordUsersEntries' def __str__(self): return 'recordUsersEntry: {};'.format(self.pk) Viewsets and Serializer just being the basic ones: class RecordUsersEntryViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericViewSet): queryset = RecordUsersEntry.objects.none() serializer_class = RecordUsersEntrySerializer def get_queryset(self): # every field returned because they are supposed to … -
Unable to see messages using django register
I have an app with views.py as follows from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request,'username taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'email taken') return redirect('register') else: user= User.objects.create_user(username=username, password=password1, email=email, first_name=first_name,last_name=last_name) user.save(); print('user created') else: print('password missmatch') return redirect('register') return redirect('/') else: return render(request,'register.html') I have added a for loop for showing the messages in register.html {% for message in messages %} <h3> {{message}} </h3> {% endfor %} I can't able to see messages when the for loop is available but i can see message address when for loop is removed. Can some explain and help me how to proceed? -
Django: Help converting Flask app: How/where to refer to main.py?
I've set up all the foundational pages/folders for a Django app, including a bunch of html templates, admin.py, apps.py, models.py, settings.py, urls.py, views.py, etc. They work fine to pull up the menu.html template without errors. But my main py file, which I call index.py, which has most of my functionality: How and where do I refer to it? Thanks! -
How can i submit two forms in django
I have a template where i should have 2 forms and update them, I succeded to get the 2 foms in the same template, but when i make changes nothing happens ! forms.py class OrderManageForm(forms.ModelForm): class Meta: model = Order fields = ['customer', 'product', 'quantity', 'status'] class CustomerForm(forms.ModelForm): address = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) class Meta: model = Customer fields = ['full_name', 'address', 'phone', 'city', 'email' models.py class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') def __str__(self): return 'Order n°: ' + str(self.id) views.py def update_order(request, order_id): order = get_object_or_404(Order, id=order_id) cust = get_object_or_404(Customer, order__id=order_id) if request.method == 'POST': customer = CustomerForm(request.POST) form = OrderManageForm(request.POST) print(request.POST) if form.is_valid() and customer.is_valid(): order = form.save(commit=False) customer = customer.save() order.customer = customer order.save() return redirect('orders') else: form = OrderManageForm(instance=order) customer = CustomerForm(instance=cust) return render(request, 'dashboard/order_details.html', {'form': form, 'customer': customer}) I put the 2 forms in only one form tag inside my HTML template -
Write an Effective query for django for a FOR Loop?
I need to get number of policies bought in each month from these model class Insurance(models.Model): #other fields.. date_purchased_on = models.DateField(auto_now_add=True) customer_region = models.CharField( max_length=10, choices=RegionType.choices) so i have written a views to get a response @api_view(['GET']) def chart_data(request): # structure of the op should be all the months from 1 to 12 # [{"month": 1,"count": 100,}, { "month:2", "count":20}] filtered_data = [] for i in range(1, 13): query = Insurance.objects.filter(date_purchased_on__month=i).count() data = { "month": i, "count": query } filtered_data.append(data) return Response(filtered_data) now the problem is this query hits the database every time its like 12 times. is there a way to handle this to get in a single query or to reduce it and my logger results (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 1; args=(1,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 2; args=(2,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 3; args=(3,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 4; args=(4,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 5; args=(5,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" …