Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a safe way to safely delete a Model field in Django?
I'm making a blog application in Django, and I want to modify a field of the Post class: I want to change the meta_description field to just description. From: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) meta_description = models.TextField(blank=True, null=True) body = models.TextField() def __str__(self): """ Show the title and the author in the admin Page """ return self.title + " by " + str(self.author) def get_absolute_url(self): return reverse("blog:article_page", kwargs={"pk": self.pk}) ⏎ To: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) description = models.TextField(blank=True, null=True) body = models.TextField() def __str__(self): """ Show the title and the author in the admin Page """ return self.title + " by " + str(self.author) def get_absolute_url(self): return reverse("blog:article_page", kwargs={"pk": self.pk}) When I do that in the model: I have an error Making the migration: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, … -
devtools: Open response HTML in new tab
I an ajax/fetch request fails, my framework (django) does display a nice debug page, which contains a lot of useful information. In chrome devtools I can see a preview of this debug page. Is there a way to open the output of the POST request in a new tab? If I use right-button-click "open in new tab" then chrome does a GET. But the GET does not trigger the exception which I would like to debug. -
Django API didn't detect a field in my database
I'm doing the Django official tutorial, here are the models I wrote and migrated from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(name="date published") class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) and I used the command python manage.py shell to use the Django API and ran the following commands: >>> from polls.models import Question, Choice >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) and got this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/mohammedi/.virtualenvs/mywebsite1/lib/python3.7/site-packages/django/db/models/base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Question() got an unexpected keyword argument 'pub_date' what the hell is wrong with this -
Django: Unique ID's across tables
I was curious if there was a good solution to implement unique ID's between tables. class Voice(models.Model): id = .. <------| slug = ... | name = .... |-- No duplicate IDs | class Group(models.Model): | id = .. <------| slug = ... name = .... My hope is that when I get an ID in a view, selecting from one model will give me None but the other will always return the object (and vice versa). If there is a better approach feel free to share. Right now I am using the slug+id as query filters but would like to move away from that. -
(Django) Value set in session disappears after i render the request through the same view a second time
Here's what's happening: HTML Template "A" has a form that passes a variable with name="var1" to URL1. URL1 sends the request to VIEW1. VIEW1 then checks for and thereafter "gets" the "var1" variable successfully, and sets it in a session variable (request.session['variable'] = "var1" VIEW1 then renders the request to HTML Template "B", which has another form that passes a variable with name="var2" to URL1 again. URL1 sends the request to VIEW1 again. This time, "VAR1" is no longer available to "GET", but "VAR2" is. However, when i print the session variable (print(request.session['variable])), it no longer exists. My question is: Does passing a request back into the same VIEW a second time clear out any session variables you have set on the first pass? It certainly appears to be the case, but i can't figure out why. Before, I was using a global dictionary variable to store everything in, and it worked well, but it would expire if i didn't navigate quickly enough. Accordingly, i switched to storing my dictionary in the session. Thanks! -
Braintree Django Exception "can only concatenate str (not "tuple") to str"
I'm using Braintree Drop-in with my Django Project. It's working completely fine when I use it in development environment (manage.py runserver). But when I'm accessing the same on elastic beanstalk im getting the error "can only concatenate str (not "tuple") to str". The following is my code. extras.py from django.conf import settings import braintree gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id=settings.BT_MERCHANT_ID, public_key=settings.BT_PUBLIC_KEY, private_key=settings.BT_PRIVATE_KEY, ) ) def generate_client_token(): return gateway.client_token.generate() def transact(options): return gateway.transaction.sale(options) def find_transaction(id): return gateway.transaction.find(id) signals.py from django.db.models.signals import post_save from django.dispatch import receiver #from django.conf import settings from invoices.extras import gateway @receiver(post_save, sender=User) def create_phone(sender, instance, created, **kwargs): if created: gateway.customer.create({ "first_name": instance.first_name, "last_name": instance.last_name, "email": instance.email, "phone": instance.phone_number, "id": instance.id, }) views.py @login_required() def customer_invoice_view(request, ticket_id): ticket = get_object_or_404(Ticket, pk=ticket_id) customer = ticket.customer client_token = gateway.client_token.generate({"customer_id": str(customer.id)}) invoice = ticket.invoice if request.method == 'POST': result = transact({ 'amount': invoice.amount_payable, 'payment_method_nonce': request.POST['payment_method_nonce'], 'options': { "submit_for_settlement": True } }) if result.is_success or result.transaction: invoice.is_paid = True invoice.save() ticket = invoice.ticket ticket.status ='Payment Made' ticket.paid = True ticket.save() return redirect(customer_invoice_view, ticket_id=ticket.id) else: for x in result.errors.deep_errors: messages.info(request, x) return redirect(customer_invoice_view, ticket_id=ticket.id) context = { 'ticket' : ticket, 'invoice' : invoice, 'client_token' : client_token, } return render(request, 'invoice/ticket_invoice_view.html', context) ticket_invoice_view.html <div … -
Translation key-based internationalization with Django
Django's default i18n system uses the code language (for instance, English) as translation keys; translations into other languages must be written from that base language. For instance, in a Django template, you would write {% trans "Hello" %} and then translate "Hello" into "Bonjour" or "Hola" in the French or Spanish translation file. This has a major flaw: words that are spelled the same in English cannot be translated differently in other languages. For instance, if I use {% trans "Fire" %} in two places of my code, one of which meaning the thing that burns, and the other using a cannon, I would need "Feu" and "Tirer" respectively in French; but Django's i18n forces me to choose a single translation for "Fire". The translation keys pattern solves this: I use translation keys such as {% trans "campsite.fire" %} and {% trans "cannon.fire" %} in my code, that I translate as "Fire" in an English translation file and as "Feu" and "Tirer" respectively in the French file. Is this a supported use of Django's i18n system? How do I inject variables into such translations? -
Django: Return back from POST-redirect in Chrome without dublicate pages
I have a detail-page, with a button that submits a GET or a POST request (tried both). This request performs an action and redirects to the same detail-page (thus refreshing it). Everything seems to be fine in Firefox, but in Chrome when I press Back Button, I get back on the same page again (so redirecting to the same page creates dublicates of this page in browser history). Can I somehow change this behaviour and remove those dublicates in Chrome also? -
Jquery for followers not triggering
I want to add the following functionality to a site but need Jquery to change the following to unfollow and vice-versa. Everything seems fine but it's not working. (All the links to jquery work perfectly and load) Jquery for the functionality $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if(data['status'] == 'ok' ){var previous_action == $('a.follow').data('action'); console.log(previous_action); // toggle data_action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text $('a.follow').text(previous_action =='follow' ? 'Unfollow' : 'Follow'); // update followers var previous_followers = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1); } } ) }); HTML {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow btn"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> {% endwith %} view for on jquery request @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create( user_from=request.user, user_to=user ) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'error'}) … -
Django - NoReverseMatch at /project/3/evillio
I'm working on a portfolio project and i face a strange problem when trying to list a project, ( class-based-views-DetailView). More specifically when trying to list a project for example /project/3/evillio i got following error Reverse for 'project-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['project/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$'] but when i add a new project, i'm able to list /project/3/evillio with no problem, however i got the same error on the next project /project/4/urban. urls.py path('project/<int:pk>/<slug:slug>', WorkProjectsDetailView.as_view(), name='project-detail'), views.py class WorkProjectsDetailView(DetailView): model = Project template_name = 'work/project-detail.html' context_object_name = 'single_project' def get_context_data(self, **kwargs): context = super(WorkProjectsDetailView, self).get_context_data(**kwargs) context['next'] = Project.objects.filter(id__gt=self.kwargs['pk']).order_by('pk').first() return context detail-project.html <div class="projects-list gallery"> {% if projects %} {% for project in projects %} <div class="item brand"> <a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" class="effect-ajax" data-dsn-ajax="work" data-dsn-grid="move-up"> <img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="" /> <div class="item-border"></div> <div class="item-info"> <h5 class="cat">{{ project.category }}</h5> <h4>{{ project.title }}</h4> <span><span>View Project</span></span> </div> </a> </div> {% endfor %} {% else %} <div class="col-lg-8"> <p>No Projects Available</p> </div> {% endif %} </div> Any help appreciated. -
Django Try/Except CBVs dealing with query returning None?
I am trying to include some exception handling to handle queries that return None, If none is returned I just want to display a simple JsonResponse message. Working with FBVs, I've done this pretty simply. But when using class based views, my except block is not doing as I expect. class BusinessDetailView(DetailView): model = BusinessDetail def get_object(self, queryset=None): business = self.model.objects.filter(**custom filters here)).values().first() logger.debug(Business: {business}') return business def get(self, request, *args, **kwargs): try: try: business = self.get_object() except BusinessDetail.DoesNotExist: return JsonResponse({'Error': 'Business Does Not Exist.'}) return JsonResponse(company, status=200) except Exception as e: logger.error(f'Error getting business detail with error: {e}') return JsonResponse({'Error': 'Database error, return to previous page'}, status=500) In the get_object method, the logger is returning Business: None as I expect. But in the get method, the BusinessDetail.DoesNotexist is not getting hit. The last Try/Except block is the one getting hit, returning return JsonResponse({'Error': 'DB error, return to previous page'}, status=500). From my understanding, the DoesNotExist exception would catch the query returning None? But in my case this is not occurring. Any help is greatly appreciated! -
Why i get 'NoneType' object has no attribute 'days_count' this error in my code
I want to multiple days_count * room_service but after multiple i see this outpout which is not suitable . Please See the image where Room_Cost is like 800days, 000 whats the solution please help me.. class PatientDischarge(models.Model): assign_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, null=True) appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=False, null=True) medicine_cost = models.IntegerField(null=True, blank=True) other_charge = models.IntegerField(null=True, blank=True) def __str__(self): return self.appointment.patient.name if all([self.appointment, self.appointment.patient, self.appointment.patient.name]) else 0 def days_count(self): return self.release_date - self.appointment.entry_date if all([self.appointment, self.appointment.entry_date]) else 0 def room_bill(self): return self.days_count() * self.appointment.room_service if all([self.appointment, self.appointment.room_service]) else 0 -
Cannot force an update in save() with no primary key
I am working with a custom build user model in Django and there was some message in the terminal at the time of migrate given in the stackoverflow link. However, I have failed to solve that and it didn't hamper to run the project, so I actually ignore it and continue with my code. Now when I try to log-in to the admin panel(http://127.0.0.1:8000/admin/) it shows the following error: Internal Server Error: /admin/login/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\contrib\admin\sites.py", line 407, in login return LoginView.as_view(**defaults)(request) File "G:\Python\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\contrib\auth\views.py", line 63, … -
Security issue with custom build decorator in Django
I am working with a custom build decorator in Django. my decorators.py: from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test def industry_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='app2:request_login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_Industry, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator Here is_Industry is a bool value, comes from models.py. my views.py: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inserted_text'] = "inserted text from EmployeeDetails of views.py" return context in urls.py: path('industryDetails/<int:pk>/', views.industryDetails.as_view(), name='industryDetails') models.py also included if you need: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) Now my problem is, suppose a user with having primary_key=3, can easily visite another user's data having primary_key=2, by using http://127.0.0.1:8000/industryDetails/2/ (by changing the primary key in this address path). I need to stop this for my project. How can I code this in such a way that, any user can only visit his own details? -
Best approach for developing a stateful computation-heavy application with a rest-api interface using python?
I want to develop an end-to-end machine learning application where data will be in gpu-memory and computations will run on the gpu. A stateless RESTfull service with a database is not desirable since the traffic between gpu-memory and database will destroy the "purpose" of it being fast. The way I see it is that I need a way to "serve" the class (lets call it as experiment class) which has the data and the methods, then call them using rest apis. Right now I am using FastApi and initialize the experiment class in it which I believe is not optimal. My class (as well as the data) lives in FastAPI runtime. Kinda like, import experiment_class import FastApi app = FastAPI() my_experiment = expertiment_class() @app.get("/load_csv") my_experiment.load_csv("some_file_path") // do some more on the data ... There are two problems I am having a hard time with, One of them is the terminology: Is this really a stateful application ? Is there a word to describe what I am doing ? Is this a "Model, View , Controller" design, can it be a simple "Server-Client" or is it something completely different ? Do I need a "Web-server" , a "Web-framework" or a "Web-service" … -
How can I use voice as an input method in Django and create models using it? How can I get the input from the microphone and send it to the backend?
This is somewhat near to a Virtual Assistant. I know I would require JS for this but how do I get the input and send it to the backend? -
DJANGO_SETTINGS_MODULE Visual Studio Code Terminal Error
Based on other posts, I've added a new .env file within my app but this error is still appearing. I've also added the top setting module in my settings.py file but still no luck. Any thoughts on what's causing this? Visual Studio Code Terminal Error: Traceback (most recent call last): File "c:/xxxx/Python/Price Tracking/Django/mysite/polls/models.py", line 7, in <module> class Question(models.Model): File "C:\Python38\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Python38\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Python38\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Python38\lib\site-packages\django\conf\__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. PS C:\Users\xxxx\Python\Price Tracking\Django\mysite> settings import os from pathlib import Path os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django django.setup() from django.core.management import call_command INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'chartjs', ] C:\Users\xxxx\Django\mysite.env file: DJANGO_SETTINGS_MODULE='mysite.settings' -
How OuterRef works in django?
Im not able to understand how really OuterRef in django ORM works. For example: Table.objects.filter(field=OuterRef("pk")) What does this mean? What role does field and pk play here and how it affects the final queryset? Someone please elaborate. Thanks in advance. -
Django E-commerce From Scratch vs Package [closed]
I'm building an e-commerce store for a startup. It's not huge - the shop will be dropping two types of t-shirts and two types of pants per month. I want to use django for back-end. Should I build it from scratch or use something like Django Oscar (or other packages - WRITE RECOMENDATIONS) and customize it? -
Django Rest Framework to return desired results from two models
I have two models (customer, movie) and I would like to return (movie_name, customer_name, id) when I hit the URL (api/customer/1) and when I hit the URL (api/customer/1/movies) just wanted the movie names alone. How can we achieve this ? models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) class Movie(models.Model): movie_name = models.CharField(max_length=200, null=True) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name') class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/customers/$', CustomerSerializer.as_view(), name='customers'), ] Note: At the moment, when I hit the URL (api/customers) it returns the id, name of all the customers. Now, I would like to know, when I hit the URL (api/customer/1) how to list the same information along with movie names and when I hit the URL (api/customer/1/movies) how to just return the movie names alone? -
What is the best way to pass a parameter from views into an anchor tag?
I'm building a dashboard that has a button on a sidebar that allows a user to update their data. Which currently looks like this: <a class="nav-link" href="{% url 'form-update' pk=id %}"> Questionnaire </a> I'm trying to connect that id field to my views.py: def dashboard(request): user = request.user account = 0 id = Form.objects.filter(author=user,account=account) context = { 'id':id } return render(request, 'dashboard/index.html',context) url pattern: path('update/<int:pk>', FormUpdateView.as_view(),name='form-update') I'm not sure the best way to send this data to the href tag? -
Running "tasks" periodically with Django without seperate server
I realize similar questions have been asked however they have all been about a sepficic problem whereas I don't even now how I would go about doing what I need to. That is: From my Django webapp I need to scrape a website periodically while my webapp runs on a server. The first options that I found were "django-background-tasks" (which doesn't seem to work the way I want it to) and 'celery-beat' which recommends getting another server if i understood correctly. I figured just running a seperate thread would work but I can't seem to make that work without it interrupting the server and vice-versa and it's not the "correct" way of doing it. Is there a way to run a task periodically without the need for a seperate server and a request to be made to an app in Django? -
Django: A GET Request gets submitted after a POST
My Web Form has a JQuery generated list, that is submitted via a Post Request This is the Jquery Generated List: $(function(){ $("#addToList").click(function(e){ var text= $("#txtSearch").val(); $("#nameList").append(`<li>${text} <a href="#" class="remove_this btn btn-danger">remove</a></li>`); $("#txtSearch").val(""); }); $(document).on('click', '.remove_this', function() { $(this).parent().remove(); return false; }); The Text Field used to populate the list is an Ajax Text Field nd is populated using the folowing code: $(document).ready(function(){ $("#txtSearch").autocomplete({ source: "/ajax_calls/search/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); The above generated list is submitted using the following Code On the Press of a Submit Button. $("#submit").on('click', function() { var stocks = getStocks(); $.ajax({ type: 'POST', url: '/analyser', data: {'stocks': stocks, 'csrfmiddlewaretoken': '{{csrf_token}}'}, }); }); The HTML for the same is as below: <form id="search" > <input type="text" id="txtSearch" name="txtSearch"> </form> <div id="listCreate"> <button id ="addToList" >Add to list</button> <ol id="nameList"> </ol> </div> <button id ="submit" form="search" >Analyse</button> The View Handler for the above request is: def function(request): print("Request is ", request.method) if request.method == 'POST': //Code To build Context here context = { "x": y, } return render(request, 'pages/analyser.html', context) return render(request, 'pages/analyser.html') The Problem is that there is an additional GET Request that is getting submitted after … -
Django form not submitting data to database
I've dig through old post about this topic but like allways nothing works for me. My problem is that data isn't saved. I've printed out form and it's okey, then I've printed out forms.is_valid which gave me true, forms.save() also returns customer object so I don't know where to look now (this form updates user shipping data) form class customerUpdate(ModelForm): class Meta: model = ShippingAddress fields = ['city', 'country','zip_code','adress','phone',] exclude = ['customer','order','date_added'] widgets ={ 'city' :forms.TextInput(attrs={'class':'updateForm',}), 'country' :forms.TextInput(attrs={'class':'updateForm',}), 'zip_code' :forms.TextInput(attrs={'class':'updateForm',}), 'adress' :forms.TextInput(attrs={'class':'updateForm',}), 'phone' :forms.TextInput(attrs={'class':'updateForm',}), } Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) city = models.TextField(max_length=50, null=True, blank=True) country = models.TextField(max_length=50, null=True, blank=True) zip_code = models.TextField(max_length=15, null=True, blank=True) phone = models.TextField(max_length=9, null=True, blank=True) adress = models.TextField(max_length=100, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.adress) views def userView(request): userData = request.user.customer forms = customerUpdate(instance=userData) if request.method == "POST": forms = customerUpdate(request.POST, instance=userData) if forms.is_valid(): forms.save() context={ 'userData':userData, 'forms':forms } return render(request,'user.html', context) html {% load i18n %} <div class="editUserInfoWrapper"> <form method="POST" action="{% url 'user' %}"class="formUserPanel" > {% csrf_token %} <div class="container"> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> {{ forms.city }} </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> {{ forms.country }} </div> </div> … -
Django model override save() method raises error when calling super()
I have the following Django model: class TCDUser(AbstractUser): is_change_password = models.BooleanField(_("Cambiar Password?"), default=True) groups = models.ManyToManyField(Group, default=[], related_name='users', verbose_name=_("Grupos")) class Meta: verbose_name = _("Usuario") verbose_name_plural = _("Usuarios") def __str__(self): return "[{}]{}".format(self.pk, self.username) def save(self): create = True if self.id is None else False if create: self.set_password(self.password) super(CustomModel).save() And this is the serializer: class TCDUserSerializer(CustomModelSerializer): class Meta: model = models.TCDUser fields = ('id','username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'password', 'is_change_password', 'groups') When I send a POST to the regular DRF ModelViewSet, I get this exception: TypeError: Got a `TypeError` when calling `TCDUser.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `TCDUser.objects.create()`. You may need to make the field read-only, or override the TCDUserSerializer.create() method to handle this correctly. If I remove the call super(CustomModel).save(), the exception is no more, but I need to set the password when the user is created.