Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trigger Django Action in Wagtail Equivalent
I'm trying to figure out how to trigger a custom Django action in Wagtail. Essentially trying to run a custom function in some way from the UI in Wagtail. I looked into the ButtonHelper / PageButtonHelper helpers, but it looks like that just allows you to navigate to a url. I'm looking for something very similar to Django Actions in Wagtail. Does anyone know if this is possible, or there's some equivalent in Wagtail? Thanks. -
What is the correct way of setting the Action attribute in a Django form
I have an html form in a Django system and I cannot find the correct way to implement the Action attribute in the form html <form action="stages" method="post"> urls.py urlpatterns = [ path('<str:partner_pk>/stages/', views.Stages.as_view(), name="stages"), ] views.py class Stages(View): """CBV for setting stages.""" url = 'duo/stages.html' def get(self, request, partner_pk): app.context['partner_pk'] = partner_pk return render(request, self.url, app.context) def post(self, request, partner_pk): """Render the POST request.""" stages_selected = app.update_stages(request) if app.context['use_stages'] and not stages_selected: messages.error(request, 'You have not selected any stages.') return render(request, f'{partner_pk}', app.context) else: return HttpResponseRedirect(reverse(f'duo/{partner_pk}/')) The error I get on clicking submit is: RuntimeError at /duo/2/stages/stages You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set... I have tried various other urls in action but the all give an error message -
Django creating super user error: AttributeError: 'ProfileManager' object has no attribute 'create_superuser'
Hi I am trying to create a superuser, however, after I added my own ProfileManager I get the error: AttributeError: 'ProfileManager' object has no attribute 'create_superuser' But my issue is should BaseUserManager already have this method? I cannot find a why to inherit the create_superuser method. My manager is: class ProfileManager(BaseUserManager): pass And my model is: class Profile(AbstractUser): objects = ProfileManager() Thanks for all the help in advance! -
The project doesn't load on Django with Ubuntu VPS, after gunicorn, supervisor and nginx settings [closed]
Hello everyone I ran into a problem, made all settings on the server, checked gunicorn, started the project directly with the command gunicorn Superman.wsgi: application --bind 0.0.0.0:8001, the site started, but without static files. Next, I installed supervisor, also made a separate configuration for it and configured nginx, when checking supervisor sudo supervisorctl status Superman the server replied that it works, when checking nginx sudo nginx-t the server also responds positively successful, but when I score the IP of my site in the browser search bar, the site does not load, the error is Site 91.228.152.32 does not allow you to establish a connection, the nginx logs are empty. What might be the problem, maybe I'm setting proxy_pass incorrectly? I attach the settings below, ASK for HELP in SOLVING the PROBLEM, I'm looking for a solution for a day and nothing(( Setup Gunicorn NAME="Superman-test" DJANGODIR=/webapps/Superman-test/Superman SOCKFILE=/webapps/Superman-test/run/gunicorn.sock GROUP=www-data NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=Superman.settings DJANGO_WSGI_MODULE=Superman.wsgi echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Setup Supervisor [program:Superman] command = sh /webapps/Superman-test/bin/gunicorn_start user = root … -
Django admin: How to get path of uploaded file
I have created model field for User Pic and User_pic_url, what i'm trying to do is when i upload image it's path should get populated in user_pic_url. Note that i'm uploading image from django admin itself. any idea. snapshot for ref: Snapshot Model.py: class Main(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) about = models.TextField() contact = models.CharField(default='0', max_length=12) email = models.CharField(default='-', max_length=50) linkedin = models.CharField(default='-', max_length=50) github = models.CharField(default='-', max_length=50) site_name = models.CharField(default='-', max_length=50) resume = models.FileField() cover_letter = models.FileField() user_pic = models.ImageField() user_pic_url = models.TextField(default="-") -
How to upload my django website to godaddy
I bought a hosting and already have the domain, however, the website is not showing up, the people over at godaddy told me that it is a code issue so I dont know what I have to change in setting.py or something, everything there is like the default -
Django error logging only working in debug mode
When getting a django.request error my logging only writes into the log file when running with DEBUG=True. With DEBUG=False nothing gets written. Here is my LOGGING definition: def skip_static_requests(record): if record.args[0].startswith('GET /static/'): # filter whatever you want return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'skip_static_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_static_requests, }, }, 'formatters': { 'verbose': { 'format': "%(asctime)s [%(schema_name)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/mylog.log', 'filters': ['skip_static_requests'], 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], }, 'null': { 'class': 'logging.NullHandler', }, }, 'loggers': { 'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False, }, 'django': { 'handlers': ['file', 'mail_admins'], 'propagate': True, 'level': config('LOG_LEVEL', default='INFO'), }, 'django.request': { 'handlers': ['file', 'mail_admins'], 'propagate': True, 'level': 'ERROR', } } } Anyone who has a clue what could be wrong? My feeling is that it has nothing to do with the LOGGING definition. -
The domain IIS is overwriting the Subdirectory
I have an site in IIS, lets say www.example.com (Laravel application) , and i have my subdirectory www.example.com/subdirectory (Django application), when i access the /subdirectory, the domain overwrite my subdirectory and I get 404 page of Laravel, I tried to make an rule in web.config of domain but i didn't get results, and I don't know what to So, this is my configs in main.settings( Django) USE_X_FORWARDED_HOST = True FORCE_SCRIPT_NAME = '/subdirectory/' SESSION_COOKIE_PATH = '/subdirectory/' LOGIN_REDIRECT_URL='/subdirectory/' LOGOUT_REDIRECT_URL='/subdirectory/' VIRTUAL_DIRECTORY = "subdirectory/" ALLOWED_HOSTS = ['example.com', 'localhost', 'wwww.example.com'] and my urlpatterns in main.urls urlpatterns = [ path(f'{settings.VIRTUAL_DIRECTORY}admin/', admin.site.urls), # path('password_change/', views.password_change, name='password_change'), path(f'{settings.VIRTUAL_DIRECTORY}', include('django.contrib.auth.urls')), path(f'{settings.VIRTUAL_DIRECTORY}', views.index, name='index'), path(f'{settings.VIRTUAL_DIRECTORY}aluno/', include('aluno.urls')), path(f'{settings.VIRTUAL_DIRECTORY}empresa/', include('empresa.urls')), ] -
How to solve this djando OneToOneField model error?
I'm trying to make a model that needs a relationship of one to one with a feedstock that is used by a plenty of formulas. This is my code: from django.db import models from dashboard.models import Formulas, Feedstock class FeedstockFormulas(models.Model): ratio = models.FloatField() feedstock = models.OneToOneField(Feedstock, on_delete=models.CASCADE, default="0") formulas = models.ForeignKey(Formulas, on_delete=models.CASCADE) This is the error I'm getting: Traceback (most recent call last): File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 798, in __init__ to._meta.model_name AttributeError: module 'dashboard.models.Feedstock' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/__init__.py", line 1, in <module> from .Formulas import Formulas File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/Formulas.py", line … -
Django Regex Validator Not Working - Error 500 Deployment Server
Take the following example: class ProjectForm(forms.Form): client = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Client Name (lowercase)'}),validators=[RegexValidator(r'^[a-z]+$', 'Enter a valid client name (only lowercase letters)')]) stage = forms.ChoiceField(choices=TYPES) folder = forms.ChoiceField(choices=FOLDERS, required=False, label='') purpose = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Project Purpose (lowercase; digit optional)'}),validators=[RegexValidator(r'^[a-z-]+[1-9]?$', 'Enter a valid purpose (only lowercase letters, with a single optional digit)')]) computeapi = forms.BooleanField(required=True, initial=True, label='Compute Engine') deploymentmanapi = forms.BooleanField(required=False, label='Deployment Manager') storagecompapi = forms.BooleanField(required=False, label='Storage Components') monitorapi = forms.BooleanField(required=False, label='Monitoring') loggingapi = forms.BooleanField(required=False, label='Logging') def clean(self): form_data = self.cleaned_data projectname = form_data['client'] + "-" + form_data['stage'] + "-" + form_data['purpose'] client = form_data['client'] purpose = form_data['purpose'] for projectdict in projectdicts: if projectname == projectdict['name']: raise ValidationError(projectname + " already exists! Please try another name.") if not re.match("^[a-z-]+[1-9]?$", purpose): raise ValidationError(purpose + " does not comply with the Regex parameters.") if not re.match("^[a-z]+$", client): raise ValidationError(client + " does not comply with the Regex parameters.") return form_data The ValidationError for projectname works perfectly fine as expected. However, it's not working for Regex, and instead keeps throwing a 500 error. Is there something we need to do specifically to get the RegexValidator to work as expected within the class variables? I don't believe my additional code in the clean is needed (and if it … -
AttributeError at /add/4/ 'Item' object has no attribute 'filter'
I'm getting error AttributeError at /add/4/ 'Item' object has no attribute 'filter' at if order.item.filter(item__id = item.id).exists(): I'm trying add Items based on the ids in to cart. The item is being added in the cart table but showing above error. my views.py @login_required(login_url='/login/') def add_to_cart1(request, id): item = get_object_or_404(Item, id=id) order_item, created = CartItem.objects.get_or_create( item=item, user=request.user, ) order_qs = CartItem.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.item: if order.item.filter(item__id = item.id).exists(): order_item.quantity += 1 order_item.save() messages.success(request, "Item qty was updated.") return redirect("ItemAddedToCart") else: order.item.add(order_item) messages.success(request, "Item was added to your cart.") return redirect("ItemAddedToCart") else: order = CartItem.objects.create( user=request.user, ) order.item.add(order_item) messages.success(request, "Item was added to your cart.") return redirect("ItemAddedToCart") my models.py class CartItem(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) item = models.ForeignKey(Item, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True ,null=True) updated_at = models.DateTimeField(auto_now=True ,null=True) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) -
Update django form maintaining expiration time
this is my first post on this life-saving community. I recently started studying django, using 3.1 right now. My main problem is about maintaining a field from a form after the update. Using: form = TodoForm(request.POST, instance=todo) I can see all the fields, except from the expire one in wich i see dd/mm/yyyy (the default from the date picker) At the moment, to take expire field, I use bootstrap_datepicker_plus. Do you need more code to see what I'm doing wrong? Any idea? -
Python calling a function that creates directory does not work as expected
I am calling a function inside my Django view. The code works but not when calling the function inside the view. I have simplified the code. import os def MakeDir(path): try: os.mkdir(path) #... some more logic... except OSError as e: print(e) def MydjView(request): MakeDir('/tmp/year') #function call but directory is not created return HttpResponse('okay') -
Django: UpdateView for Double Nested Forms
I currently have an error with writing UpdateView for double nested forms. My architecture is comprised of one template containing one form and two formsets. There's a large form for publisher. Someone can then add as many author formsets as they want and as many book formsets to each author as they want. So it looks like: Publisher -> Author1, Author2, Author3, ... Author1 -> Book1, Book2, Book3 Author2 -> Book4 Author3 -> Book5, Book6 Again, this is all listed in one create.html template. I wrote this using CreateView and it works fine. Now with writing UpdateView, I redirect to my html template for the creation of the forms and can correctly populate the form with data for publisher and author. However, when I try to populate the form with the book data, it populates every author instance with the same book instances rather than populate each author instance with their matching book instances. So it looks like: Publisher -> Author1, Author2, Author3, ... Author1 -> Book1, Book2, Book3 Author2 -> Book1, Book2, Book3 Author3 -> Book1, Book2, Book3 My models.py looks like : class Publisher(models.Model): name = models.CharField(max_length=255, unique=True) class Author(models.Model): name = models.CharField(max_length=255, unique=True) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) … -
The session is idle and there is no current transaction pgAdmin - Django
I'm really new in Postgres and PgAdmin. I'm trying to import new attributes in to my database class from Django project. This project is connected to pgAdmin Postgres. The problem is when I make migrations and migrate from django, this news attributes doesn't impact my database in pgAdmin. I see my migrations files in django project and the migration is successful, but when I see pgadmin it shows this message The session is idle and there is no current transaction pgAdmin I have searched in google but there is no so much information, so I really will appreciate your help. -
Django Rest Framework: How to filter only Many2Many data that matches the conditions
I have many related models and serializers and I want to return only the filtered result (including nested content). models.py class Screen(models.Model): title = models.CharField(max_length=100) class Item(models.Model): screen = models.ForeignKey(Screen, related_name='items', on_delete=models.CASCADE) title = models.CharField(max_length=100) class Card(models.Model): item = models.ForeignKey(Item, related_name='cards', on_delete=models.CASCADE) title = models.CharField(max_length=100) settings = models.ManyToManyField('Settings') class Settings(models.Model): sdk = models.IntegerField(default=1) drm = models.BooleanField(default=False) serializers.py class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ['sdk', 'drm'] class CardSerializer(serializers.ModelSerializer): settings = SettingsSerializer(many=True, read_only=True) class Meta: model = Card fields = ['id', 'title', 'settings'] class ItemSerializer(serializers.ModelSerializer): cards = CardSerializer(many=True, read_only=True) class Meta: model = Item fields = ['id', 'title', 'cards'] class ScreenDetailSerializer(serializers.HyperlinkedModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = Screen fields = ['id', 'title', 'items'] views.py class ScreenDetail(generics.RetrieveAPIView): serializer_class = ScreenDetailSerializer def get_queryset(self): qs = Screen.objects.all() params = {} settings_params = {} cards_params = {'settings__isnull': False} items_params = {'cards__settings__isnull': False} sdk = self.request.query_params.get('sdk', None) if sdk: params['items__cards__settings__sdk'] = sdk settings_params['sdk'] = sdk qs = qs.prefetch_related( Prefetch('items', queryset=Item.objects.filter(**items_params).distinct().prefetch_related( Prefetch('cards', queryset=Card.objects.filter(**cards_params).distinct().prefetch_related( Prefetch('settings', queryset=Settings.objects.filter(**settings_params).distinct()) )) )) ) return qs.filter(**params).distinct() Example of not filtered JSON: { "id": 1, "title": "Фильмы", "items": [ { "id": 1, "title": "Лучшие ужастики", "cards": [ { "id": 1, "title": "Проклятье Анабель", "settings": [ { "sdk": 1, "drm": true … -
Submiting multiple (unrelated) forms django, ajax same view same page
I'm trying to submit more than four forms in the same view and template in Django, each unrelated to the other. the challenge is that only one form is submitting successfully, while nothing happens to the other forms, Is there a way I can effectively solve this problem without having separate views for each form using ajax or? Here is my views.py def course_options(request): option1form = Choice1Form() option2form = Choice2Form() option3form = Choice3Form() educhoiceform = EduchoiceForm() if request.is_ajax(): option1form = Choice1Form(request.POST) option2form = Choice2Form(request.POST) option3form = Choice3Form(request.POST) educhoiceform = EduchoiceForm(request.POST) print(request.POST) if option1form.is_valid(): Choice1 = option1form.save(commit=False) Choice1.user = request.user option1form.save() return JsonResponse({ 'message': 'success' }) if option2form.is_valid(): Choice2 = option2form.save(commit=False) Choice2.user = request.user option2form.save() return JsonResponse({ 'message': 'success' }) if option3form.is_valid(): Choice3 = option3form.save(commit=False) Choice3.user = request.user option3form.save() return JsonResponse({ 'message': 'success' }) if educhoiceform.is_valid(): Educhoice = educhoiceform.save(commit=False) Educhoice.user = request.user educhoiceform.save() return JsonResponse({ 'message': 'success' }) return render(request, 'applyBugema/select.html', {'option1form': option1form, 'option2form': option2form, 'option3form': option3form, 'educhoiceform': educhoiceform}) template.html <div class="card2 card border-0 px-4 py-1" style="background-color: #e9ecef;"> <h2>Select courses you'd like apply for</h2> <hr> </div> <div class="row d-flex"> <div class="card2 card border-0 px-4 py-3" style="background-color: #e9ecef;"> <form method="POST" class="post-form" id="form">{% csrf_token %} {{ option1form|crispy }} <!-- <button type="submit" class="btn btn-outline-info">First … -
How do I render HTML returned from a filter in django template?
I have a md file which needs to be converted into html (for blog website). The filter (markdownify) converts md file into html tags. Now, html tags are shown on the website. How do I render this html on website (in django template). Is there any filter to do so? Or is there any other method to convert md into html in django? Code -> <p>{{ post.body | markdownify }}</p> md file -> ### h1 header *jh* * sdfs * ksdjfh * skdjkfhsk [link] (#) The output in web page: h1 header <em>jh</em> sdfs ksdjfh skdjkfhsk [link] (#) -
Delete records from 2 tables in join with Django ORM
I am using Django and have 2 tables and I want to delete records from the join. These are simplified model definitions: from django.db import models class MyModelA(models.Model): created = models.DateTimeField(null=True, blank=True) class MyModelB(models.Model): modela = models.OneToOneField( MyModelA, on_delete=models.DO_NOTHING, db_constraint=False ) created = models.DateTimeField(null=True, blank=True) If I used SQL, I could write a DELETE statement with a join, which would delete all records that are returned by the join like this: DELETE a, b FROM mymodela AS a INNER JOIN mymodelb AS b ON a.id = b.modela_id WHERE a.created < '<some date>' I would like to use the Django ORM and the delete() method. I could easily write the SELECT equivalent using: MyModelA.objects.filter(mymodelb__isnull=False) .filter(created__lt=<some date>) .select_related("mymodelb") However, when I chain the delete(), only records in MyModelA are deleted and the resulting SQL-query is something like this: DELETE FROM mymodela WHERE mymodela.id IN (<LIST OF IDs in JOIN>) I could of course use a different on_delete action or get the list of ids and delete the records table by table, but I would like to know: is it possible to get a DELETE a, b FROM... statement as shown above? -
How can pass my data into this particular serializer?
I'm currently working with data that looks like: { "events": [] } But, I'd like to transform it to: { "events": "added-to-calendar": [], "confirmed": [] } I've written out a serializer that looks like: class CalendarFeedSerializer(serializers.Serializer): """ Serializer for the Calendar Feed """ added_to_calendar = EventSerializer(many=True, read_only=True) confirmed = EventSerializer(many=True, read_only=True) class Meta: model = Event But, I'm not entirely sure how to pass my data into this Serializer. Here's the ListAPIView that I am working with to achieve { "events": [] }: class CalendarFeedView(generics.ListAPIView): serializer_class = serializers.EventSerializer def get_queryset(self): user = get_user_model().objects.get(id=self.request.user.id) added_to_calendar_events = user.events_in_calendar() confirmed_events = user.events_confirmed() return added_to_calendar_events | confirmed_events But, as you can see, I am using the base EventSerializer that I created to transform this list of Event's. What I want, is to somehow pass added_to_calendar_events and confirmed_events to my CalendarFeedSerializer so that I can have the desired data structure { "events": "added-to-calendar": [], "confirmed": [] } -
Retrieve Data From Database and display in HTML forms through AJAX in django
recently I'm working on blog application using django framework.Right now I dont know how to retrieve data from database through ajax in HTML form.For example if user wants to edit his own post the page will redirected to blog_post page along with his old published post.I want to set that published data to blog_post page.So whenever the user go for edit the post the published post would be already mentioned and user can edit them easily. Here is my code, blog_post.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Clean Blog - Start Bootstrap Theme</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> </head> <body> <!--- --- Here is my ajax which I had tried ----- --- !> {% for i in blogs %} <script> $(document).ready(function(){ setInterval(function () { $.ajax({ type : "post", url : "{% url 'edit_post' %}", data: { "blogger" : {{ … -
How to update/create new jwt after user changed username
I use JWT(JSON Web Token) in my project(backend: Django), now I allow user to change his/her username. As we known, after user changed username, the token will invalid(since the token(payload) include the username info, so the current local saved token cannot be used further). Then what we can do? Logout? and let user re-login? create new jwt? but how to do this since backend don't have the password(as I know, password is needed to create new jwt). -
How to avoid to resend data and update page in django forms?
I have a modal form which is displayed clicking some buttons. When the user fill the form and submit it i can save the data and redirect the user to and index page. If the user return on the previous page he see the "old" form already filled, because the page isn't refreshed. What can i do? This is my wiew: def calendar(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = ReservationForm(request.POST) # check whether it's valid: print('prima del form valid') if form.is_valid(): print("il form e' valido") reservation = form.save(commit=False) reservation.validation_code = get_random_string(length=32) reservation.delete_code = get_random_string(length=8).upper() reservation.reservation_confirmed = False reservation.save() return redirect('prenotazionicampo:index') # return render(request, 'prenotazionicampo/index.html') else: print(form.errors) # if a GET (or any other method) we'll create a blank form else: form = ReservationForm() -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Please give me a solution
Exception happened during processing of request from ('127.0.0.1', 63281) Traceback (most recent call last): File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 720, in init self.handle() File "D:\customerApplication\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "D:\customerApplication\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
TypeError in view: Field expected a number but got SimpleLazyObject
I upgraded to django v3.1 and suddenly getting this error: Field 'id' expected a number but got <SimpleLazyObject: '23'>. The failing line of code is this: my_obj = get_object_or_404(MyModel, pk=kwargs.get('pk')) Any ideas what I might be doing wrong? Thanks!