Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How can I put the initial data into database by editting migrations file?
I added 'models' and created a file using 'makemigrations'. I want to have the initial data in the database at the same time as 'migrate'. However, no matter how much I edit the 'migrations' file, there is an error that says no because there is no 'table' in the database before 'migrate'. Help me... -
Django REST Framework serialize multiple foreign keys related between
Let's imagine we have next models: class Radio(models.Model): name = models.CharField(...) class Artist(models.Model): name = models.CharField(...) class Song(models.Model): title = models.CharField(...) artist = models.ForeignKey(Artist, ...) class Reproduction(models.Model): song = models.ForeignKey(Song...) radio = models.ForeignKey(Radio...) date = models.DateTimeField(...) How should I create my serializer and view if I will receive in a POST: title: "Song title", artist:"Artist name", radio:"Radio name", date:"Reproduction date" and it's needed to create the artist and the song if they don't exist. Thank you. -
Django migration error table is already exists
Hi i have only one migration file called 001_initial..... it contains all create table(sql) django makemigrations created when i did makemigrations for example 5 tables [1,2,3,4,5] and i have first(1) already there in my database for example 1, so i need to migrate table for example 2,3,4,5 but i'm getting error when i do python manage.py migrate, error is table one(1) is already created and table 2,3,4,5 not created in the database because of this error i have only one migration file an i deleted the django_migration file data so how to do? -
NOT NULL constraint failed: app_model.author_id
I am trying to make forms only visible to its author but I fail with this error NOT NULL constraint failed: app_myModel.author_id when I add some objects from Django Administration, added objects are visible for all, but in template if I fill the form and click save button it gives me above error. Here what i have tried so far models.py class Project(models.Model): service_name = models.CharField(max_length=100) service_code = models.CharField(max_length=5) report_month = models.CharField(max_length=6) report_year = models.CharField(max_length=6) last_year = models.CharField(max_length=6) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.service_name views.py def add_object(request): ProjectFormSet = modelformset_factory(Project, fields=( 'service_name', 'service_code', 'report_month', 'report_year', 'last_year'), extra=1) if request.method == "POST": form = ProjectFormSet(request.POST) form.author = request.user if form.is_valid(): form.save() form = ProjectFormSet() return render(request, 'app1/home.html',{'form':form}) here what I have. How can I add objects and make visible only for its author. Any help? -
Django Channels, instantiating a new Consumer on the fly, not linked to a Websocket or other protocol?
I am building off the Django Channels Tutorial, trying to add a "Chat Manager" consumer to the tutorial's simple chat app. It would function as a simple chatbot, maybe sending a random message in the chatroom every ten seconds, for example. The idea is that this ChatManagerConsumer would be created once when a new chat room is made, and only one ManagerConsumer exists for the lifespan of the whole chatroom, even as individual users/WebsocketConsumers come and go from the room. I'm not clear on how to go about doing this. Background workers would not work, since it looks like you can't programmatically create multiple instances of a background worker; only one can be spawned from the command line. Instead, I would like to have one Consumer instance running per each chat room. The documentation says "consumers are long-running" and "a chatbot protocol would keep one scope open for the entirety of a user’s conversation with the bot" but doesn't really explain how to open up a consumer for this hypothetical chatbot protocol. Any help would be appreciated! -
django+heroku+postgres error in createsuperuser "
i wanted to deploy my django app in heroku with postgresql ,everything went well , migrations ran fine but when i am trying to createsuperuser it is giving me error (youngmindsenv) E:\young_minds\heroku\youngminds>heroku run bash Running bash on ? youngminds... up, run.8229 (Free) ~ $ python manage.py createsuperuser Username (leave blank to use 'u21088'): johnson Email address: johnson@gmail.com Password: Password (again): Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils .py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_profile" does not exist LINE 1: INSERT INTO "users_profile" ("user_id", "image", "descriptio... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user _data) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode ls.py", line 161, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode ls.py", line 144, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base _user.py", line 73, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py ", … -
Best way to call a function in specific time in django
in my django project i have a model Task : class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() expiration_date = models.DateTimeField(default=max_expiration_date) #################################### def max_expiration_date(): now = timezone.now() return now + timezone.timedelta(days=7) exact in expiration date i need call notification function.please be notice i will have too many Task instance so i need the best method for optimal system consumption.what is best way to do that? celery can do this?thank you. -
Does Amazon-SES provide any api to know if the email was successfully sent?
So I am sending a few emails to clients using Amazon-ses. In few cases, I need to know if the email was successfully delivered. Is there any way to know? Does Amazon provide any api that tells me if the email was delivered successfully? Some of the mails I send have critical status. I am using django1.9 and python3. -
Adapting an existing django site for modal forms
I have a site which uses the urls to add/edit/view records to the database. These pass the information to another template for data entry. I'm now looking at modal forms - at the moment we have used css, rather than the Django modal forms. My question, which is basic, is it possible to keep the urls and templates but embed them in the modal? This way we can keep the same code and migrate to modals without recoding the views. I'm looking for a clear simple documentation for this - so please send me any good links. For a basic example (we have more complex views): template storage {% extends 'storage/base.html' %} {% load staticfiles %} {% load widget_tweaks %} {% block content%} {% include "mainheader.html" %} {% include "storage/submenu.html" %} <div class="container top"> <div class="row"> {% for storage in storage.all %} <a class="text-light" href="{% url 'depot:detailstorage' storage.store_id %}"> <div class="col-md-4"> <div class="card text-white bg-dark mb-3" style="max-width: 18rem;"> <!--div class="card-header">{{ storage.store_name }}</div--> <div class="card-body" style=""> <h5 class="card-title text-center">{{ storage.store_name }}</h5> <img class="card-img-top p-3" src="{{ storage.icon_desc.icon.url }}" /></a> <p class="card-text" style = "font-size:0.7em;">{{ storage.address_1 }} {{ storage.address_2 }} {{ storage.city }} {{ storage.region }} {{ storage.zip }} {{ storage.country }}</p> </div> … -
Uploading and using static (for Django project) to AWS S3
Thanks for taking the time to read this. My issue is simple. I was able to setup the collectstatic function to upload static to AWS S3, but screwed up a little. I have been making some changes and now, my website is not using the correct url to load the css files. So my initial code moved the static to S3 bucket, folder 'static' and referenced it at this url: https://{project}.s3.amazonaws.com/static/css/bootstrap.min.css Now, after some of the changes I have made it references the same address, but without the 'static' folder: https://{project}.amazonaws.com/css/bootstrap.min.css Same thing happens to collectstatic function. Instead of loading all the static to the 'static' folder it loads everything to the root of the bucket. Here is my settings file: settings.py AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/static/" % (AWS_S3_CUSTOM_DOMAIN) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = 'https://%s/media/' % (AWS_S3_CUSTOM_DOMAIN) Thanks for all the help in advance! I really appreciate the community and support. Best, Rasul Kireev -
I have python syntax error in django project
first, i am beginner of django and python i want to make sign up and login service but i have python syntax error I use python 3.7.3 from django.shortcuts import render from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == "POST" : if request.POST["password1"] == request.POST["password2"] : user = User.objects.create_user{ username=request.POST["username"], password = request.POST["password"] if user is not None: auth.login(request,user) return redirect['home'] else: return render(request, 'login.html', {'error': 'username or password is incorrect'}) else: return render(request,'login.html') } in line 8, (user = User.objects.create_user) i have syntax error help me! -
NoReverseMatch at /config/list_enseignant/
I try to list instances of enseignant but I have the raised exception Reverse for 'dfi' with arguments '(14,)' not found. 1 pattern(s) tried: ['config/ajoutdfi/$'] I don't know very well what to do if i delete all the instances of dfi I'll get list of enseignant. models.py class Enseignant(Personne): type_enseignant=models.CharField("Type d'enseignant",max_length=75, choices=(("misssionnaire", "Missionnaire"),("permanent", "Permanent"),("vacataire", "Vacataire") ),default='permanent' ) departement_enseignant=models.ForeignKey("Departement",max_length=75, verbose_name="Département de tutelle", on_delete=models.CASCADE) poste_enseignant=models.CharField("Poste de l'enseignant", max_length=75, choices=(("enseignant","Enseignant"), ('resp_niv', 'Responsable de Niveau'), ('chef_dpt', "Chef de département"), ("dfi", "DFI")), ) grade_enseignant=models.CharField("Grade de l'enseignant",max_length=75, choices=(('M./Mme','M./Mme'),('Ass','Assistant'), ('Cc','Chargé des Cours'),('Mc', 'Maître de conférences'),('Pr','Professeur')) ) anciennete_grade=models.IntegerField('Ancienneté au grade', validators=[ MinValueValidator(limit_value=0, message="L'ancienneté entrée est négative" ), MaxValueValidator(limit_value=50, message='Ancienneté supérieur à 50') ]) def __str__(self): return "{0} {1}".format(self.nom, self.prenom) class DFI(Enseignant): faculte=models.OneToOneField(Faculte, on_delete=models.CASCADE) views.py class list_enseignant(ListView): model =Enseignant context_object_name = "liste_enseignant" template_name = "configuration/lister_enseignant.html" traceback C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = response.render() ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\response.py in render self.content = self.rendered_content ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\response.py in rendered_content content = template.render(context, self._request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\backends\django.py in render return self.template.render(context) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\base.py in render return self._render(context) … -
Loggin django based in class view no working,
I'm new to django, I'm doing a login based on a udemy course, but it does not work for me. My error is that the credentials are not correct, if I start session with admin it does not work either. This is my code, I hope you can help me thanks, If there is any way to debug to find the error, please tell me url.py ############################################################################## from django.conf import settings from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views from tienda.users.views import ( Indice, ListarProductos, DetalleProducto, ComentarioProducto, Ingresar, Salir, CambiarPerfil ) urlpatterns = [ path('', Indice.as_view(), name="indice"), path("listado_productos", ListarProductos.as_view(), name="listado_productos"), path("detalle_producto/<int:pk>/", DetalleProducto.as_view(), name="detalle_producto"), path("crear_comentario/", ComentarioProducto.as_view(), name="crear_comentario"), path("ingresar/", Ingresar.as_view(), name="ingresar"), path("salir/", Salir.as_view(), name="salir"), path("editar_perfil/", CambiarPerfil.as_view(), name="editar_perfil"), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ######################################################################## views.py from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.views.generic import DetailView, RedirectView, UpdateView, TemplateView , CreateView, ListView from django.db.models import Q, Max, Min from tienda.productos.models import Producto, Comentario from django.contrib.auth.views import LoginView, LogoutView from django.http import HttpResponseRedirect from django.urls import reverse_lazy, … -
Paginate comments to Posts
I have a comment form for my posts. It looks like this view.py def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user #comment.author.photo = object.author.profile.image.url comment.save() return redirect('Post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=20) text = models.TextField(max_length=200, verbose_name='内容') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('text',) widgets = { #size of textbox 'text': forms.Textarea(attrs={'rows':4}), } Where should I add pagination function to my comments to make it works? I have a pagination for my posts, but posts are using a DetailView class and I dont know how to make it work for comment function -
Error when trying to access uploaded files in Django application
I have a Django application where I'm uploading some json files. When trying to access these files got 404 (not found) error. The files are to load in a OpenLayers layer. If I use a json in project static files it works fine. The files are uploading correctly to "uploaded_files" directory in project folder. But when trying to access these files in html page by object.file.url I always get error. If I change MEDIA_URL to "/uploaded_files/" got error because it expects to find core/ or admin/ url. Example: http://127.0.0.1:8000/uploaded_files/file.json settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/core/uploaded_files/' # core is the application in django project. I have admin and core applications. MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_files') urls.py file: from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py file: def get_upload_file_name(instance, filename): return "%s_%s" % (str(time()).replace('.', '_'), filename) class Estado(models.Model): estado = models.CharField(max_length=2) def __str__(self): return self.estado class TipoFile(models.Model): tipo = models.CharField(max_length=50) def __str__(self): return self.tipo class FileEstadoMunicipio(models.Model): estado = models.ForeignKey(Estado, on_delete=models.CASCADE, null=False) municipio = models.CharField(max_length=100, null=False) tipo = models.ForeignKey(TipoFile, on_delete=models.CASCADE, null=False) dat_criacao = models.TimeField(default=datetime.datetime.now(), null=False) file = models.FileField(upload_to=get_upload_file_name, null=False) html file: {% load static … -
Is there a way to save the current time + 1 hour or 1day or 1week to a DatetimeField using django view orm?
Is there a way to save the current time + 1 hour or 1day or 1week to a DatetimeField using django view orm? for example models.py dead_line = models.DateTimeField(blank=True, default=utc_tomorrow) def add_todo_by_ajax(request): title = request.POST['title'] dead_line_option = request.POST['dead_line_option'] # print("dead_line_option : " , dead_line_option) if dead_line_option == "1h": print ("1h") # deadline = elif (dead_line_option == "4h"): print ("4h") elif (dead_line_option == "8h"): print ("8h") elif (dead_line_option == "1d"): print ("1d") elif (dead_line_option == "8h"): print ("1w") todo = Todo.objects.create(title=title, author=request.user, director = request.user) print("todo(insert result) : " , todo) user_update = Profile.objects.filter(user=request.user.id).update(uncompletecount = F('uncompletecount')+1) return HttpResponse(redirect('/todo/')) -
How to use href in a loop in Django?
I want to create a side bar in which I want to add different links. My query is that the IDs if the hrefs are same but the names are different. Like 127.0.0.1:8000/1/Austria 127.0.0.1:8000/1/America I want to refer every href to a different link. Is it possible using a loop?If yes, Please tell me how? Here is the code views.py def details(request,item_id): item=get_object_or_404(Item,pk=item_id) clients=Client.objects.all() return render(request,'details.html',{'item':item,'clients':clients}) template.html <div> <h1 style="text-align: center">Products</h1> <div class="container-fluid d-none d-xl-block" style="width: 17%;height: 1400px;float: left;background-color: lavender"> <ul style="list-style: none;" class="form-control" id="client"> {% for client in clients %} <li class="btn btn-block btn-responsive" style="background-color: #daad86;color: white;width: 250px;height:50px;margin-top: 10px"><a href="{{ client.place }}">{{ client.place }}</a></li> {% endfor %} </ul> </div> url.py path('<int:item_id>/',views.details,name='details'), Thanks in advance -
Upgrade to django2.2.2 produces TypeError: render() got an unexpected keyword argument 'renderer'
I have an application that seemed to work fine under django 2.0 using postgresql. I decided to rebuild it using sqlite3 and took the opportunity to upgrade to django 2.2.2. I am moving my code in from the old application on an as-needed basis, hoping to leave some mistakes behind. When I use a Generic View (CreateView) with a form that uses crispy forms and auto-complete-light, I get the error cited in my title. Other, similar questions lead me to believe that auto-complete-light has been updated for this problem. I am running django 2.2.2 in a virtual environment on MacOS 10.14.5. Here is the result of pip freeze: backports.csv==1.0.7 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20181111 Django==2.2.2 django-autocomplete-light==3.3.5 django-bootstrap3-datetimepicker==2.2.3 django-bootstrap4==0.0.6 django-crispy-forms==1.7.2 django-crontab==0.7.1 django-csvimport==2.12 django-datetime-widget==0.9.3 django-debug-toolbar==2.0 django-extra-views==0.12.0 django-filter==2.1.0 django-guardian==2.0.0 django-import-export==1.2.0 django-pdb==0.6.2 django-pivot==1.8.0 django-querysetsequence==0.11 django-tables2==2.0.6 djangorestframework==3.9.4 et-xmlfile==1.0.1 jdcal==1.4.1 odfpy==1.4.0 openpyxl==2.6.2 pytz==2019.1 PyYAML==5.1.1 six==1.12.0 sqlparse==0.3.0 tablib==0.13.0 Unipath==1.1 xlrd==1.2.0 xlwt==1.3.0 Here is the view that produces the error: views.py from .forms import BankTransactionInputForm from .models import BankTransaction from django.views.generic import CreateView class BankTransactionCreate(CreateView): model = BankTransaction form_class = BankTransactionInputForm success_url = 'http://localhost:8000/mny/home/' Here is the form referred to: forms.py from django.forms import ModelForm from django import forms from django.db import models from crispy_forms.helper import FormHelper from crispy_forms.layout import … -
Updated via form OnetoOneField - Duplicate key value violates unique constraint
I am creating an app in which a user can create a project and each project has one-and-just-one set of questions (i.e. a form - I called it Firstquestions). I want the user to be able to edit/update this set of questions via a form. However, I get the error: duplicate key value violates unique constraint projects/models.py class Project(models.Model): title = models.CharField(max_length=255) content = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) projects/urls.py urlpatterns = [ #Regarding the projects path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), path('<int:project_id>/deleteproject', views.deleteproject, name='deleteproject'), #Regarding the set of questions path('<int:project_id>/', include('firstquestions.urls')), ] firstquestions/urls.py class Firstquestion(models.Model): first_one = models.TextField() first_two = models.TextField() first_three = models.TextField() first_four = models.TextField() first_five = models.TextField() first_six = models.TextField() first_seven = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) firstquestions/urls.py urlpatterns = [ path('questionstoanswer', views.questionstoanswer, name='questionstoanswer'), path('firstquestionsdetail', views.firstquestionsdetail, name='firstquestionsdetail'), path('firstquestionsedit', views.firstquestionsedit, name='firstquestionsedit'), ] MY EDIT FUNCTION firstquestions/views.py @login_required def firstquestionsedit(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': if request.POST['first_one'] and request.POST['first_two'] and request.POST['first_three'] and request.POST['first_four'] and request.POST['first_five'] and request.POST['first_seven']: question = Firstquestion() question.first_one = request.POST['first_one'] question.first_two = request.POST['first_two'] question.first_three = request.POST['first_three'] question.first_four = request.POST['first_four'] question.first_five = request.POST['first_five'] # question.first_six = request.POST['first_six'] question.first_seven = request.POST['first_seven'] question.developer = … -
query filter with namespace and path from url parameters
I have a django rest framework app. I want to pass in two paramters through the url and if they are passed in, I want to then use each of the parameters as a filter in the queryset. So basically. if not parameter is passed, then grab all data for user. if namespace is passed in I want to filter by user and namespace. if path is pased in, I want to filter by user, namespace, and path. RIght now it is not doing that. I have it setup as 3 different urls that go to 3 different viewsets because whne I try to make it a single url it bugs out and does not work at all. I also want namespace and path to be optionally included in the url so the url would work without namepsace and path assigned to it. When i tried a single url it would require both parameters to work.... Urls: router.register(r'preferences', PreferenceUserViewSet, basename='Preference') router.register(r'preferences/(?P<namespace>.+)', PreferenceNamespaceViewSet, basename='Preference-namespace') router.register(r'preferences/(?P<namespace>.+)/(?P<path>.+)', PreferencePathViewSet, basename='Preference-path') viewset: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def … -
Solving NoReverseMatch at /projects/19 in nested urls
I created Django app. The user can create a new project. Once created, each project has a set of 10 macroquestions. Each macroquestion contains a form. The relationship project-macroquestion is OneToOneFiled. The User is showed all the macroquestions for that specific project in projectdetails. Here, the user can: 1) Click on "Answer the macroquestion" so he is redirect to the form (see above) 2) Click on "Edit the macroquestion" which is not working Basically, if the "Edit the macroquestion" is clicked, I want to: {% url 'firstquestionsedit' project.id question.id %} BUT it gives me the error: Solving NoReverseMatch at /projects/19 in nested urls. The project.idis succesfully passed, in fact is 19, but this is not the case for question.id, which is empty. Reverse for 'firstquestionsedit' with arguments '(19,)' not found I think the problem is that question.id is created after. projects/urls.py urlpatterns = [ #Regarding the projects path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), path('<int:project_id>/deleteproject', views.deleteproject, name='deleteproject'), #Regarding the set of macro-questions path('<int:project_id>/firstquestions/', include('firstquestions.urls')), ] projects/models.py class Project(models.Model): title = models.CharField(max_length=255) content = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstquestions/urls.py urlpatterns = [ path('questionstoanswer', views.questionstoanswer, name='questionstoanswer'), path('<int:question_id>/firstquestionsdetail', views.firstquestionsdetail, name='firstquestionsdetail'), path('<int:question_id>/firstquestionsedit', views.firstquestionsedit, name='firstquestionsedit'), ] firstquestions/model.py class Firstquestion(models.Model): … -
How to calculate total price of a product in models in Django?
I want to calculate total price of products.I am calculating the price in models.py using @property. But the problem I m facing is that the product table is in Product app (models.py) which contains price however the quantity is in the Cart app (models.py). And for total I want to multiply price*quantity. Cart/models.py class CartItem(models.Model): cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True) product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True) accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True) quantity=models.IntegerField(default=1) updated = models.DateTimeField(auto_now_add=True,auto_now=False) line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True,on_delete=models.SET_NULL) product = models.ManyToManyField(Product, blank=True) accessory = models.ManyToManyField(Accessories, blank=True) subtotal = models.DecimalField( default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField( default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True,) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) Product/models.py class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=20, default=0.00) In my Cart/models.py def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) Cart/template.html <tr class="total"> <td>Total</td> <td colspan="4"></td> <td class="num">{{cart.get_total_price|floatformat:"2"}}</td> </tr> But it's displaying the total as 0.00. I have also tried it as: def get_total_price(self): return self.product.price* self.cartitem.quantity But all in vain nothing worked. Please help me in this regard? Note: I have made a function in cart/views.py fro calculating the total. Can i call use that calculation somehow in cart/models.py. Thanks in advance -
Django oauth toolkit is it possible to log in using only client id and secret id?
I have to communicate through REST two internal applications, I don't need to use user credentials. Is it possible to authenticate using only cliend_id and client_secret keys? If this is not possible with OAuth Thanks in advance to all -
question about where self.kwargs come from if it is not defined? specifically in the SingleObjectMixin class in the django code base
I am following a Django tutorial and I am creating a CBV that inherits from (SelectRelatedMixin, DetailView) and I was taking a look at the code base when I reached SingleObjectMixin which has a function called get_object. It sets pk=self.kwargs.get(self.pk_url_kwarg) Where does kwargs attribute come from here? because SingleObjectMixin is only instantiating from one class "ContextMixin" and this does not have that attribute This is a part of the function: def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) -
Dynamically display django form multiple times
I am using django formset to get display django form few times to get information from user. But here the number of times I can display form is fixed. Is there any good way to get display form dynamically, once the user enter the details then display same form again to get more information without refreshing the page. Below is the code currently I'm using. in models.py class Tiers(models.Model): user = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,) tier_name = models.CharField(max_length=128, blank = True) #name of the tier tier_value = models.IntegerField() #Can only be in exact dollar amount tier_benefits = models.CharField(max_length = 5000, blank = True) #creators explain what the donor benefits for each tier in forms.py class TierForm(forms.ModelForm): class Meta: exclude = ['user'] model = models.Tiers TierFormset = modelformset_factory(models.Tiers,form=TierForm, extra=2) in HTML page <!-- {% extends "base.html" %} --> {% load bootstrap3 %} <!-- {% block content%} --> <div class="container"> <h1>Update Your Profile</h1> <form method="post"> {% csrf_token %} {% bootstrap_formset formset %} <input type="submit" class='btn btn-default' value="Update Profile"> </form> </div> <!-- {% endblock%} --> Currently I'm displaying form 2 times but I want to display several depends how tiers user want to use. Thanks!