Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: Django model form data not being saved in the database
I'm trying to create a blog model but the form data is not being saved in the database after submitting the form. views.py def postsform(request): if request.method == "POST": form = BlogForm(request.POST) if form.is_valid(): form.save() return redirect('blog') else: form = BlogForm() messages.warning(request, "Opps! Something went wrong.") return render(request, 'blog/postform.html', {'form':form}) else: form = BlogForm() return render(request, 'blog/postform.html', {'form':form}) forms.py from django_summernote.widgets import SummernoteWidget class BlogForm(ModelForm): class Meta: model = BlogPost widgets = { 'blog': SummernoteWidget(), } fields = ['title', 'featureImg', 'blog', 'meta_description', 'keyword', 'author'] models.py class BlogPost(models.Model): title = models.CharField(max_length=999) featureImg = ProcessedImageField(upload_to = 'blog/', format='JPEG',options={'quality':60}, null=True) slug = models.CharField(max_length=999, blank=True,null= True) blog = models.TextField() meta_description = models.TextField() keyword = models.TextField() author = models.CharField(max_length=255) created_on = models.DateField(auto_now_add=True) updated_on = models.DateField(auto_now=True) def save(self, *args, **kwargs): if BlogPost.objects.filter(title=self.title).exists(): extra = str(randint(1, 1000000)) self.slug = slugify(self.title) + "-" + extra else: self.slug = slugify(self.title) super(BlogPost, self).save(*args, **kwargs) html <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Publish</button> </form> I've tried finding where I made the mistake but couldn't find it. After submitting the form the warning message pops up and the form doesn't get submitted. -
Django: Forloop Counter 0 divisible by 3 not working properly
PLATFORM: Django Problem When using {% forloop.counter0|divisibleby:3 %} it doesn't seem to properly divide out? I can't quite tell what's going on. Goal Display an Avery HTML template with pre-populated info from the database. 3 column table with variable rows. Code <table> {% for job in jobsite %} {% if forloop.counter0|divisibleby:3 %}<tr>{% endif %} <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</td> {% if forloop.counter < 3 %} <td class="spacer" rowspan="0">&nbsp;</td> {% endif %} {% if forloop.counter0|divisibleby:3 or forloop.last %}<tr>{% endif %} {% endfor %} </table> Why is this failing? Additional Info I can get close if I change the code around to the following. The problem then becomes that counter 2 is blank. If I fill in data, it's duplicated (row 1 column 2, row 1 column 3): <table> <tr> {% for job in jobsite %} {% if forloop.counter|divisibleby:3 %}</tr><tr>{% endif %} <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</td> {% if forloop.counter < 3 %} <td class="spacer" rowspan="0">&nbsp;</td> {% endif %} {% if forloop.counter == 2 %} <td></td> {# <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ … -
How to count the number of specific objects in a Django model?
I have a Django model called User and would like to count how many items are within the following object. class User(AbstractUser): following = models.ManyToManyField("self", related_name="followers") I have tried counting them using this line followers_num = User.following.count(), but I receive this error 'ManyToManyDescriptor' object has no attribute 'count'. I have also tried followers_num = User.objects.all().count(), but that returns the number of users. Does anyone know how to do this? -
How would I use write a test case to login using the email
In the functions test_login and test_get_add_page I would like to login using the email,pw and then for one to redirect to the add page and check if it's using the right template. Running the following gives me: Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\instawork\Internship\tests.py", line 89, in test_login user_login = self.client.post(self.login_url, {'email': self.user.email, 'password': self.user.password}) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 852, in post response = super().post( File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 44 return self.generic( File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 541, in generic return self.request(**r) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 810, in request self.check_exception(response) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 663, in check_exception raise exc_value File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\instawork\Internship\views.py", line 21, in login username = request.POST['username'] File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'username' I am trying to use email instead of the username for my default login. from django.test import TestCase, Client from django.urls import reverse from .models import Profile, Team from .forms import ProfileForm # Create your tests here. class Instawork(TestCase): #fields are first_name, last_name, … -
How to use media files on heroku?
There is a way to use media files on heroku? if yes, how I have to set MEDIA_URL and MEDIA_ROOT? -
How would I get sum from all rows, but only output one row? Django and Postgresql
currently the way I have the code written is that I have a model named Finances. I have an aggregate set up so it sums up all of the rows. I am trying to display the outcome of the rows, but when I do it displays a row for every database entry. I understand that I am grabbing all with .all() in the viewpayout = Finances.objects.all() in views.py, but I am unsure of how this should be written to only display one row. How would I display only one row that sums up all of the rows for a column? Any help is greatly appreciated! Below is my code: views.py def finances(request): viewpayout = Finances.objects.all() updatepayout = UpdatePayout() updatewithdraw = UpdateWithdraw() updatecash = UpdateCash() if request.method == "POST": if 'add_payout' in request.POST: updatepayout = UpdatePayout(request.POST) if updatepayout.is_valid(): post = updatepayout.save(commit=False) post.save() return redirect("/finances") else: updatepayout = None if 'bank_withdraw' in request.POST: updatewithdraw = UpdateWithdraw(request.POST) if updatewithdraw.is_valid(): post = updatewithdraw.save(commit=False) post.save() return redirect("/finances") else: updatewithdraw = None if 'add_cash' in request.POST: updatecash = UpdateCash(request.POST) if updatecash.is_valid(): post = updatecash.save(commit=False) post.save() return redirect("/finances") else: updatecash = None return render(request, 'portal/finances.html', {"updatepayout": updatepayout, "updatewithdraw": updatewithdraw, "updatecash": updatecash, "viewpayout": viewpayout}) model.py: class Finances(models.Model): payout … -
CustomUser in Django with failed migration
I did migration in Django for my database. My models.py file looks like this from django.contrib.auth.models import AbstractUser from django.db import models from tkinter import CASCADE from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class CustomUser(AbstractUser): user_type_data = ((1,"Manager"),(2,"Employee")) user_type = models.CharField(default = 'test', choices = user_type_data, max_length=20) class Manager(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length = 100,default='test') email = models.CharField(max_length = 100,default='test') password = models.CharField(max_length = 100,default='test') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) objects = models.Manager() class Tasks(models.Model): id = models.AutoField(primary_key=True) headline = models.CharField(max_length = 100) body = models.CharField(max_length = 10000) created_at = models.DateTimeField(auto_now_add = True) assigned_at = models.DateTimeField(auto_now_add = True) closed_at = models.DateTimeField(auto_now_add = True) manager_id = models.ForeignKey(Manager, on_delete=models.CASCADE) objects = models.Manager() class Employee(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length = 100,default='test') email = models.CharField(max_length = 100,default='test') password = models.CharField(max_length = 100,default='test') objects = models.Manager() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) tasks_id = models.ForeignKey(Tasks, on_delete=models.CASCADE) daily_r = models.IntegerField(default = 0) weekly_r = models.IntegerField(default = 0) monthly_r = models.IntegerField(default = 0) annual_r = models.IntegerField(default = 0) Sometimes it says "Table does not exist", but after I change something … -
Conversion from Markdown to HTML in Django project
I'm on a project which include use of Python, Django, HTML and Markdown. I have to develop a site similar to wikipedia, in fact the project is called encyclopedia. My goal is to make visiting / wiki / TITLE, where TITLE is the title of an encyclopedia entry, to display a page that displays the content of that encyclopedia entry. The encyclopedia entries are CSS Django Git HTML Python (each entry has its own .md file). the problem I have is with the "markdown" library. In practice, I was able to convert the syntax from markdown to HTML but as output I only receive the tags in written format, without them applying their standard style to the content inside them. I am attaching the code I wrote for the conversion and a screenshot of the output I receive. from django.shortcuts import render import markdown from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): content = util.get_entry(title) if content == None: content = markdown.markdown(f'## {title.capitalize()}\'s page has not been found') content = markdown.markdown(content) return render(request, f"encyclopedia/entry.html", { 'title': title, 'content': content }) -
How Can I do PIN Activation, user registration and Authentication in Django
I am working on a Django project where users would have to activate PIN and then register for an event seat. I have done it in such a way that users activate PIN and they are prompted with registration form to secure a seat for an event. And I want to get the Event name, Price, Date, category from the Ticket table. Meanwhile I have a Guest Model that is saving username and pin using an update query during the registration process; using a forms field to request for PIN again (Don't want to repeat this process too). And I have used the pin field as a ForeignKey in the Guest Model so I am getting error that Cannot assign "'384513'": "Guest.pin" must be a "Pin" instance. What is the best way of doing this logic of PIN activation, registration and authenticating a user and getting the Models values associated with his PIN in this case. I was thinking of using the Guest Table to get the information relating to Events, Ticket and Pin Details but no way. See below Models code: class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PAYMENT, default=None, blank=False, null=False) added_date = … -
Explicitly defining fields on ModelSerializer overrides Model's parameters like verbose_name and validators
Imagine having a simple model like the one bellow: from utils.validators import name_validator class Customer(models.Model): name = models.CharField(verbose_name="Customer Name", validators=[name_validator]) email = models.EmailField(verbose_name="Customer Email") def __str__(self): return self.name Now if I explicitly define a filed on my serializer, both validators and verbose_name are lost. I can use label= and validatos= when defining the field on my serializer but I don't want to repeat myself. What if I have multiple serializer pointing to the same Model? class CustomerSerilizer(serializers.ModelSerializer): custom_field_name = serializers.CharField(source="username") class Meta: model = Customer fields = "__all__" Is there anyway to prevent this from happening? -
Wagtail - Override internal links in richtexteditor
Since I use wagtail headlessly the internal links get messed up due to them using the site-url listed in settings. Instead, I want to be able to override that same URL and point them to my frontend. This post talks a little bit about it in 2018, but I'm hoping this has changed? Wagtail: Is it possible to disable prepending internal link's with the site domain? For external links you'd do something like this to override it: class NewWindowExternalLinkHandler(LinkHandler): # This specifies to do this override for external links only. identifier = 'external' @classmethod def expand_db_attributes(cls, attrs): href = attrs["href"] print(attrs) # Let's add the target attr, and also rel="noopener" + noreferrer fallback. # See https://github.com/whatwg/html/issues/4078. return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href) Is it possible to do the same for internal links? E.g now since I use a multi-site setup my link looks something like: https://localhost.my-backend-api-domain.com/page/pagename I want it to look like this: https://my-frontend-domain.com/page/pagename -
Post only unique key value pairs to redis instance
I am POSTing a list of key values pairs to a redis_instance. I would like to first check if any of the keys/values I am posting to redis already exist to avoid having duplicate key value pairs or instances where a pre-existing key has a different value or a pre-existing value has a different key so for example avoiding scenarios like this: Fred: Luke Luke: Jim Jim: Jane and instead only allow these pairs to be written to my redis_instance: Fred: Luke Jim: Jane This is what I have: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): if request.method == 'GET': items = {} count = 0 for key in redis_instance.keys("*"): items[key.decode("utf-8")] = redis_instance.get(key) count += 1 response = { 'count': count, 'msg': f"Found {count} items.", 'items': items } return Response(response, status=200) elif request.method == 'POST': item = json.loads(request.body) keys = list(item.keys()) values = list(item.values()) for i in range(0, len(keys)): redis_instance.set(keys[i], values[i]) response = { 'msg': f"{keys} successfully set to {values}" } return Response(response, 201) not quite sure how to carry this out -
raise TypeError("%s() got an unexpected keyword argument '%s
I am trying to create super user in django==4.0.1 when add my information i get this error raise TypeError("%s() got an unexpected keyword argument '%s I trying this and get the same error File "C:\Users\ZAKARIA\Desktop\task\Users\models.py", line 39, in create_superuser user =self.create_user( File "C:\Users\ZAKARIA\Desktop\task\Users\models.py", line 24, in create_user user =self.model( File "C:\Users\ZAKARIA\Desktop\task\env\lib\site-packages\django\db\models\base.py", line 507, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: NewUser() got an unexpected keyword argument 'is_staff' can any one help my to solve this problem my model : from statistics import mode from time import timezone import django from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser ,BaseUserManager,PermissionsMixin class CustomAccountsManager(BaseUserManager): use_in_migrations: True def create_user(self ,email,username, first_name,last_name,password=None,**extra_fields): if not last_name: raise ValueError(_('User must a last name')) elif not first_name: raise ValueError(_('User must have a firstName')) elif not username: raise ValueError(_('User must have a username')) elif not email : raise ValueError(_('User must provide an email address')) user =self.model(email= self.normalize_email(email), username=username,first_name=first_name,last_name =last_name,**extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, email ,username,first_name,last_name,password=None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser' , True) extra_fields.setdefault('is_admin',True) user =self.create_user(email= self.normalize_email(email), username=username,first_name=first_name,last_name =last_name,password=password,**extra_fields) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is staff=True') if extra_fields.get('is_superuser') is not … -
Django whats the best model for this table
I am lookin for the best way to match the first column with the 2nd & 3rd columns? Foerign key and ManyToManyField didnt work. -
Django - Displaying content based on permissions in a class based view
I want to display an edit link on certain content if the user has permission to edit the content. I've done some research and it appears that the best way to do this is via the view. I saw some vague suggestion to use permissions to add the link via context. As a beginner, I am not sure how to go about this. Any suggestions? The view: class CompanyProjectsDetailView(UpdateView): queryset = Project.objects.get_with_counted_notes_documents_todos() template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm The model: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) -
How remove password from response in django
Code: SERILIZERS class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("email", "user_name", "password") def create(self, validated_data): return User.objects.create_user(**validated_data) VIEWS @api_view(["POST"]) @permission_classes([AllowAny]) def CreateUserView(request): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) MODELS class CustomAccountManager(BaseUserManager): def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_("You must provide an email address")) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user After i post user i got response data with password. { "email": "mawqgvxdfdat1@mat.com", "user_name": "sdwxcvgfsdefsdf", "password": "pbkdf2_sha256$320000$g74DLAMRDypcK6LuGriBio$ } How can i remove that password from returned data? -
Django queryset to CSV, string field with quotes
I have a feature where i translate a queryset to a CSV, and i have two string fields coming from a JSON, "media" and "brand", but when i export it to CSV i got the media result with quotes and the brand field without quotes. I want to remove that quotes without having to parse the CSV because of performance. This is the process i do: from django.db import connection from django.db.models.functions import Cast # Get queryset fields = { "Media:: Cast("event__media_name", output_field=CharField()), "Brand": Cast("event__brand_name", output_field=CharField()), } queryset = ( base_queryset.order_by("id") .annotate(**fields) .values(*fields.keys()) ) # Create CSV file filename = "filename.csv" path = f"reports/{filename}" folder = tempfile.mkdtemp() temp_path = os.path.join(folder, filename) # Copy values into CSV sql, params = queryset.query.sql_with_params() sql = f"COPY ({sql}) TO STDOUT WITH (FORMAT CSV, HEADER, DELIMITER ',')" with connection.cursor() as cur: sql = cur.mogrify(sql, params) cur.copy_expert(sql, file) -
Foreign Key Constraint is failed is showing while getting auth token using Token authentication provided by django rest framework
I have created a custom model using ABSTRACTBASE USER in django. Now i am trying to generate auth token and it is showing Foreign key constraint fail error. I a able to login and register the user to the custom model. My AUTH_USER_MODEL is set to the custom model i have created -
ModelForm customisation with image upload in django
i am new to django and in my project i have a form that lets the user update his/hers profile picture. The problem is that the way i wrote the code for that form the output in the browser is like this: But the thing is i don't want the first line (Profile pic:...) to show up. Is there any way i can do that?? The code: views.py def profile_view(request, profile_id): askedprofile = Profile.objects.get(pk=profile_id) profiles = Profile.objects.all() form = ProfileForm(request.POST, request.FILES, instance=askedprofile) if request.method == "POST": if form.is_valid(): image_path = askedprofile.profile_pic.path if os.path.exists(image_path): os.remove(image_path) form.save() return redirect('myprofile', profile_id=profile_id) context = { 'askedprofile': askedprofile, 'profiles': profiles, 'form': form, } return render(request, 'my_profile.html', context) models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) username = models.CharField(max_length=200, null=True) password = models.CharField(max_length=50, null=True) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/') forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name="home"), path('forum/', views.forum_view, name="forum"), path('forum_detail/<topic_id>', views.forum_detail_view, name="forumdetail"), path('login/', views.login_view, name="login"), path('signup/', views.signup_view, name="signup"), path('logout/', views.logout_view, name="logout"), path('forum-create/', views.forum_create, name="forumcreate"), path('answer-create/<topic_id>', views.answer_create, name="answercreate"), path('topic-delete/<topic_id>', views.delete_topic, name="deletetopic"), path('answer-delete/<answer_id>', views.delete_answer, name="deleteanswer"), path('my-profile/<profile_id>', views.profile_view, name="myprofile"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my_profile.html {% for profile in profiles %} {% if profile.user == request.user %} … -
Django how to pass arguments to a view with {% url %}
I have this url path: urlpatterns = [ path('f/<str:a>/<str:b>', views.f, name='f') And the view: def f(request, a, b): # some code The f view takes 2 paramters. Now if I have the code below in a template: <a href="{% url 'f' %}">click me</a> How can I pass values for parameters a and b? -
Django/PostgreSQL not displaying search result
I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I am not sure if I am not doing the search query right or I just cannot display the results. I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown. Any help would be greatly appreciated! models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost views.py @login_required(login_url="/login") def search(request): q = request.GET.get('q') if q: vector = SearchVector('product', 'description') query = SearchQuery(q) searchinv = Inventory.objects.annotate(search=vector).filter(search=query) else: searchinv = None return render(request, 'portal/search.html', {"searchinv": searchinv}) inventory_management.html (where … -
How to properly migrate a monolith architecture app to a microservice app in Django
Today I come with this question probably to someone who has large experience in this. Basically what the title indicates. We have that app and we have to migrate it to microservices. We didn't find any solid approach (or we felt it like that) about this. What we ended up doing is creating 1 project per microservice (a single functionality related to a module app, in general) but then we had some problems because we already had a database to work with since this is already a functioning app. We had problems communicating with the existing models, so basically what we did was to point in every settings.py of the projects to the existing DB, and with python3 manage.py inspectdb, we grabbed the existing models. This approach ended up working, but we feel that is not the best approach. We had a lot of problems with circular imports and more. Is out there good practices about microservices with Django, and how to properly do it, like in most of the cases that we want to create something with the framework? If someone knows or has something we would really appreciate it! -
SortableHiddenMixin AttributeError: module 'nested_admin' has no attribute 'SortableHiddenMixin'
Estoy buscando usar la opcion de arrastrar y soltar para ordenar elmentos de una lista en django. admin usando nested_admin 3.2.4. vi este issue en github LINK PERO NO FUNCIONA. return ModuleType.__getattribute__(self, name) AttributeError: module 'nested_admin' has no attribute 'SortableHiddenMixin' class ReportSectionFieldInline(nested_admin.SortableHiddenMixin, nested_admin.NestedTabularInline): model = ReportSectionField extra = 0 classes = ['collapse'] class ReportSectionInline(nested_admin.NestedTabularInline): model = ReportSection inlines = [ReportSectionFieldInline] extra = 0 classes = ['secciones-informe'] class Media: css = { "all": ("admin/css/reportsection.css",) } class ReportAdmin(nested_admin.NestedModelAdmin): list_display = ('id', 'description', 'type_report', 'modulo', 'active',) search_fields = ('description', 'type_report',) list_filter = ('type_report', 'active',) inlines = [ReportSectionInline] -
Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>
I have foreign key LOCATION in LOCATION table to get the Location value in another table, i got the error json_object is my input, item is another table Code=item["LOCATION"]=LOCATION.objects.get(LOCATION = json_object["LOCATION"]) error=Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>. -
Getting (NoReverseMatch at / Reverse for 'chatpage' with no arguments not found. 1 pattern(s) tried: ['ChatView/(?P<uname>[^/]+)\\Z'] after login
I know this question had been asked for more than five times but I had tried many solutions as a noob and still weren't able to find out the solution. I had been following the django-channels documentation and instead of room-name I want to display username in the URL but when I try as per instructions this error occurred. This is the image of error. Image of error when I run it on Mozilla firefox and this is what it is saying in terminal Image of error in terminal and this is the line of chatpage urls.py line which is I am trying to display with username path('ChatView/<str:uname>', login_required(views.ChatView.as_view()), name="chatpage"), and this is the line of views.py for chatpage. class ChatView(View): def get(request, username): uname = User.objects.get(username=username) return render(request, 'chatbot/chatPage.html', { 'uname': uname }, context_instance=RequestContext(request)) and this is the Html code that I use for username input: <input class="w-full text-lg py-2 border-b border-gray-300 focus:outline-none focus:border-indigo-500" type="text" placeholder="Enter Your Username" id="username" name="username" value="{{data.username}}" Required> These are the four links of pastebin for whole code: views.py urls.py chatpage.html signin.html