Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Django Filters ModelMultipleChoiceFilter doesn't work with icontains
I'm trying to filter Django permission groups by the permissions within the group which has a ManyToMany relationship. I'm using django == 3.2.5, django_filter == 2.4.0 and django_rest_framework==3.12.4. Currently the filter only works if I use "exact" as my field lookup but when I use "icontains" it throws this error; { "permissions__icontains": [ "“can” is not a valid value." ], I can't see what I'm doing differently versus from docs and this stack overflow post. https://django-filter.readthedocs.io/en/stable/ref/filters.html?highlight=ModelMultipleChoiceFilter#modelmultiplechoicefilter How to use ModelMultipleChoiceFilter? Is there a way I can get filter results when it is not an exact match?? cheers in advance! request url http://127.0.0.1:8000/permission_groups/?permissions__icontains=can filter class PermissionsGroupFilterSet(FilterSet): name = AllValuesMultipleFilter(field_name="name") permissions = ModelMultipleChoiceFilter( queryset=Permission.objects.all(), field_name="permissions__name", to_field_name="name" ) class Meta: model = Group fields = { "name": ["icontains", "in"], "permissions": ["exact", "icontains"], } models.py (standard group/permission models) class Group(models.Model): name = models.CharField(_('name'), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) class Permission(models.Model): name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) objects = PermissionManager() class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = [['content_type', 'codename']] … -
Saving an object with formset element AND making a copy with new related elements
I'm trying to do some kind of a mixte between a Create and an Update on an object that has foreign keys (managed as inline formset). Updating the parent object in a form (as well as its related formset forms) works fine. I can also save a copy of that parent object as a new instance in the DB, that works fine. However I can't seem to figure out how to also make copy of the formset as new independant objects. Basically, once all is said & done, I want: Foo (pk=1) bar_1 bar_2 ... bar_n FooCopy (pk=2) bar_1_copy ... bar_n_copy I currently can modify Foo, create FooCopy, as well as modify bar_1 to bar_n... but cannot create bar_1_copy etc. For instance: class SoumissionUpdateView(LoginRequiredMixin, SideBarMixin, UpdateView): def form_valid(self, form, formset): # that saves any modification to the initial object, as well as the elements in the formset self.object = form.save() formset.instance = self.object formset.save() # this saves the parent object as a new instance. However no new formset objects are created in the db. self.object.pk = None self.object.save() formset.instance = self.object formset.save() # since those should be 2 different sets of instance in db return HttpResponseRedirect(self.get_success_url()) My understanding was since … -
Filtering field in a django form
I am building a website with django. This website is user based and each user has a profile model. Right now, I am working on building a system where each user can input their job experience. I want it so that you can input a category, and then fill out points for each category. (For example, if you wrote for the New York Times, the category would be "New York Times" and then right under it would be the articles you wrote in bullet points). I can create a category. I can create a work and then assign the work to a category. The issue I am having is that a user can choose a category from a different user in the work form. All I want to do is make it so that the field "category" is filtered so that users can only select categories that they made. I have tried a couple of things but I am not sure where is the best place to filter this field. models.py from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='cat') name = models.CharField(max_length=100) date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) def __str__(self): return … -
AttributeError: 'InMemoryUploadedFile' object has no attribute 'decode'
I am building a django application where I upload a folder containing a lot of CSV files. I retrieve the folder like this in HTML and it works fine: <div class="upload_csv"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="folder" multiple="true" webkitdirectory="true" directory="true"/> <button type="submit">Upload</button> </div> Now, the problem is that I need to use "utf-8" encoding before moving on. I dont know how to do that when handling a directory, and not only an UploadedFile file. What I have so far is this: def csv_retriever(request): if request.method == 'POST' and request.FILES['folder']: # encoding could happen here with the entire folder for file in request.FILES.getlist('folder'): # or here with the current file calculations(file) return render(request, 'price_calculator_started.html') -
json decode error expecting value: line 1 column 1 (char 0)
I am trying to get an mpesa authentication token which is json format. It gives an error in the decoding code Below is my views.py import requests import json def getAccessToken(request): consumer_key = '' consumer_secret = '' api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate? grant_type=client_credentials' r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret)) mpesa_access_token = json.loads(r.text) validated_mpesa_access_token = mpesa_access_token['access_token'] return HttpResponse(validated_mpesa_access_token) Below is my projects urls.py from django.urls import path, include urlpatterns = [ path('', include('store.urls')), ] where store is the name of my app My store urls.py, from django.urls import path from .import views urlpatterns = [ path('access/token/', views.getAccessToken, name='get_mpesa_access_token'), ] When I access that url instead of giving me the token I want, it gives the error below: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 24, 2021 - 20:45:26 Django version 2.2, using settings 'mvee.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /access/token/ Traceback (most recent call last): File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/victor_nzioka/Desktop/projects/venv/MVEE/src/store/views.py", line 121, in getAccessToken mpesa_access_token = json.loads(r.text) File "/home/victor_nzioka/anaconda3/lib/python3.8/json/__init__.py", … -
Django Model and Form for Comment system
I have made a comment system under my books where only the authenticated user can comment. When I use the form to add a comment, it doesn't work! why ? here is my models models.py class Books(models.Model): author = models.ManyToManyField(Authors) title = models.CharField(max_length=250) number_of_pages = models.PositiveIntegerField(validators=[MaxValueValidator(99999999999)]) date_added = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) publication_date = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(300), max_value_current_year]) cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg') pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf') category = models.ForeignKey(Categories, on_delete=models.CASCADE) def __str__(self): return self.title class Comments(models.Model): book = models.ForeignKey(Books, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} - {}'.format(self.livre.title, self.user) here is my forms forms.py class BookForm(ModelForm): class Meta: model = Books fields = '__all__' class CommentForm(ModelForm): class Meta: model = Comments fields = ['body'] here is my views views.py @login_required(login_url='login') def book_detail_view(request, book_id): books = get_object_or_404(Books, pk=book_id) context = {'books': books,} return render(request, 'book_detail.html', context) @login_required(login_url='login') def add_comment(request, comment_id): form = CommentForm() books = get_object_or_404(Books, pk=comment_id) user = request.user if request.method == "POST": form = CommentForm(request.POST, instance=books) if form.is_valid(): comment = form.save(commit=False) comment.user = user comment.books = books comment.save() return redirect('book_detail', books.id) context = {'form': form} return render(request, 'comment_form.html', context) here is my book detail page book_detail.html {% extends 'base.html' %} {% block … -
Input data in german data format combined with ChartsJs
I'm relative new to Charts.js, but I'll need it to create some nice graphs for my webpage. In the background I have a Django project running which computes me a certain amount of numbers. Since I've put the language code in Django to "de-at" (requirement, since there are some input variables to fill in by austrian users), the number formats are done like: "1.000.000,54€" and not the US-way like "1,000,000.54€". If I now want to add some of my data into charts.js, it won't read the data, which has more than 6 digits. Furthermore, if there is a number like "653.598,36" it takes actually two parameters, namely (653,598 ; 36). Formatting the numbers in python does not help, since charts.js won't use strings for the graphs. Using the setting "locale = 'de-DE'" in the charts.js options only helps for labelling propertes, not for the data itself. If I change the Django setting back to "en-us", charts.js works with the numbers, but than my numbers on the webpage are not formatted correctly for the end-user. Has someone experienced this problem and has a solution to it? Thank you and best regards! Here is the code of charts.js with example values. I … -
How to add items drop down menu in django
I'm making a web app for post blogs.And I added categories field to identify the category of that blog.But the problem is I can add categories in only when I on admin page.But I want to have that add category button in fronend as well. example: when I click categories field it shows up current categories in database but I want to add add button to that drop down menu of category. .this is picture of my add post page model.py class PostForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name')) class Meta: model = Post fields = ('title', 'category','author', 'content', 'image','status') template {% if user.is_authenticated %} <h1>Add Post...</h1> <br/><br/> <div class="form-group"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <br> <button class="btn btn-secondary btn-lg">Post</button> </form> -
AppRegistryNotReady Error when packaging a Django app with Pyinstaller
I'm using Django 3 (also tried with 2.2) and pyinstaller to make an standalone Django based app. I run pyinstaller this way: pyinstaller --onedir --clean --name=projectx manage.py --additional-hooks-dir=projectx_backend/ I have a custom hook with this code: from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('django.contrib') And an __init__.py file in my projectx_backend/settings folder with the following content: from .desktop import * The content of manage.py is: #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectx_backend.settings.desktop') import django from django.conf import settings from projectx_backend.settings import desktop settings.configure(default_settings=desktop) django.setup() try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) When trying to build the exec it complaints about some missing modules. I ensured those modules are installer in my current environment, but I think I'm not loading them correctly. pyinstaller --onedir --clean --name=projectx manage.py --additional-hooks-dir=projectx_backend/ 39 INFO: PyInstaller: 4.3 39 INFO: Python: 3.8.10 49 INFO: Platform: Linux-5.11.0-27-generic-x86_64-with-glibc2.29 49 INFO: wrote /home/peckers/dev/projectx-backend/projectx.spec 51 INFO: UPX is not available. 52 INFO: Removing temporary files and cleaning cache in /home/peckers/.cache/pyinstaller 53 INFO: Extending PYTHONPATH … -
UndefinedError: 'request' is undefined in template
I am using Django 3.1. I have a template view that usually renders fine, however on occasion I find the following error in my logs. Unfortunately I can't seem to reproduce it. UndefinedError: 'request' is undefined File "django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "django/core/handlers/base.py", line 106, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "django/middleware/csrf.py", line 242, in process_view return self._reject(request, REASON_NO_REFERER) File "django/middleware/csrf.py", line 149, in _reject response = _get_failure_view()(request, reason=reason) File "django/views/csrf.py", line 154, in csrf_failure return HttpResponseForbidden(t.render(c), content_type='text/html') File "django_jinja/backend.py", line 59, in render return mark_safe(self._process_template(self.template.render, context, request)) File "django_jinja/backend.py", line 105, in _process_template return handler(context) File "scout_apm/instruments/jinja2.py", line 74, in wrapped_render return wrapped(*args, **kwargs) File "jinja2/environment.py", line 1090, in render self.environment.handle_exception() File "jinja2/environment.py", line 832, in handle_exception reraise(*rewrite_traceback_stack(source=source)) File "jinja2/_compat.py", line 28, in reraise raise value.with_traceback(tb) File "/app/templates/403_csrf.html", line 8, in top-level template code {% set card_body %} File "/app/templates/global/base_tenant.html", line 2, in top-level template code {% extends 'global/base.html' %} File "/app/templates/global/base.html", line 4, in top-level template code {% block header %} File "/app/templates/global/base.html", line 26, in block "header" <link nonce="{{ request.csp_nonce }}" rel="manifest" href="{{ static('manifest.json') }}"> File "jinja2/environment.py", line 471, in getattr return getattr(obj, attribute) This appears to be an issue … -
Need Django Query optimization (2 Queries instead of 21)
I have a Django project on EBS and one query takes a pretty long time. I'd like to optimize it so that it's just one or two queries but I'm not sure if it's even possible. Models: WebSite,Article The query is a list of Articles from different websites. WebSite model has a home_order and home_article_count attributes that are used to select a number of articles and in which order they are. Example for websites A, B and C: A - A.home_order = 2, A.home_article_count=3 B - B.home_order = 1, B.home_article_count=5 C - C.home_order = 3, C.home_article_count=7 The result would be (aA means an article from website A): aB,aB,aB,aB,aB,aA,aA,aA,aC,aC,aC,aC,aC,aC,aC The lists starts with aB that means articles from website B because B.home_order=1, there are 5 aB articles as B.home_article_count=5. Right now, this is a Manager method that returns the articles: def home(self) -> QuerySet: articles_pks = [] for ws in WebSite.objects.active().order_by('home_order', 'name'): articles_pks.extend(ws.articles.filter(is_active=True).order_by('-created')[:ws.home_article_count].values_list('pk',flat=True)) return self.get_queryset().filter(pk__in=articles_pks) That means, for 20 WebSite objects, there is 21 queries (one that gets the websites and the other 20 for articles). Is it possible to merge it into one or two queries while respecting the WebSite.home_order and WebSite.home_article_count? -
How to sort column with dates from sqlite3 django with js datatables
I'm have datetime.datetime data in sqlite database in format "2021-04-07 09:12:22". Web app on Django show me this like "7 апреля 2021 г. 09:12" ("7 April 2021 09:12"). And I'm cant find the right format date to apply sort in my table on page with JS Datatables. All script source load on HTML page. $(document).ready(function() { $.fn.dataTable.moment('YYYY-MM-DD HH:mm:ss'); $('#purchases').DataTable( { "iDisplayLength": 50, "order": [[ 2, "desc" ]] } ); } ); When i'm commented this $.fn.dataTable.moment('YYYY-MM-DD HH:mm:ss'); datatables render table very well. But with this => datatables is not work right (dont render table). Asking for help with right date format for sorting. -
how to get url and pass it as a url parameter in django
i want to pass url as a url parameter for example in my website there are two hotels (hotel A and hotel B) in home page it only shows two buttons one for access hotel A and the other for hotel B i want to get the first url and pass it as url parameter for example my-ip/hote-A get the hotel-A in the url and pass it as url parameter class Hotels(models.Model): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name def hotels(request): hotel_lists= Restaurants.objects.all() return render(request,'hotel/lists.html',{'lists':hotel_lists}) <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3 pt-3"> {% for i in lists %} <a href="{% url 'rooms:categories' i.hotel_name %}"><button class="text-pink-500 bg-transparent border border-solid border-pink-500 hover:bg-pink-500 hover:text-white active:bg-pink-600 font-bold uppercase px-8 py-3 rounded outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150" type="button"> {{i.hotel_name }} </button></a> {% endfor %} </div> till here everything works fine , but when we select for example hotel A it will bring us to a dashboard which everything should be related with hotel A in my main.html there is a menu which all links should bring us to that data which relates with that hotel class Rooms(models.Model): hotel= models.ForeignKey(Restaurants,on_delete=models.PROTECT) room_number = models.IntegerField() beds = models.IntegerField(default=2) @login_required def categories(request,hotel): lists = Room.objects.filter(hotel__hotel_name=hotel).values('hotel__hotel_name', 'beds', … -
How long does Django's password reset link work?
I just want to know after how much time does the link expire. How long does Django's password reset link work? -
Django: Can I have access to client cookies on first page load?
I need to read a cookie set by Google in order to render my homepage view. But I noticed that, on first load, the object request.COOKIES is always empty. I'm not sure if this is normal, my logic says "when you have a new visitor, all cookies are empty by default, so this is normal", but then, how do tools like Google Optimize work? Is there any way to wait for all client cookies to be set before rendering a view in Django? or will this never be something you'll want to do? I'm having a rough time trying to make an A/B to test work, but I'm starting to think that my approach of reading the cookies on first load was destined to never work. Can someone give me some piece of advice here? -
How to input data in django forms as a list?
I need to forrward this data as python list to django, not as string. How to create list, just to input data separated with commas? class CreateForm(forms.Form): list = forms.CharField(label='Input names (separate with commas): ') -
Django :Uncaught ReferenceError: require is not defined. Is it a django or javascript problem? how i can fix it?
how can use requier function in javascript enter the templates (Django)? -
Marshmallow: How to build a Schema from a nested JSON that includes lists?
I have the following JSON from a payload: { "lunch":{ "appetizer":[ { "size_id":2, "menu_id":34 }, { "size_id":6, "menu_id":78 } ], "entree":{ "start":12, "end":34 }, "dessert":12 } } I need to build a schema subclass using marshmallow.Schema. The lunch will always have an appetizer, entree and dessert keys. The appetizer will be a list of apps, the entree will always have a start and an end, and the dessert will always have a single number. -
Django list view repeatedly fails, but detail pages work
testt1 is my view for taking a queryset and turning out a list of objects and their foreign key children. mydetail is the detail view for the individual objects. No slug is used in the list, but it is in the list template to call the detail pages. But all these errors come from trying to call the list, not the detail. If I just type the slug into the address bar, all my detail pages come up just fine! I have tried a lot of different things, and get a lot of different errors, but the bottom line is always the same: no list named url fails Error during template rendering In template /home/malikarumi/Projects/hattie/templates/base.html, error at line 44 Reverse for 'jhp_url' not found. 'jhp_url' is not a valid view function or pattern name. ‘jhp_url’ is the named url for the detail page. But here is line 44: <link href="{% static 'plugins/owl-carousel/owl.carousel.css' %}" rel="stylesheet"> the urlpattern: path('<slug:slug>/', mydetail, name='jhp_url'), the call to reverse(): def get_absolute_url(self): return reverse(‘jhp_url', kwargs={'slug': self.slug}) namespaced url fails Error during template rendering In template /home/malikarumi/Projects/hattie/templates/base.html, error at line 44 Reverse for 'jhp_url' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P[^/]+)/courts/(?P[-a-zA-Z0-9_]+)/$'] Now it has … -
how to build a url on django outside a template
I have an application that when the user instance is created a signal is dispatched to send an email. I am implementing a signal to send an SMS. On my email HTML template I have this line that redirect the user, I need to send the same link on the SMS. <a href="{{ uri }}{% url 'password-reset-and-active-account' uidb64=uid token=token %}">Aqui</a> the parameters used there is passed through this context context = { 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode("utf-8"), 'token': default_token_generator.make_token(user), 'uri': settings.ABSOLUTE_URI } how can I build this URL outside Django Templates, because the {% url 'password-reset-and-active-account' %} will not work outside the template right? -
How do I get List of values from django form template to form.py Cleaned_data
I am actually try to post a list of values ['good','nice','happy'] to the backend. I have following files in my django app. models.py class TagModel(models.Model): name = models.CharField(max_length=255) class BlogModel(models.Model): title = models.CharField(max_length=255) tags = models.ManyToManyField(TagModel) forms.py class BlogForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder':_('Enter Blog Title'), 'class' : 'form-control border-success' })) blog_tags = forms.ChoiceField(widget=forms.TextInput(attrs={ "name":"blog_tags" })) def clean_title(self): title = self.cleaned_data.get('title') print(title) return title def clean_blog_tags(self): //this line does not get whole list of data tags = self.cleaned_data.get('blog_tags') print(tags) // problem is here return tags class Meta: model = PostModel fields = ['title','blog_tags'] views.py class create_blog(CreateView): template_name = 'blogbackend/create_blog.html' form_class=BlogForm def get_form_kwargs(self): kwargs = super(create_blog,self).get_form_kwargs() print(kwargs) return kwargs Html Template What happen on template is :- I render the title field on the view I added a JS code on Input box , which gets value a create a hidden input with name blog_tags which is same as the filed name in forms.py file After user submit the form I successfully receives the both input values title and blog_tags in my views.py file and successfully display on console with helper function get_form_kwargs() Data is look like this {'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['4Cm5mvGFv4skPJNTzRI8fKZKq9i7edQbwNmOgCPbDTtu8JQHqE5cd9rQLA8Kzhpu'],'title': ['first'],'blog_tags' : ['good','nice','happy']}>, 'instance':None} Problem When … -
NoReverseMatch at login with Django password reset
I have a small Django application. I am setting up authentication and I have just finished the forgotten/reset password functionality. However, once the password is reset it does not redirect to the success page. I've trawled through all my code and cannot find any references to 'login' that is incorrectly coded. The error that appears is the following: 'Reverse for 'login' not found. 'login' is not a valid view function or pattern name' Here's the relevant files from my project: account urls.py from django.urls import path, include, reverse_lazy from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Login URLs path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), #User Pages URLs path('dashboard/', views.dashboard, name='dashboard'), path('nodes/', include('nodes.urls')), #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), #Password Reset URLs path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('account:password_reset_done')), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('account:password_reset_complete')), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] password_reset_confirm.html: {% block content %} <div class="page-title"> <h1>Reset Password</h1> </div> <br> <div class="login-container"> <div class="login-box"> <br> <h3 style="text-align: center;">Reset your password</h3> <div class="login-form" style="text-align: center; "> {% if validlink %} <p>Please enter your new password twice:</p> <form method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Change my password"/></p> </form> {% else %} <p>The password … -
django __init__() takes 1 positional argument but 6 were given
My model class: class Campaign(models.Model): name = models.CharField(max_length=255) campaign_id = models.CharField(max_length=8, null=False, blank=False, unique=True) def __init__(self): super(Campaign, self).__init__(self) self.campaign_id = generate_random_id(8) # it generates just random string class Meta: ordering = ["name"] def __str__(self): return self.name My view class: def campaign_list(request): campaigns = Campaign.objects.order_by('name').all() return render(request, 'mp/campaign/list.html', {'campaigns': campaigns}) I got error init() takes 1 positional argument but 6 were given Before creating init in my model everything were working fine. But i assume that now Campaing.object.all() is using constructor and not str. How can i omit this and in .all still use just reffering to name, not creating an object again? -
django: returning django form as response for ajax request
I'm new in django. Now I'm looking for a way to get django form as ajax response. I have prepared an ajax request in my myjs.js file Ajax is sending request by url: 'formJson/<str:skl>/' and my formJson view is getting variable skl and it is used as a key to choose a proper form in forms dictionary included in this view. How can I return this form and use it as response in my ajax success function? Any Idea? myjs.js const skladnikBox= document.getElementById('wybieraj'); const modalTytul=document.getElementById("exampleModalLabel") skladnikBox.addEventListener( 'change', e=>{console.log( event.target.value ); const skl=event.target.selectedOptions[0].text; console.log(skl); modalTytul.innerText=event.target.selectedOptions[0].text; `` $("#exampleModal").modal('show'); ////////////////ajax/////////////////////////////// $.ajax({ type: 'GET', url: `formJson/${ skl }/`, success : function(response){ console.log('success', response); // // const skladnikForm = response.data }, error : function (response){ console.log('error', error)} }) /////////////////////ajax///////////////// skladnikBox.selectedIndex = 0; }) views.py def formJson (request,skl): forms={'witamina A':VitAForm,'witamina E':VitEForm,'Hydrokortyzon': HydrokortyzonForm} form=forms[skl] context={ 'form':form} return JsonResponse(context) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home,name='home'), path('formJson/<str:skl>/', views.formJson, name='formJson') ] -
Django dynamic url in root domain overwrites all other urls
I want to have a dynamic root url for different users. All users get their own url. I want to have the dynamic url in the root but also be able to have more hardcoded urls as alternatives, for example on the url that the user will edit their profile. The problem i have is that all urls redirect to view2 and none goes to view1. path(r'edit/<str:user>/', views.view1, name='view1'), path(r'<str:user>/', views.view2, name='view2'), example.com/edit/user always gets redirected to example.com/user which is not wanted.