Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
как создать форму из двух связанных моделей?
я не очень опытен в джанго, поэтому нужна помощь. Подскажите пожалуйста что делать? Класс курсов: class Course(models.Model, HitCountMixin): STATUS_CHOICES = ((1, u'На модерации'), (2, u'Отклонена'), (3, u'Включена')) title = models.CharField(u'Заголовок', max_length=250) slug = AutoSlugField(populate_from='title', unique=True, max_length=255) category = models.ForeignKey(CourseCategory,on_delete=models.CASCADE) image = models.ImageField(u'Картинка', upload_to=user_courses_directory_path, blank=True, null=True) description = models.TextField(u'Описание', blank=True, default='') author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) price = models.PositiveIntegerField( u'Цена', blank=True, default=0) status = models.PositiveIntegerField(choices=STATUS_CHOICES, default=1) is_published = models.BooleanField(default=False) likes = ArrayField(models.IntegerField(blank=True), blank=True, null=True) dislikes = ArrayField(models.IntegerField(blank=True), blank=True, null=True) hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) objects = CourseManager() Класс Видео которые находятся внутри курсов class CourseVideo(models.Model, HitCountMixin): """Model for course videos""" title = models.CharField(u'Заголовок', max_length=250) course = models.ForeignKey(Course,on_delete=models.CASCADE) price = models.PositiveIntegerField( u'Цена', blank=True, default=0) is_published = models.BooleanField(default=False) position = models.PositiveIntegerField(u'Позиция', default=1) is_deleted = models.BooleanField(default=False) likes = ArrayField(models.IntegerField(blank=True), null=True) dislikes = ArrayField(models.IntegerField(blank=True), null=True) image = models.ImageField(u'Картинка', upload_to=user_course_video_directory_path, null=True) preview_video = models.FileField( upload_to=user_course_video_directory_path, blank=True, null=True) image = models.ImageField(u'Картинка', upload_to=user_directory_path, blank=True, null=True) file = models.FileField( upload_to=user_course_video_directory_path) objects = CourseVideoManager() Мне нужно сделать одну форму из этих двух моделей так чтобы с одной страницы можно было добавить и курс и видео в них помогите пожалуйста!!! SOS SOS SOS -
Django Update unique modelform field
I am new to Django, I created small stock web app. I created stock model with unique "part_number" field. in update template, I send all item information to be displayed. Then I get an error in the part_number field that it is already there. How can I avoid this validation for that part_number only! I mean for same part_number suppose validation will not work. But if I modified to another part_number that is exist. suppose to raise "duplicated" Model: class Stock(models.Model): part_number = models.CharField(max_length=30, blank=False, unique=True) part_name = models.CharField(max_length=70) quantity = models.IntegerField(blank=False) location = models.CharField(max_length=3, blank=True) model = models.CharField(max_length=40, blank=True, null=True, default="") min_quantity = models.IntegerField(unique=False, blank=True, default=0) max_quantity = models.IntegerField(unique=False, blank=True, default=0) class Meta: ordering = ['part_number'] def clean(self): self.part_number = self.part_number.upper() def __str__(self): return self.part_number Form.py: class StockUpdateModelForm(forms.ModelForm): class Meta: model = models.Stock fields = ['part_name', 'quantity', 'location','part_number'] views.py: def stock_update_form_view(request, part_id): item = Stock.objects.get(id=part_id) item_id = Stock.objects.get(id=part_id).pk form = StockUpdateModelForm({ 'part_number' : item.part_number, 'part_name' : item.part_name, 'quantity' : item.quantity, 'location' : item.location }) if request.method == 'POST': form = StockUpdateModelForm(request.POST) if form.is_valid(): s = Stock.objects.get(pk=item_id) s.part_name = form.cleaned_data['part_name'] s.part_number = form.cleaned_data['part_number'] s.quantity = form.cleaned_data['quantity'] s.location = form.cleaned_data['location'] print("form is valid") s.save() return redirect('/stock/') return render(request, 'stock/stock_update.html', {'form': form, … -
Standalone Vue front end for Django admin
I was wondering if there's a way to display a standalone Vue front end for the Django Admin. I know people use a standalone frontend with Django but not on the admin site. Imagine two separate servers: One is the standalone Vue server that is the frontend and the other is the Django server for the backend. I was hoping to communicate between the two using the Django Rest Framework but I don't understand how I'll do that for the admin site. My goal is basically display and update what default Django admin displays, but not using the admin templates that Django provides, rather the templates that the Vue server will serve. Could someone tell me where to get started? -
I am getting an error as 'QuerySet' object has no attribute 'Profile' what does that mean and how to solve it?
Guys I am having an issue using django since I am newbie and learning right now and making a temporary project of blog where I am having a Profile page and there I want to insert an image and just of checking I am using shell and trying to find out url of the image (in my own laptop) but I am getting an error "QuerySet' object has no attribute 'Profile" I am also attaching a image for your reference [1]: https://i.stack.imgur.com/CdaFw.png [2]: https://i.stack.imgur.com/BMkyv.png So I have attached my image links above please take a look and please solve this issue as I am not able to learn ahead. I am also providing you the code which I am writing in my shell :- **from django.contrib.auth.models import User In [2]: user = User.objects.filter(username = "varun") In [3]: user Out[3]: <QuerySet [<User: varun>]> In [4]: user.profile** This gives me the result as :- 'QuerySet' object has no attribute 'profile' -
What's the most performant way to track deleted database rows?
TL;DR How to professionally track deletions? Anyway, lemme illustrate what I want. I'm creating a technical-commercial website for myself and I want to track everything that gets deleted, this means I'll not use database CASCADEs and I need a way to track the data removed. I want to be as DRY as possible. Let's say I've a user who has a profile and both are one to one, when someone deletes his account, both the user and his profile should be deleted, I want to keep track of the deleted users/profiles and I've been thinking about performance because the API itself will be intensively heavy. Create a separate table which has the same structure as the deleted tables to track deletions Create an attribute to mark users/profiles as deleted Use a polymorphic relation with a table that's with a model say it's called Trackable and this model should be all to query all deletions of all models, and when I query, I filter by the model type, so essentially everything that I want to track inherits from Trackable ... The problem is that if I wrote the first logic, I'll have a lot of repetitive code as I'll have each … -
Django context variable in the navigation bar - correct href assignment?
What is the correct assignment of context variables in the navigation bar? My Django example is: in view.py: from django.shortcuts import render from django.http import HttpResponse context_navigation = { 'Link1' : 'Blog', 'href1' : "{% url 'blog' %}", } def index(request): return render(request, 'app_about/index.html', context=context_navigation) in urls.py: from django.urls import path from . import views urlpatterns = [ path('blog/', views.index, name='blog'), ] in templates/base.html this does work <a class="nav-item nav-link text-light" href="{% url 'blog' %}" > {{Link1}}</a> this does not work (see href1 and Link1) <a class="nav-item nav-link text-light" href={{href1}}" > {{Link1}}</a> In the last case a wrong url is generated, something like http://127.0.0.1:8000/blog/%7B%. What is the correct assignment of href as a context variable href1 ? Thank you for some hints! -
how call a comment function in django
i'm trying to add bid and comments to a item page but if the user make a comment return this error: UNIQUE constraint failed: auctions_bids.auction_id if the user make a bid return this one: int() argument must be a string, a bytes-like object or a number, not 'NoneType' how should i call this functions? def add_bid(request, id): username = request.user.username # get username item = Auction_listings.objects.get(pk=id) try: bid_value = int(Bids.objects.get(auction=id).bid_value) except: bid_value = int(item.product_price) if request.method == "POST": new_bid_value = int(request.POST.get("bid")) if new_bid_value > bid_value: new_bid = Bids(auction=item, username=username, bid_value=bid_value) new_bid.save() else: return render(request, "auctions/error.html", { "error": "your bid is lower than the current bid..." }) def add_comment(request, item_id): if request.method == "POST": comment = request.POST.get("comment") # get user comment new_comment = Comments(auction=item_id ,username=request.user.username, content=comment) new_comment.save() def view_item(request, id): item = Auction_listings.objects.get(pk=id) try: if request.method == "POST": add_bid(request, id) add_comment(request, item) bid = Bids.objects.get(auction=item) except: if request.method == "POST": add_bid(request, id) add_comment(request, item) bid = '' return render(request, "auctions/item.html", { "auctions": item, "username": request.user.username, "comments": Comments.objects.filter(auction=item), "bid": bid }) urls.py: from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("user/<username>", views.user_page, name="user_page") path("item/<id>", views.view_item, name="view_item"), path("item/<item_id>", views.add_comment, name="add_comment") ] thank … -
Object is not subscristable django
i have a function which is trying to get all the elements from a model and agroup them in a list, but when i try to get the query, i get the error 'Customer_Group' Object is not subscritable.. I am using two methods get_groups is to obtain the list and process_all_groups is for create the list. Where is my mistake in here?: @api_view(['POST', 'PUT', 'GET']) @permission_classes([LoginRequired]) @renderer_classes([JSONRenderer]) def get_groups(request): resp = {'dat': '', 'message': 'no se encontro groups', 'success': False} database = request.user.company_select.company_db try: groups = Customer_Group.objects.using(database).all() if groups: list_groups = process_all_groups(groups, database) resp = {'dat': list_groups, 'message': 'exito!', 'success': True} except Exception as e: print(e) resp.update(dict(message='Error')) return Response(resp) def process_all_groups(groups, database): list_groups = list() for group in groups: group_aux['id_group'] = Customer_Group.objects.using(database).values().filter(id_group=group['group_id']) group_aux['group_code'] = Customer_Group.objects.using(database).values().filter(group_code=group['group_code']) if group_aux: list_groups.append(group_aux) return list_groups Thank you!! -
Django: Page not found but path is shown
I have recently started using Django and I am a little lost as to why my services.html page does not render as I have followed what appears to be the same steps I took for my home page to work but I keep getting the error that nothing matches the current path. Below are my snippets for views and urls.py. I also had it be included in my website urls.py by using path('', include('affiliate.urls')), Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin/ [name='home'] [name='services'] The current path, services.html, didn't match any of these. Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('', views.services, name="services"), ] Views.py from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html', {}) def services(request): return render(request, 'services.html', {}) -
Django REST Framework API Key
I'm trying to use Django REST Framework API Key package. I installed it and configure it correctly. I need to mack HTTP request to endpoint that has permissions of HasAPIKey. {I need to pass key to access it } firstly I create API key in the admin page. Then I tried to access with that API. and I git this error. "detail": "Authentication credentials were not provided." I think that I don't configure the api key correctly. I don't know how to do it :( -
Django generic editing views: Styled HTML form is not saved
I'm using Django's generic editing views CreateView, UpdateView, etc. together with the auto-generated HTML forms and it works fine: # views.py class TagCreate(CreateView): template_name = 'app/tag_form.html' model = Tag fields = ['name', 'description', 'color'] class TagUpdate(UpdateView): model = Tag fields = ['name', 'description', 'color'] <!-- app/tag_form.html --> {% extends 'app/base.html' %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} Now, I want to customize the generated form {{ form.as_p }} with bootstrap: {% extends 'app/base.html' %} {% block content %} <form method="post"> {% csrf_token %} <div class="form-group"> <label for="nameInput">Name</label> <input class="form-control" type="text" id="nameInput" placeholder="Name" value="{{ tag.name }}"> </div> <div class="form-group"> <label for="descrInput">Description</label> <input class="form-control" type="text" id="descrInput" placeholder="Description" value="{{ tag.description }}"> </div> <div class="form-group"> <label for="colorInput">Color</label> <input class="form-control" type="color" id="colorInput" placeholder="Color" value="{{ tag.color }}"> </div> <input type="submit" value="Save"> </form> {% endblock %} The page renders nicely exactly how I want it to, but when I click the "Save" button, nothing happens and the data is no longer saved, nor am I forwarded to the detail view like I was before. I tried following the Django documentation on how to render fields manually; again, it's rendered correctly, but the data isn't … -
Django js create a newWindow unable find url
I am using ajax to update photo. But newwindow can't load url imagecrop.html $('#btnCrop').on('click', function () { alert("图片上传喽"); var newWindow = window.open() $.ajax({ url: '{% url "account:my_image" %}', type: 'POST', data: {"img": img}, success: function (e) { newWindow.location.href = url {#if (e == "1") {#} {# parent.location.reload();#} {# } else {#} {# alert("图片未上传成功,请稍后再试")#} {# }#} } }); urls.py url(r'^detail/$', views.myself, name='detail'), url(r'^edit_detail/$', EditMyself.as_view(), name='edit_detail'), url(r'^my_image$', views.myImage, name='my_image'), views.py @login_required() def myImage(request): if request.method == 'POST': img = request.POST['img'] userinfo = UserInfo.objects.get(user_id=request.user.id) userinfo.photo = img userinfo.save() return HttpResponse('1') else: return render(request, 'account/imagecrop.html') models.py photo = models.ImageField(blank=True, verbose_name='照片') In browser display about:blank.I am already type in url.But seems not work. Where is my problem? -
Routing with Django and React
El código del proyecto está aquí I'm very new to working with Django and I've been relying on some tutorials to link this one to React, but the problem is that initially (when I open 127.0.0.1:8000) React loads perfectly, then when I reload the page Django tries to interpret the path from urls.py and obviously can't find it. I hope you can help me, thanks in advance -
Not able to retrieve data from firebase in django
I've been trying to get data from Firebase into my Django app the issue i face is that some of the documents are retrieved and some aren't. A really weird thing I noticed is when on the admin page the documents that can be accessed are highlighted in a darker shade than the ones that we aren't able to get from the database. The highlighted issue is shown in the image above. The first document is highlighted but the second isn't and the first is read by the django function below def home(request, user=""): db = firestore.client() docs = db.collection(u'FIR_NCR').stream() for doc in docs: print(doc.id,end="->") s = db.collection(u'FIR_NCR').document(u'{}'.format(doc.id)).collection(u'all_data').get() print(s[0].id,end="->") print(s[0].to_dict()) return render(request, "home.html", {"user":user}) In this docs is not able to get the complete list of the documents necessary and hence the issue. It would be wonderful if someone could help me understand what I'm doing wrong. T.I.A. -
Django OperationalError “Lost connection to MySQL server at 'reading initial communication packet', system error: 0”
I'm on a mac connecting to a remote ubuntu server using ssh. MySQL is installed and running on the server, and my Django project is on it as well. I'm able to use mysql -u [username] -p to get into mysql, and I'm able to run the Django project on my local machine. When I run python manage.py runserver, this is my error traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/root/djangoenv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/root/djangoenv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/root/djangoenv/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/root/djangoenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in … -
django model for quiz application
Hi everybody i want to build a web application that creates Exams With several different types of questions And I want to know if the design of these models is good? please tell me what should i do these are my models :) and it is usefull to introduce me good Articles about Database design ''' from django.db import models from quizza import settings class Exam(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='exams') title = models.CharField(max_length=100) description = models.TextField(max_length=120, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() identyfier = models.CharField(max_length=20, unique=True) def __str__(self): return self.title class Question(models.Model): exam_id = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name='questions') QUESTION_TYPE = ( ('T', 'Test'), ('D', 'Descriptive'), ('S', 'Short Answer'), ('Two', 'Two choices') ) type = models.CharField(max_length=3, choices=QUESTION_TYPE) question = models.TextField(max_length=512) def __str__(self): return f"{self.question[0:10]} -- {self.type} -- {self.exam_id}" class Student(models.Model): full_name = models.CharField(max_length=100, unique=True) class Test(models.Model): question = models.OneToOneField(Question, on_delete=models.CASCADE) choice_1 = models.CharField(max_length=100) choice_2 = models.CharField(max_length=100) choice_3 = models.CharField(max_length=100) choice_4 = models.CharField(max_length=100) correct_answer = models.CharField(max_length=100) point = models.PositiveSmallIntegerField() def __str__(self): return f"{self.choice_1[0:10]} - {self.choice_2[0:10]} - {self.choice_3[0:10]} - {self.choice_4[0:10]}" class Descriptive(models.Model): question = models.OneToOneField(Question, on_delete=models.CASCADE) content = models.TextField(max_length=512) point = models.PositiveSmallIntegerField() def __str__(self): return self.content[0:20] class Short_Answer(models.Model): question = models.OneToOneField(Question, on_delete=models.CASCADE) content = models.CharField(max_length=50) correct_answer = models.CharField(max_length=50) … -
IntegrityError at /adding-url-patterns-for-views null value in column "question_id" violates not-null constraint
I am trying to allow user to post answer and comments to a particular bloq question Q&A Here is my model class PostAnswer(models.Model): """ Model for answering questions""" question = models.ForeignKey( PostQuestion, on_delete=models.CASCADE, related_name='comments', ) text_content = models.TextField() user = models.ForeignKey( User, on_delete=models.CASCADE, ) approved_comment = models.BooleanField(default=False) created_on = models.DateTimeField('published', auto_now_add=True) class Meta: ordering = ['created_on'] def approve(self): self.approved_comment = True self.save() def __str__(self): return 'comment by {} on {}'.format(self.user, self.question) Here is my views.py on an app class Index(ListView): queryset = PostQuestion.objects.all() template_name = 'index.html' context_object_name = 'posts' paginate_by = 10 def detail(request, slug): post = get_object_or_404(PostQuestion, slug=slug) comments = post.comments.all() new_comment = None # comment posted if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = post new_comment.save() return HttpResponseRedirect(reverse('page:detail_view')) else: form = CommentForm() context = {'post': post, 'comments': comments, 'new_comment': new_comment, 'form': form} return render(request, 'detail.html', context) My App form: class CommentForm(forms.ModelForm): text_content = forms.CharField(widget=PagedownWidget()) class Meta: model = PostAnswer fields = ['text_content'] My urls.py view for the app from .views import detail, ask, Index from django.urls import path urlpatterns = [ # path('<slug:slug>/comment', add_comment_to_post, name='add_comment_to_post'), path('ask/', ask, name='ask'), path('<slug:slug>', detail, name='detail_view'), path('', Index.as_view(), name='index'), ] Here is the html template for the … -
Limit number of rooms Django channels urls
I was looking for a way to limit the number of rooms avaliable on a Django channels chat app. I can't figure out how to code this, I wonder if I can do this directly on urls.py or maybe in views.py, during the routing. Here is my urls.py: path('app/<str:room_name>/', views.room, name='room'), and my views.py: @login_required(login_url='main:login') def room(request, room_name): return render(request, 'app/room.html', { 'room_name': room_name, }) I can't figure out the way of limit the number of rooms avaliable (only avaliable the rooms within a lis) so that a user would be redirected to app_main when tries to access a non avaliable room -
How to change the value of Boolean Field in Model from the views?
The application I've been working uses Class Based Views has two models, Question and Answer. The Question model has a FileField to store the actual solution to that question and the Answer model has a FileField named result to store the solution given by the user ( as solved by the user ). a Boolean Field named iscorrect in the Answer model which is set to False by default. I want to check if the two files are identical ( the solution in the Question model and the result in the Answer model ) and, toggle the BooleanField iscorrect ( as mentioned above, this Boolean Field is present in the Answer model ). What does my question boil down to? Assuming that I have figured out how to check whether two files are identical ( using a comparator method in the views.py and then requesting Question model's file for the particular id, then checking if they are identical. To be fair, I haven't implemented that yet so help with that would be appreciated as well ), I want to know how to toggle the BooleanField from the views.py based on what my comparator method returns ( True or False ). … -
how to send default data in all flask templates files?
i am new in flask python.i am making woocommerce site with python flask. my current flask structure is following pycache (where all blue prints) static (where all css and js) templates -siteparts header.html, footer.html, head.html, sidebar.html -dashboard -dashboard.html -layoyt.html -other template folders venv main.py dashboard_blueprint.py product_blueprinit.py other moduls blueprints now , my question is.i want to display cart items count in header.html.it can be displayed by using {{count}} syntex. my main(route) python file is main.py . all blueprints i have registered in main.py. now from dashboard_blueprint i am passing the variable "count" for cart count. dashboard_blueprinit is rendering only dashboard.html. header.html file is comman file for all templates file. but suppose i am calling product_blueprinit so again i have to pass variable "count". thats might be long process to pass default variable from all blueprints.is there any way to pass this variable commanly from all blueprints? any help will be appreciated. -
Django - How to exclude instances in queryset due to foreign key model relation
I am trying to filter out the instances in Quotation model if there are any item instances that are not within a certain list of items. The certain list of items are retrieved from the ProjectItem model. The model structure is below, I will explain more after the code. models.py class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) class ProjectItem(models.Model): project_item_id = models.AutoField(primary_key=True) project = models.ForeignKey('SalesProject', related_name='items', on_delete=models.CASCADE) item = models.ForeignKey('Item', on_delete=models.CASCADE) remarks = models.TextField(max_length=1000) class Quotation(models.Model): quotation_id = models.AutoField(primary_key=True) salesProject = models.ForeignKey( 'SalesProject', related_name='quotations', on_delete=models.CASCADE, null=True, blank=True) details = models.TextField(max_length=1000, blank=True, null=True) class QuotationItem(models.Model): quotation_item_id = models.AutoField(primary_key=True) item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True, blank=True) quotation = models.ForeignKey('Quotation', on_delete=models.CASCADE, related_name='items', null=True, blank=True) remarks = models.TextField(max_length=1000) class Item(models.Model): item_id = models.AutoField(primary_key=True) item_code = models.CharField(max_length=500, null=True, blank=True) item_description = models.TextField(max_length=1000, null=True, blank=True) Firstly, I will get a list of Item instances by querying the current SalesProject. (where project = a SalesProject instance) items = ProjectItem.objects.filter(project=project).values_list('item', flat=True) Basically the Item instances that are within this items list are the 'permitted items' of sorts. What I would want to return is all the Quotation instances that contains only Item instances within this list (or to exclude any Quotation instances with Item instances outside of this … -
Confounding Django NoReverseMatch error on django-tables2 links
I am using django_tables2 to render a table with hyperlinks -- and thus far, I am losing. I will show a bit of code and state the issues I am having at the end of this post. models.py class Developer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) ... class Tool(models.Model): """Model representing a tool (but not a specific copy of a tool).""" tool_name = models.CharField(verbose_name='Package Name', max_length=200) release_date = models.DateField(verbose_name='Release Date', null=True, blank=False) github_repo = models.URLField('GitHub', max_length=300, default='', blank=True) developer = models.ManyToManyField(Developer, help_text='Select developer(s)') summary = models.TextField(max_length=1000, help_text='Enter a brief description of the tool') category = models.ManyToManyField(Category, help_text='Select package category(ies)') class Meta: ordering = ['tool_name', '-release_date'] #ordering = ['tool_name', Developer, '-release_date', Category] def __str__(self): """String for representing the Model object.""" return f'{self.tool_name}' def save(self, *args, **kwargs): self.tool_name = self.tool_name.lower().title() return super(Tool, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('tool-detail', args=[str(self.id)]) def display_developers(self): return ', '.join(developer.last_name for developer in self.developer.all()) #[:3]) tables.py class ToolTable(tables.Table): tool_name = tables.LinkColumn() #tool_name = tables.Column(linkify=True) developer = tables.LinkColumn() #developer = tables.LinkColumn('developer-detail', args=[A('developer_id')]) #page does not render (tool_list.html) #tool_name = tables.LinkColumn('tool-detail', args=[A('tool_name.id')]) #Reverse for 'developer-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['packages/developer/(?P<pk>[0-9]+)$'] #tool_name = tables.LinkColumn('tool-detail', args=[A('pk')]) #Failed lookup for key [tool_name_id] in <class 'packages.models.Tool'>, when resolving the accessor … -
Django REST Viewsets - Cannot delete with custom queryset
I'm using Django REST and I have a question about viewsets. I can't seem to create a viewset (with a custom query) where deleting a record is still possible. So I use another viewset which is exactly the same, but without the custom query to delete records. This way it works, but I'm still wondering if there's a way to combine it into one as this seems like a hack. List my employees, DELETE doesn't work with this viewset. 404 Not found error. class MyEmployeeViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer def get_queryset(self): return CustomUser.objects.filter(employer=self.request.user.pk) So I use this viewset to ADD/DELETE. class EmployeeViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer def perform_create(self, serializer): serializer.save(employer=self.request.user) -
How to display django-treebeard MP in template as dropdown menu?
Following the treebeard docs api example, I created an annotated_list of my tree using get_annotated_list(parent=None, max_depth=None) with parent=<my root node>. I pass this to my template and using the example they attribute in the docs to Alexey Kinyov, I am able to successfully display my tree using {% for item, info in annotated_list %} {% if info.open %} <ul><li> {% else %} </li><li> {% endif %} {{ item }} {% for close in info.close %} </li></ul> {% endfor %} {% endfor %} What I would like though is to be able to give these nested lists dropdown features. Borrowing from this standard example on w3schools, I modified it to work with my annotated_list template variable and ended up with this: <ul id="myUL"> <li><span class="caret">{{ annotated_list.0.0 }}</span> {% for item, info in annotated_list|slice:"1:" %} {% if info.open %} <ul class="nested"><li> {% else %} </li><li>{% if item.get_children_count > 0 %}<span class="caret"> {% endif %} {% endif %} {{ item }} {% if item.get_children_count > 0 %}</span> {% endif %} {% for close in info.close %} </li></ul> {% endfor %} {% endfor %} </li> </ul> My code almost works, but does not seem to display node children for left-most nodes and I can't … -
Where/How to store and check specific user permissions?
Permissions may be the incorrect word to use, but I can't think of a better word at the moment. I have a standard User, Group, Permission schema that use to grant/revoke CRUD permissions to my users. I have an API that serves filtered data from a model Data based on a user's query. I want to have the ability to limit how many objects get returned when a user sends a query. My question is I'm not sure where/how to best store this information. The basic solution I have is add a max_rows column to my Group and reference that every request It's simple and easy to manage, but since users can have multiple groups I'd have to make sure that max_rows is in sync with the other groups that user belongs to. Any thoughts to improve this?