Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework OAuth2 Access Token Guidance Required
I'm trying to implement OAuth and jwt token login in Django Rest Framework for practice. I'm using social-auth-app-django and djangorestframework_simplejwt. I use the basic documentation and successfully created a user using GitHub (Checked that in Django Admin) and I also created a user using Simple CreateAPIView. For login purposes, I can use simple jwt to login and retrieve the access token to call the other authenticated APIs, but how can I do the same using an OAuth logged-in user account. Another problem I'm facing is, whenever to visit http://localhost:8000/api/auth/login/github/ in the browser is prompts my login screen, after login, it redirects me to http://localhost:8000/api/auth/complete/, which returns 404 because it's not the right endpoint as per the Django default error page. It represents api/auth/complete/<str:backend>/ [name='complete'] as one of the available endpoint. When I visit /api/auth/complete/github/ the error that comes up is AuthMissingParameter at /api/auth/complete/github/. I don't have any idea what is happening. My settings.py configurations are: INSTALLED_APPS = [ --- # Plugins "rest_framework", "corsheaders", "oauth2_provider", "social_django", "rest_framework_social_oauth2", --- ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework_social_oauth2.authentication.SocialAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } AUTHENTICATION_BACKENDS = ( "rest_framework_social_oauth2.backends.DjangoOAuth2", "django.contrib.auth.backends.ModelBackend", "social_core.backends.github.GithubOAuth2", "social_core.backends.spotify.SpotifyOAuth2", "django.contrib.auth.backends.ModelBackend", ) -
Updating model with signals
now i'm trying to update field from my model with help of post_save signal. All works well in the admin page, but the field "number_of_photos" updates only after i click save button in the second time. Why is this happening? Signal code: @receiver(post_save, sender=PhotoAlbum) # noqa def count_photos(sender, created, instance, *args, **kwargs): # noqa instance.number_of_photos = instance.photos.count() signals.post_save.disconnect(count_photos, sender=PhotoAlbum) instance.save() signals.post_save.connect(count_photos, sender=PhotoAlbum) -
how to render data in django template that has been queried in backend using "__contains"
I am using django multiselect field in my model that is used to upload cases. Now I have a field in my model where the admin can select multiple categories for the same case. I have seperate pages to render this data according to the categories selected for them. I am filtering the data like this views.py law_data= Laws.objects.all().filter(sub_law_type__contains = 'ipc').order_by('-date') for law in law_data: print("\n these are the available cases : ", law.title," with sub law types : ", law.sub_law_type, "\n") return render(request, 'citation_ipc.html', {'law_data': law_data} ) here I want to filter all the cases that has ipc in it. And the result I am getting is this, which is accurate these are the available cases : dfsdf with sub law types : ipc, pocso, pmla, ni_act these are the available cases : dfgdfg with sub law types : ipc Now I am trying to render out this data in my html like this html <div id="sclimitations" class="tabcontent"> {% for data in law_data %} {% if data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} <div class="tab"> <div class="judge-content"> <a class="judge-ttle" href="{% url 'doc' data.pk %}">{{data.title|safe}} &nbsp <i class="fas fa-external-link-alt"></i></a><br/><br/> <p> <strong> {{data.sub_title|safe}} </strong> </p> <div … -
How to run my local django server using poetry
I am new to python/django and I am coming into an existing codebase that uses the package manager poetry. My question is simple; how do I start my local django server using poetry run? If not using poetry I understand I can just use python manage.py runserver, but when I run that in my project, I get ImportError: No module named django.core.management. The other most relevant command I ran was poetry run python manage.py runserver, but that yielded ModuleNotFoundError: No module named 'django_q'. I am literally just trying to figure out how to run poetry commands, and in this instance, start my local django server. I am decently lost, so any help with django/poetry would be very helpful. Thank you all in advance! -
Can not create super user, because foreign key can not be null
How to assign foreign key value, when creating super user in Django? I want to make new superuser using python manage.py createsuperuser command, but I get an error: ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. Here is the code: class CompanyAccountType(models.Model): accountTypeName = models.CharField(max_length=50) accountTypeValue = models.IntegerField() class Company(models.Model): city = models.ForeignKey(City, on_delete=models.RESTRICT) category = models.ForeignKey(Category, on_delete=models.RESTRICT) companyAccountType = models.ForeignKey(CompanyAccountType, on_delete=models.RESTRICT) class MyAccounManager(BaseUserManager): def create_user(self, username, password): user = self.model( username=username, ) #I tried this for testing (real I would like to send id throught request), but I get error #ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. companyObj = Company.objects.filter(id=1) user.company = companyObj user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): user = self.create_user(username=username, password = password, ) #user.company.id = 1 user.save(using=self._db) return user class Worker(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default="user") password = models.CharField(max_length=300, default="password") company = models.ForeignKey(Company, on_delete=models.RESTRICT) #blank=True workerName = models.CharField(max_length=50) workerProfileImage = models.ImageField(upload_to='images/', default = "images/defaultUser.png", null = True) USERNAME_FIELD = 'username' #REQUIRED_FIELDS = ['company'] objects = MyAccounManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -
Download multiple files as zip in Django shows memory error
I am trying to download multiple files as a zip in Django. It works well when file sizes are small. If the file size is more than 1GB, it's showing memory error: Traceback (most recent call last): x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write x-xxx-xx: shutil.copyfileobj(src, dest, 1024*8) x-xxx-xx: File "/usr/lib64/python3.7/shutil.py", line 82, in copyfileobj x-xxx-xx: fdst.write(buf) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1131, in write x-xxx-xx: self._fileobj.write(data) x-xxx-xx: MemoryError x-xxx-xx: During handling of the above exception, another exception occurred: x-xxx-xx: Traceback (most recent call last): x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner x-xxx-xx: response = get_response(request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response x-xxx-xx: response = self.process_exception_by_middleware(e, request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response x-xxx-xx: response = wrapped_callback(request, *callback_args, **callback_kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner x-xxx-xx: return view(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled x-xxx-xx: response = viewfunc(request, *args, **kw) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view x-xxx-xx: return view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/current/fileupload/views.py", line 519, in downloadScanView x-xxx-xx: zf.write(tmp.name, zip_path) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write … -
ignore fields on update view
I have a very large form that I have an update view for. The issue is when the users submits an update it says some fields are required such as author and post date. I don't want users to change these fields. The fields are manually rendered How can I ignore these fields in the update view. I have tried to set the requirements to false def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['author'].required = False self.fields['date_posted'].required = False But this throws a null value in column "author" of relation "blog_post" violates not-null constraint Alot of posts said to add null=True but these fields cannot be null view: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post form_class = PostFormUpdate def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False form: class PostFormUpdate(ModelForm): class Meta: model = Post fields = '__all__' -
ImportError : cannot import name 'ugettext_lazy'
I'm trying to install suit, I entered this command : pip install https://github.com/darklow/django-suit/tarball/v2 and wrote this code : from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig) : layout = 'horizontal' And added it : INSTALLED_APPS = [ 'products.apps.SuitConfig', .....] But when I added this last code I had this error : InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'suit.templatetags.suit_menu': cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\hp\environments\env3\lib\site-packages\django\utils\translation_init_.py) note : django 4.01 -
Stripe 'card-element' isn't visible (Python/Django)
this is my first time using this site to ask a question. I'd appreciate the help, I have to turn in this bit of the project today as part of my course :( I'm following this tutorial: https://www.youtube.com/watch?v=ncsCnC3Ynlw (chapter: stripe elements) When I visit my checkout page, the card element isn't showing up. I am at the stage around 3:45:00, and when looking at the checkout, the div for the card element is just a thin, empty bar. Could anyone help me find where I made a mistake? I think it might be the connection between the script and the template or just the script itself, but I'm losing my mind trying to figure out what I've done wrong. My views.py: def BasketView(request): carrinho = Carrinho(request) total = str(carrinho.gettotal()) total = total.replace('.', '') total = int(total) stripe.api_key='sk_test_[...]' intent = stripe.PaymentIntent.create( amount=total, currency='brl', metadata={'integration_check': 'accept_a_payment', 'userid': request.user.id} ) return render(request, 'pedido/pedido_novo.html', {'client_secret': intent.client_secret}) My html template: {% load static %} {% block title %}Livraria Aquaflora | Novo Pedido{% endblock %} {% block adtscripts %} <script src="https://js.stripe.com/v3/"></script> <script src="https://unpkg.com/imask@6.0.7/dist/imask.js"></script> <script src="{% static 'js/orderform.js' %}"></script> <script src="{% static 'js/payment.js' %}" data-rel-js></script> {% endblock %} {% block conteudo %} <div class="container-fluid"> <div class="row no-gutter"> … -
How to get all objects with certain interval of time in django
I want to get all objects which has time to live next 5 seconds with django python ORM. I'm trying in a following way and I don't know why that is not working or what i'm doing wrong... def ttl_expire_list(self): query = self.filter(is_remove=False,ttl__range=[timezone.now() + timedelta(seconds=5), timezone.now()]).order_by("-ttl") # query = self.filter(is_remove=False).order_by("-ttl") return query' -
Django how to find if the object is referenced by ForeignKey from another class in model.py
I have two classes shown below, I wanted to add a function to File to check if the file is referenced by any data inside the Project class (similar how "was published recently" is done here: https://docs.djangoproject.com/en/4.0/_images/admin12t.png ). class File(models.Model): def __str__(self): return self.name file = models.FileField(upload_to='uploads/') class Project(models.Model): def __str__(self): return self.name project = models.ForeignKey(Project, on_delete=models.CASCADE) -
Index not being used for django desc
I have a django model with the following indexes: class Meta: indexes = [ models.Index(fields=['-current']), models.Index(fields=['current']), ] These were added and I ran the migration and saw the results: companies/migrations/0294_auto_20220110_1155.py - Create index companies_c_current_f2c815_idx on field(s) -current of model company - Create index companies_c_current_c8bcb7_idx on field(s) current of model company I've found that running a django-rest-framework query with ordering=current is ~5x faster than with ordering=-current. Using PSQL explain I get the following: # explain select * from company order by current desc nulls last limit 100; QUERY PLAN -------------------------------------------------------------------------------------------------------- Limit (cost=41028.75..41040.42 rows=100 width=1223) -> Gather Merge (cost=41028.75..68747.19 rows=237570 width=1223) Workers Planned: 2 -> Sort (cost=40028.73..40325.69 rows=118785 width=1223) Sort Key: current DESC NULLS LAST -> Parallel Seq Scan on companies_company (cost=0.00..35488.85 rows=118785 width=1223) (6 rows) # explain select * from company order by current asc nulls last limit 100; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------ Limit (cost=0.42..49.79 rows=100 width=1223) -> Index Scan Backward using companies_c_current_f2c815_idx on companies_company (cost=0.42..140727.06 rows=285084 width=1223) (2 rows) It seems clear from the above that the asc is using the index while the desc is not, which explains the time difference. My question is: why not? Is there a different way the index needs to be added to make sure … -
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name. I´m trying to make an search engine for my website in django, via views.py, but Django always says that there's an exception in views.py Views.py def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entries(request, entry): if entry not in util.list_entries(): raise Http404 content = util.get_entry(entry) return render(request,"encyclopedia/entry.html", {"title": entry, "content": Markdown().convert(content)}, ) def search(request): query = request.GET.get("q", "") if query is None or query == "": return render( request, "encyclopedia/search.html", {"found_entries": "", "query": query}, ) entries = util.list_entries() found_entries = [ valid_entry for valid_entry in entries if query.lower() in valid_entry.lower() ] if len(found_entries) == 1: return redirect("entry", found_entries[0]) return render( request, "encyclopedia/search.html", {"found_entries": found_entries, "query": query}, ) But Django says: "if len(found_entries) == 1: return redirect("entry", found_entries[0]) have an "NoReverseMatch" error" Urls.py from django.urls import path from . import views, util urlpatterns = [ path("", views.index, name="index"), path("entries/<str:entry>", views.entries, name="entries/{{ entry }}"), path("search/", views.search, name="search"), ] handler404 = 'encyclopedia.views.error_404_view' Layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a … -
How could i redirect a user to a specific primary key
Good evening everyone, I am writing a forum where there are different rooms, in each room a user can leave a comment and also update it as needed. After updating the comment, i want to redirect the user to the same room where this comment was. I tried: 1.Reverse + HTTPResponseRedirect def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('created') participants = room.participants.all() if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room': room, 'room_messages': room_messages, 'participants': participants,} return render(request, 'base/room.html', context) @login_required(login_url='login') def updateMessage(request, pk): message = Message.objects.get(id=pk) form = MessageForm(instance=message) if request.user != message.user: return HttpResponse('Unable to edit message') if request.method == 'POST': form = MessageForm(request.POST, instance=message) if form.is_valid(): form.save() return HttpResponseRedirect( reverse( "room", kwargs={ "pk": "13" } ) ) return render(request, 'base/message_form.html',{'obj':message, 'form': form}) but it's working out to return the user only when I manually write the id of the room in which the comment is. Is there a way to bind the id of the comment and the id of the room? I tried to search for similar material and looked for similar projects on github repos, but I can't figure out how to do it, the … -
NGINX serve static files - django project has no styling
I managed to deploy my Django app but I can not pass the static files with Nginx. I have followed all the instructions for deploying to production. When I inspect the page all I see is empty static folder Can anyone spot the mistake? Thanks a lot nginx.conf 10 upstream app_upstream { 9 server app:8080; 8 } 7 6 server { 5 listen 80; 4 listen 443; 1 server_name #######; 2 3 location /static/ { 4 alias /static/; 5 } 6 7 location /media/ { 8 alias /media/; 9 } 10 11 location / { 12 proxy_set_header Host $host; 13 proxy_pass http://app_upstream; 14 } 15 } settings.py 14 13 STATIC_URL = '/static/' 12 STATIC_ROOT = '/static/' docker-compose.yml .... 12 app: 13 build: . 14 ports: 15 - 8000:8000 16 - 8080:8080 17 env_file: 18 - db_${RTE}.env 19 volumes: 20 - .:/app/ 21 - static:/static/ 22 - media:/media/ 23 depends_on: 24 - db 25 26 nginx: 27 build: nginx/ 28 ports: 29 - 443:443 30 - 80:80 31 volumes: 32 - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/ 34 - static:/static/ 35 - media:/media/ 36 depends_on: 37 - app 38 39 volumes: 40 static: ... Error message when I docker-compose: nginx_1 | 2022/01/10 16:26:17 [error] 10#10: *8 … -
How to resolve an Import error when using markdownx with Django?
I'm attempting to use markdownx in my code and keep getting an error when running migrations/runserver as shown in extract below: https://i.imgur.com/lzWkM9r.png I've done some searching and everything I have found lists the steps as: pip install django-markdownx Reference in urls.py & settings use in code - models/views py update migrations & run my code currently: settings.py https://i.imgur.com/74n6rPn.png main urls.py (cookbook is app name) https://i.imgur.com/fXIez51.png app/models.py https://i.imgur.com/cJVwBuq.png package versions https://i.imgur.com/t7n5ukS.png The link I have been referencing as a tutorial is: https://dev.to/vladyslavnua/how-to-build-a-django-web-app-from-scratch-tutorial-5bp0 If I comment out the path line relating to the markdownx in main urls.py all works except for a missing import error embedded in page and in server console ' "POST /markdownx/markdownify/ HTTP/1.1" 404 3590 Not Found: /markdownx/markdownify/' I've not used markdownx previously so not sure how to resolve; any help greatly appreciated. Thanks -
Register button won't disappear when user logs in(django, html, css, bootstrap)
Why is this code showing the register button regardless of whether or not a user is logged in? (this is for Django with bootstrap) ''' {% if user.is_authenticated %} <li class="nav-item"> <span class="navbar-text"}">Study hard, {{ user.username }}.</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'users:register' %}">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:login' %}">Log in</a></li>''' -
Django displays source code instead of web page
I am new to django. Any help will be appreciated. It displays source code instead of web page. To be specific the base page (base.html). What I want is to use the data from patient details and doctors detail as they are from different groups. I think that the problem is when i pass my dictionary. Views.py def booking(request): if not request.user.is_active: messages.success( request, ("In order to book an appointment you must login first")) return redirect('login') doctor_details = Doctor.objects.all() f = {'doctor_details': doctor_details} g = request.user.groups.all()[0].name if g == 'Patient': patient_details = Patient.objects.all().filter(EmailAddress=request.user) d = {'patient_details': patient_details} return render(request, 'booking.html', f, d) Html {% extends 'base.html' %} {% block content %} {% load static %} <div class="loginContainer"> <div class="img"> <img src="{% static 'image/booking.svg' %}"> </div> <div class="login-content"> {% for d in patient_details %} <form method="POST" id="signupForm"> {% for f in doctors_details %} {% csrf_token %} <h2 class="title">Booking form</h2> <div class="input-div one"> <div class="i"> <ion-icon name="person-circle"></ion-icon> </div> <div class="div"> <h5>Patient ID: PID - {{d.id}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="person"></ion-icon> </div> <div class="div"> <h5>Name: {{d.FirstName}} {{d.LastName}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="business"></ion-icon> </div> <div class="div"> <h5>Department</h5> <input type="text" class="input" name="age" required> </div> </div> <div class="input-div … -
Save multiple objects in Django DRF ViewSet create
I have a model in Django which stores some basic information. class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) manufacturer = models.ForeignKey(InventoryManufacturer, on_delete=models.PROTECT) comment = models.TextField(max_length=500, blank=True, null=True) link = models.URLField(max_length=100, blank=True, null=True) class Meta: unique_together = ('manufacturer', 'manufacturer_part_no') I have another table which stores images for this model: class InventoryImages(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) file = ImageField(blank=True, default='', upload_to='inventory/images/%Y/%m/') primary = models.BooleanField(default=False) order = models.IntegerField(blank=True, null=True) item = models.ForeignKey(Inventory, on_delete=models.CASCADE, blank=True, null=True, related_name='images') What is the right way to handle a scenario where a user can fill out a form (where you can set the Inventory model fields) and also upload multiple images. What I did now that the user can upload images everytime on this form, the image gets uploaded but the item Foreign Key stays null. When the user submits the form, the ForeignKey is set for each uploaded image. The scenario when a image gets discarded (no form submission) is handled. This is what I did now: def create(self, request, *args, **kwargs): # Create Inventory item serializer = CreateInventoryItemSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(added_by=self.request.user, updated_by=self.request.user) # Save properties inventory_id = serializer.data['id'] # Add id … -
Django - convert datetime string to timezone aware datetime object
So I have a a list of dates and times as a string "2022-01-23 21:30” that I need to import into my Django Application My Django server UTC, however the strings are intended to be UTC+2. So if I import it directly, Django would assume it’s UTC and then the timestamp would saved as 2022-01-23 21:30 (UTC), where in reality it should be converted to 2022-01-23 19:30 (UTC). Is there a specific way I should format it before saving the object in a Django DateTimeField so it will become timezone aware? Thanks in advance. -
formset function update view does not save the forms because the id is missing
I have a view to update 6 of my formset only that the click of the send button gives me the error that the id of each form is missing ... how do you fix it? When I have to create formset there are never problems with the id... Can anyone tell me where I'm wrong? I leave my code below view @login_required def PianoSingleUpdateView(request, id): piano = models.Piano.objects.get(single_piano__id = id) piano_sett = models.PianoSingleDay.objects.get(id = id) dato = models.PianoDay.objects.filter( piano_day = piano_sett) DatiFormSet = modelformset_factory(models.PianoDay, extra = 0, fields=('id', 'kcal', 'carboidrati', 'proteine', 'grassi')) if request.method == 'POST': dati_formset = DatiFormSet(request.POST, request.FILES, queryset = dato) if dati_formset.is_valid(): for dato in dati_formset: dato.save() return redirect('gestione-piano', id = piano.id) else: dati_formset = DatiFormSet(queryset = dato) context = {'piano': piano, 'piano_sett': piano_sett, 'dati_formset': dati_formset} return render(request, 'crud/update/update_piano_giornaliero.html', context) models class Piano(models.Model): nome_piano = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente_piano = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente_piano' ) def __str__(self): return self.nome_piano class PianoSingleDay(models.Model): giorni_settimana_scelta = [ ("1","Lunedì"), ("2","Martedì"), ("3","Mercoledì"), ("4","Giovedì"), ("5","Venerdì"), ("6","Sabato"), ("7","Domenica") ] giorni_settimana = models.CharField( choices = giorni_settimana_scelta, max_length = 300 ) single_piano = models.ForeignKey( Piano, on_delete = models.CASCADE, related_name = 'single_piano' ) def __str__(self): return self.giorni_settimana class … -
Parse File While Upload in Django
May I know how to parse XML tags from XML files while upload in django ? I wanted to make sure below things :- Once I upload file from GUI i wanted to parse data from it and store somewhere in models in django and then land file in media storage directory -
CSRF cookie is not set in Django after API call
I have a small Django web app that allows you to log in with a platform using their API. The user is able to log in, but the callback from the log in returns this error: Forbidden (CSRF cookie not set.): /account/platforms/apicallback/ on my server output. I believe that the callback does route to the correct url in my web app, but when it gets to the view associated with it, the CSRF cookie error arises. My request code is below: params = { "app_name": "My App", "scope": scope, "user_id": request.user.id, "return_url": redirect_uri, "callback_url": "https://www.myapp.co.uk/account/platforms/apicallback", "state": {"platform":"api"} } query_string = urlencode(params) url = "%s%s?%s" % (auth_url, query_string) return redirect(url) Here is the urls.py file that contains the callback url: urlpatterns = [ path(r'apicallback/', views.apicallback, name='apicallback'), ] Here is the views.py file with the view for the callback url: @login_required def apicallback(request): consumer_key = request.GET.get('consumer_key') consumer_secret = request.GET.get('consumer_secret') I have got two APIs already working with my web app that both use OAuth2.0, and I haven't come into this issue before. Any ideas on how to fix it without disabling CSRF cookies. Thank you -
Can not use POST method with Django 4 Rest Framework
I'm having an issue with a new django 4 app not processing or not allowing POST method. I used to bypass this in Django version 3 by adding a trailing slash "/" to the end of url in Postman API Tester like http://127.0.0.1:8000/api/didipay/ instead of http://127.0.0.1:8000/api/didipay . But now in my Django 4 API I completed the url with the slash but POST method is still not processing the data. It gives me a "500 internal server error" and I don't understand where it is coming from. The GET method is rather giving an empty array which is normal because I've not inserted any data yet in the database. I'm using venv, Django 4 Rest framework, serializer, viewSet and these is my models and API urls configurations: //Serialize.py from rest_framework.decorators import permission_classes from didipay_app.models import Didipay_app from rest_framework import viewsets, permissions from .serializers import Didipay_appSerializer class Didipay_appViewSet(viewsets.ModelViewSet): queryset = Didipay_app.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = Didipay_appSerializer // Project folder's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('didipay_app.urls')), ] // App folder's urls.py from rest_framework import routers, urlpatterns from .api import Didipay_appViewSet router = routers.DefaultRouter() router.register('api/didipay', Didipay_appViewSet, 'didipay') urlpatterns = router.urls The … -
Python Paramiko "exec_command" does not execute - Django
I am facing an issue with the Python Paramiko library in my Django Application This is a function I have written to create an SFTP connection: def createSFTPConnection(request,temp_pwd): ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) user = User.objects.get(username=request.user) ssh.connect(hostname=temp_host,username=user.username,password=temp_pwd,port=22) sftp_client=ssh.open_sftp() return ssh,user,sftp_client This just returns me the variable for ssh, the username, and sftp_client Then I execute a command on the remote server using this code - ssh,user,sftp_client=createSFTPConnection(request,temp_pwd) # passes the password on that server for the user for creating the connection cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" # executing a shell script by passing it 2 variables stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call print("stderr: ", stderr.readlines()) print("pwd: ", stdout.readlines()) Now, this code works fine and executes the script "temp.sh" on the remote server, but it takes a lot of time as I am returning stdin, stdout and stderr and printing them on the console But, since I don't want that I removed the readlines() calls from there making my code look like this - cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call But for some reason, this code just doesn't execute on the remote server after removing the readlines() calls Thus, making me think that exec_command …