Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use DeleteView to delete an object, got "'mysite' is not a registered namespace"
I followed this example to upload document to AWS (https://github.com/sibtc/simple-s3-setup/tree/master/s3-example-static-and-media). I am now adding a functionality which allows user to delete an uploaded document. I got the error "django.urls.exceptions.NoReverseMatch: 'mysite' is not a registered namespace". Followed is the parameter values in /home/ubuntu/.local/lib/python3.6/site-packages/django/urls/base.py: args [1]; current_app ''; current_ns None; current_path None; kwargs {}; ns 'mysite'; ns_converters {}; ns_pattern ''; parts ['delete', 'mysite']; path []; prefix '/'; resolved_path []; resolver ; urlconf 'mysite.urls'; view 'delete'; viewname 'mysite:delete' Here are the files I made changes: (1) mysite/core/views.py class DocumentCreateView(CreateView): model = Document fields = ['upload', ] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) documents = Document.objects.all() context['documents'] = documents return context (below was added by me.I may need to add some code here to make the deletion work) class DocumentDeleteView(DeleteView): model = Document fields = ['upload', ] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) documents = Document.objects.all() context['documents'] = documents return context (2) mysite/urls.py app_name = 'mysite' urlpatterns = [ url(r'^$', views.DocumentCreateView.as_view(), name='home'), *(below was added by me)* path('<int:pk>/delete/', views.DocumentDeleteView.as_view(), name='delete'), ] (3) mysite/core/templates/core/document_form.html: I also added the following code to line 27 of https://github.com/sibtc/simple-s3-setup/blob/master/s3-example-static-and-media/mysite/core/templates/core/document_form.html <td><a href="{% url 'mysite:delete' document.id %}">Delete</a></td> (If I change 'mysite:delete' to 'delete', I got β¦ -
Django - How to do a prefetch_related? Am I doing it wrong?
I have these four models/tables: class Category(models.Model): image = models.ImageField(upload_to="images/") position = models.IntegerField() class CategoryTranslation(models.Model): name = models.CharField(max_length=32) language = models.CharField(max_length=2) category = models.ForeignKey(Category, related_name="translated_category", on_delete=models.CASCADE) class Quote(models.Model): num_views = models.IntegerField() category = models.ForeignKey(Category, related_name="quote_category", on_delete=models.CASCADE) class QuoteTranslation(models.Model): quote_text = models.TextField(max_length=512) language = models.CharField(max_length=2) quote = models.ForeignKey(Quote, related_name="translated_quote", on_delete=models.CASCADE) I want to prefetch all of the related data, I came up with this: t_quote = QuoteTranslation.objects.filter( language='en' ).prefetch_related( 'quote__category__translated_category' ).first() With this I can get: >>> t_quote.quote_text >>> t_quote.quote.num_views >>> t_quote.quote.category.image without any additional query, but I get None when I try to get the category name: >>> t_quote.quote.category.translated_category.name and to get what I want (the category name) I still need to do this: >>> t_quote.quote.category.translated_category.get( category=t_quote.quote.category.id, language='en').name Am I doing prefetch_related wrong? I couldn't figure out how to do it with Prefetch either. Please help. -
Django Rest Framework get_field is not being called
I've got an existing Django code base which uses Django Rest Framework to expose the data. I had one field which was defined as a SerializerMethodField() in the Serializer: categories = serializers.SerializerMethodField() And in the same serializer this get_method is defined: def get_categories(self, obj): return [obj.categories.choices[key.upper()] for key in obj.categories] That worked, but I had to add a way to also let users post new data to the api. Since the SerializerMethodField is read-only by definition I changed the field to a CharField (because it's a varchar in the DB): categories = serializers.CharField(required=True, allow_blank=False, max_length=100) That works for posting new content, but unfortunately, the get_categories() is not being called anymore. Does anybody know how I can make it call the get_categories() method while keeping the CharField? -
Django Show Unique List Of Subjects (Many To Many) In Dropdown Menu
I want to be able to produce a dropdown menu in my template with a unique list of subjects. Subjects are populated inside of admin rather than hard coding them in SUBJECT_CHOICES. A course can have many subjects or only 1 subject. For example: Course Title = Django Subject = Technology Course Title = Python Subject = Technology Course Title = Accounting Subject = Business Course Title = E-commerce Subject(s) = Technology, Business CourseListView corresponds to the course_list.html template. Models and views: https://dpaste.de/s8jq Desired Output: https://imgur.com/a/l0FWJoN I tried writing a for loop in my template that does return the subjects successfully but they are not unique or showing only once. https://dpaste.de/NHdF I would prefer to do it with a for loop that produces unique results, but maybe it can be done with django-select2 or use a form with model select or multiple model select? Can someone provide some code for either the loop or one of these methods? I would appreciate any help with this. -
NameError: name doohickey is not defined
This doesn't make sense... The error message: something = doohickey() NameError: name 'doohickey' is not defined get_random_tweet.py import twitter api = twitter.Api(consumer_key='i43eOLgYs6u6CCNQ93TxqqUR4', consumer_secret='18l0emYejR9rTWVd8ri1b0WtqC2qSj74yHqN0iyc$ access_token_key='1126243617482231808-q997kDrZf7gmGLhfKwB$ access_token_secret='oHdW4EaAg7ZS0hloJnvRpaz1CZmnimlJrKYd$ timeline = api.GetUserTimeline(screen_name='realDonaldTrump', include_rts=False, trim_user=True, exclude_replies=True, count=6) def doohickey(): pprint(timeline) return {'index': "<i> something </i>"} My views.py from django.shortcuts import render from django.http import HttpResponse from hello.sampled_stream import okdood import hello.get_random_tweet from .models import Greeting # Create your views here. def index(request): # return HttpResponse('Hello from Python!') # okdood() something = doohickey() return render(request, "index.html") Now I need to fill up space with something.... -
Best stack for uploading and processing several pdf files on a website?
I'm making a website where users can upload several pdf files (normally 10 MB in total, but can it can go up to 80-100 MB) and extract certain parts of those files in an Excel sheet. It involves heavy use of functions on each page, as there are a lot data to retrieve. I've already coded it in python as a script, but I want to make it as a website. Noob question: What stack should I use? Is it better using server-side or client-side? I know pdf.js can retrieve some information, but I'm not sure it would be the most appropriate for this. I was thinking about flask or django as it's already in python. What would be the best option for speed? User would use the browser, not the smartphone for this app. -
Django documenation page
I'm busy making a documentation page in my Django project and would like to make a dynamic page where theres a sidenav with links but if you click on a nav item it loads the page within the "master page aka the documentation page" without leaving that page like so https://www.nbinteract.com/tutorial/tutorial_github_setup.html I have created the side nav etc and it's working fine and linked my first URL to a nav item but if you click on the nav item, it opens that .html file instead of loading it within the main documentation page. I would like to find a way to do it with Django only and not JavaScript if possible, any guidance would be appreciated. Yes, this could be a silly question but please don't flame me about learning how to do stuff :) -
Django Rest Framework - GenericViewSet with Authentication/Permission decorator
Currently i have a simple rest setup for a single entity, you can create an object and you can retrieve it by the id. "POST" requires authentication/permission, "RETRIEVE" requires no authentication/permission. settings.py (requires global authentication/permission from every resource): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'api.authentication.token_authentication.TokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ] } In my resource the global authentication/permission settings are applied correctly but i want to generate an exception for the retrieve method: my-resource.py: from django.utils.translation import gettext_lazy as _ from rest_framework import mixins, serializers, viewsets from rest_framework.decorators import authentication_classes, permission_classes from api.models import Entity class EntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = [...] read_only_fields = [...] class EntityViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Entity.objects.all() serializer_class = EntitySerializer @permission_classes([]) # this is ignored ? @authentication_classes([]) # this is ignored too ? def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) Result: "POST" works as expected "RETRIEVE" return 403 ??? Why does the retrieve method still require authentication and returns 403? Is there any easier way to accomplish this? Greetings and thanks! -
Django-ckeditor upload permission for all users and scroll bar
1) I am using Django-CKEditor and when I am trying to upload any file or image in it then it is showing Alert error: "Incorrect Server Response", And when I checked in the terminal, there it is showing "GET /admin/login/?next=/ckeditor/upload/ HTTP/1.1" I don't know what to do to make this work! Please help me here... 2) when I am copy-pasting 100 lines of text in the editor it increases its height rather providing any scroll bar in it, here is the config code I am using: CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'height': '200', 'width': 1250, 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Table', 'SpecialChar']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize']}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' β¦ -
Django form : Setting the user to logged in user
I am trying to create an address book website where logged in user is able to fill in a form and store contact information. I was able to implement the login and logout functionality. But the problem is that I am not able to set the username to current logged in user. Here is what I have implemented so far: Models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) #additional def __str__(self): return self.user.usernname class UserContacts(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length = 150) last_name = models.CharField(max_length = 150) phone_number = models.CharField(max_length = 150) email_address = models.CharField(max_length = 150) street_address = models.CharField(max_length = 350) def __str__(self): return '{}'.format(self.first_name) Forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserContactForm(forms.ModelForm): class Meta(): model = UserContacts fields = "__all__" views.py: @login_required def new_contact(request): form = UserContactForm() current_user = request.user.get_username() user = User.objects.filter(username=current_user).first() output = UserContacts.objects.filter(current_user_id=user.id).first() if request.method == "POST": form = UserContactForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print('Error Form Invalid') return render(request,'basic_app/contact.html',{'form':form}) Here is how the output looks like when the logged in user tries to enter contact information details: Updating contact screenshot. As you can see the current user has to select his username to fill β¦ -
df.to_html() method is displaying the actual html on the webpage and not the representation it should (Django website)
I'm currently making a django website for a Software Engineering class. I'm having a problem with displaying a pandas dataframe using the .to_html() method. The webpage template is rendering the actual html code on the UI instead of the representation of the html code. I don't understand why and have looked for similar problems on the internet. I think I can't find a similar problem because I don't know the right words to use in the search engine to get the answer I want. The webapp template (called graphs.html) is displaying the actual code itself. Here is a code fragment: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>itemId</th> <th>title</th> <th>endPrice</th> <th>location</th> <th>endTime</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>283584749546</td> <td>1979 80 TOPPS #18 WAYNE GRETZKY ROOKIE CARD PSA 6 EX-MINT</td> <td>500.0</td> <td>Canada</td> <td>2019-11-17T08:08:30.000Z</td> </tr> <tr> <th>1</th> <td>163940352354</td> <td>1979 Topps Hockey Unopened Wax Pack Gretzky PSA ?</td> <td>103.5</td> <td>Rice Lake,WI,USA</td> <td>2019-11-16T16:27:42.000Z</td> </tr> <tr> <th>2</th> <td>293329130191</td> <td>1979/80 Topps Wayne Gretzky Rookie #18 High End PSA 6 RC Priced to Sell</td> <td>345.0</td> <td>Liberty Lake,WA,USA</td> <td>2019-11-15T22:04:27.000Z</td> </tr> <tr> As you can see, the UI is displaying html tags when it shouldn't. Below, the html is displaying without the tags showing, and would look like β¦ -
django Arabic Hijri calendar
I use Django 2.2 When I have a field that has DateTimeField type, Django automatically uses Django calendar. But in Saudi Arabia we use Islamic Hijri Calendar. How can I define a field with Hijri calendar? -
Can't Login into Django Admin
What I know about AbstractUser and AbstractBaseUser is that AbstractBaseUser allow you to start from scratch but AbstractUser is to work with existng fields in USER. Similarly I created model using AbstractBaseUser and changed name of some fields like is_admin and is_staff but when I tried to login in Django Admin it doesn't allows. I figure out the problem and change name back to default and it worked. So if I wan't to login in to django admin what should I do. -
Adding a Custom DateTimePicker in a Django form
I'm quite new to Django, so I decided to build a simple app to test my skills. On one of the model forms, I have a DateTimeField, but that only defaults to a TextField. I would like to create a custom datetime picker with bootstrap, but I didn't know how to implement it. I followed a tutorial for Tempus Dominus Bootstrap 4 here. I have everything they say, but when I navigate to my form, it displays an error: 'BootstrapDateTimePickerInput' object has no attribute 'is_hidden'. Models.py from django.db import models class ToDoItem(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() remind_time = models.DateTimeField() Widgets.py from django.forms import DateTimeField class BootstrapDateTimePickerInput(DateTimeField): template_name = 'main/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context forms.py from django import forms from .widgets import BootstrapDateTimePickerInput from .models import ToDoItem class NewEventForm(forms.ModelForm): start_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) end_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) remind_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] views.py from django.shortcuts β¦ -
Query through intermediate models that returns multiple results, using Django Q object
How to follow an intermediate 'through' model, in a Q object? I'm trying to get a list of the ids of all Property objects that a User is a member of, in one query. A User is a member of a BusinessUnit through BusinessUnitMember. How do I make a filter with a Q object that finds all (multiple) BusinessUnitMembers for a particular User, and then finds all (multiple) BusinessUnits for those BusinessUnitMembers? class Property(BaseModel): """Physical Things belonging to various Business Units""" category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) objects = PropertyQuerySet.as_manager() @property def asset(self): asset_maps = { 'typea': 'type_a_asset', 'typeb': 'type_b_asset', } if self.category not in asset_maps: return None return getattr(self, asset_maps.get(self.category), None) class AssetBase(models.Model): """Abstract Base Asset model.""" business_unit = models.ForeignKey('BusinessUnit', null=True, on_delete=models.SET_NULL) class TypeAAsset(AssetBase): """Type A Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_a_asset') class TypeBAsset(AssetBase): """Type B Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_b_asset') class BusinessUnit(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey('core.User', null=True, on_delete=models.SET_NULL, related_name='owned_business_units') class BusinessUnitMember(models.Model): """ ``through`` model for BU and members. """ business_unit = models.ForeignKey('BusinessUnit', on_delete=models.CASCADE) member = models.ForeignKey('core.User', on_delete=models.CASCADE) I need to find the ids of all Property objects that the current User is a member of. I'm thinking of a filter like: available_ids = Property.objects.filter(Q(type_a_asset__business_unit__in=user.businessunitmember.all().businessunit_set.all())).values_list('id', flat=True) β¦ -
django-select2: Select Field doesn't open when tabbed
In my simple Django App, I've implemented django-select2. I have a form with 2 fields: product and category. When I create a new product I first give it a title and than tab to the category-field, but the dropdown does not open automatically. Only when I press Space-Bar or Enter the dropdown opens. What can I do so that the dropdown opens automatically, when it is reached? Here my code: forms.py from django import forms from django_select2.forms import Select2Widget, ModelSelect2Widget, Select2MultipleWidget from .models import Product, Category class MyForm(forms.ModelForm): category = ModelSelect2Widget(queryset=Category.objects.all()) class Meta: model = Product fields = ['name', 'category'] widgets = { 'category': Select2Widget, } models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name product.html {% extends 'base.html' %} {% block content %} {{ form.media.css }} <br> <form action="" method="POST"> {% csrf_token %} {{ form}} <button type="submit">Save</button> </form> {{ form.media.js }} {% endblock content %} -
How can make django find a specific css file forSphinx?
I am using Sphinx to document my django application. My directory tree, based on this django tutorial is: . βββ db.sqlite3 βββ help β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ templates β β βββ help β β βββ _images β β βββ index.html β β βββ _modules β β βββ objects.inv β β βββ _sources β β β βββ index.rst.txt β β βββ _static β β βββ css β β β βββ badge_only.css β β β βββ theme.css β β βββ fonts β β βββ js β β βββ modernizr.min.js β β βββ theme.js β βββ tests.py β βββ urls.py β βββ views.py βββ manage.py βββ mysite β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ polls β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ 0001_initial.py β β βββ __init__.py β βββ models.py β βββ tests.py β βββ urls.py β βββ views.py βββ users βββ admin.py βββ apps.py βββ __init__.py βββ migrations β βββ __init__.py βββ models.py βββ tests.py βββ urls.py βββ views. The code to set the css file in the html is: <link β¦ -
Mocking a Django model specific instance function
I have a test that has two django model instances. I want to mock two functions in a django model instance - only for one of the instances. I want the other instance to not have mocks. This is my code: The model: class MyModel(models.Model): id = models.AutoField(primary_key=True) def __init__(self, *kargs, **kwargs): super(self.__class__, self).__init__(*kargs, **kwargs) @property def count(self): logic.... return count def get_data(self, parameter=None): logic..... return data The test: def test(self): data_dict = {....} my_model = MyModel(**data_dict) my_model.save() data_dict2 = {....} data_dict2['parent'] = my_model my_model2 = MyModel(**data_dict) my_model2.save() with patch.object(my_model2, 'count', lambda x: 20), \ patch.object(my_model2, 'get_data', lambda x: {[{'Id': str(i)} for i in range(20)]}): self.assertEqual(my_model2.count, 3) # This will also call my_model.get_data and my_model.count - of the instance I am trying to mock These mocks don't work - I get this error: Error Traceback (most recent call last): File "x.py", line x, in test with patch.object(my_model2, 'count', lambda x: 20), \ File "x/mock/mock.py", line 1485, in __enter__ setattr(self.target, self.attribute, new_attr) AttributeError: can't set attribute How can I mock a django model instance functions? Thanks -
How to gert id from foreign key model in django
How Do I get id of to_user from the below model: class Friend(models.Model): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs, ): friend = self.create(from_user_id=request.user.id, status="Pending") return friend class Meta: unique_together = (('from_user', 'to_user'),) def __str__(self): return self.to_user.email my view : def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" Friend.status = "pending" try: uid = urlsafe_base64_decode(uidb64) friend_user = User.objects.filter(id=Friend.to_user.id) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() f.status = "accepted" return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except AttributeError: return render(request, 'blog/base.html') I cannot retrieve the friend_user = User.objects.filter(id=Friend.to_user.id) Thanking you in advance, -
Deploy angular 8 and django rest framework
I have successfully deployed django rest framework backend and angular 8 frontend apps independently on Heroku. I'm clueless whether they should be deployed as separate apps or should be integrated on single instance. What is the best practice when it comes to DRF and SPA,particularly angular? If to be deployed as independent app,how can I configure DRF backend to respond to the frontend in another server. Any help would be appreciated. Thanks -
Django database keeps vanishing on Heroku
I have a Django project that is live on Heroku. I'm trying to create a superuser on remote, but I get: django.db.utils.OperationalError: no such table: auth_user So I run heroku run python manage.py migrate and get the expected response. Running python manage.py migrate on β¬’ MyWebsite... up, run.5296 (Free) Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK ... But when I run heroku run python manage.py createsuperuse, I get the same old django.db.utils.OperationalError: no such table: auth_user No matter how many times I run migrate, the table just seems to vanish right after. Any ideas on whats going on? Thanks! -
show in a table html template the result of a SQL query using DJANGO
I have DDBB with a specifict table that is the result of a store procedure calculation. I would like to show this SQL table in a table in html using a DJANGO Template. I have tried in many differents ways but the nearest I got was show only one register. views.py cursor.execute("SELECT NIVEL, COMP, PONDERACION FROM COMP ORDER BY NIVEL ") COMP = cursor.fetchall()[0] index.html: <table> <tr> <th>NIVEL</th> <th>COMPONENTE</th> <th>PONDERACION</th> </tr> {% for row0 in COMP %} <td>{{ row0 }}</td> {% endfor %} </tr> </table> I know that a query es a tuppla but i dont know how to transform a tuppla with many registers in a table just like the result of a sql query... thanks you very much... -
Filling ManyToMany field of a form in class based view - Django
I am trying to create a ManyToMany relationship between Project and User model. I created a users_list field for Project model to hold the list of users that can access a specific project. While creating a project in, I fill the field user, successfully, with the current logged in user. For the users_list field, initially, I try to add the current logged in user to the users_list (other uses shall be added later when invited). However, I cannot. I get the following error: ValueError: invalid literal for int() with base 10: '' models.py class Project(models.Model): title = models.CharField(max_length=1000) user = models.ForeignKey(settings.AUTH_USER_MODEL, default="", on_delete=models.CASCADE) users_list = models.ManyToManyField(User, related_name='users_list') def __str__(self): return self.title + " - " + str(self.user) def get_absolute_url(self): return reverse("planner:projects_listed") views.py class ProjectCreateView(CreateView): model = Project fields = ["title"] template_name = "planner/projects_listed.html" def get_success_url(self): return reverse("planner:projects_listed") def get_context_data(self, **kwargs): kwargs["project_list"] = self.model.objects.filter(user=self.request.user) return super(ProjectCreateView, self).get_context_data(**kwargs) def form_valid(self, form): form.instance.users_list.add(self.request.user) form.instance.user = self.request.user return super(ProjectCreateView, self).form_valid(form) -
get_form in ModelAdmin causing TypeError
This question refers to the issue I was having here which has not been solved. I have created a new simplified version of the MemoForm called AdminMemoForm to help me isolate the issue. After creating the new version of the form I have come to find that the get_form method is what is causing the TypeError: MemoForm object not callable. Here is a snippet of the new code that is throwing the error: Forms.py: class AdminMemoForm(forms.ModelForm): """ Memo creation form, related to: :model: 'memos.Memo', """ class Meta: model = Memo fields = ( 'title', 'content', 'important', 'word_file', 'receiver', 'read', 'unread', ) Admin.py: class CustomMemoAdmin(admin.ModelAdmin): form = AdminMemoForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # if not request.user.is_superuser: # self.fields = ( # 'title', # 'content', # 'important', # 'receiver', # 'read', # 'unread', # 'word_file', # ) # self.filter_horizontal = ('casino',) return form() This is probably simple but I don't get why this error is arising. Any help would be appreciated. -
Add custom url action parameter to django-cms
The common url action parameters in django-cms are for example: ?edit to enter Edit-mode, ?toolbar_off to disable/hide the toolbar. Now I'd like to add a new action parameter e.g. ?logout which just logs out the user no matter on which url he/she currently is. I'd tried to include this in the urls.py with the following pattern: url(r'^.*\?logout$', RedirectView.as_view(url='/admin/logout/')), I read in another SO answer that you shouldn't catch URL Params with an url pattern... Should I do this in a kind of middleware? Or where else?