Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering not working even through command is visible in CMD log
I am new to django, trying to use AJAX to move data from html to views.py via AJAX, something weird is happening, data is moving but the page is not changing, new page is not getting rendered. HTML CODE <div class="bodyclass"> {% csrf_token %} {% for account in accounts %} <div class=""> <div class="accountname"> <button onclick="submitform('{{ account}}')" class="btn btn-info accbtn " id="{{ account }}">{{account}}</button> </div> </div> {% endfor %} </div JS Code <script> function submitform(accname){ alert(accname); var csrf = document.getElementsByName('csrfmiddlewaretoken'); $.ajax({ type : 'POST', url : 'accounts', data:{ csrfmiddlewaretoken : csrf[0].value, 'accname': accname, }, }); alert('bye'); } </script> views.py def accounts(request): if request.user.is_authenticated: if request.method == 'GET': if request.user.is_superuser: account = AccountDescription.objects.all() else: account = UserAccount.objects.filter(user=request.user) return render(request, 'accounts.html',{'accounts':account}) elif request.method == "POST": print(request.POST) print(request.POST.get('accname')) return HttpResponseRedirect('/clientinfo') else: return HttpResponseRedirect('/login') also the cmd screenshot Kindly let me what wrong I am doing. also let me know if any more input is required. Thanks in advance. -
Django - What is better, creating a ImageField on DB or a string path?
i started programming on Django and needed to make an Image Upload, saving the imagepath. I have 2 options, save the image on the BD as an ImageField or Save the path where the image is saved. Which one is better? -
How do I allow the authenticated user to retrieve their API credential from the database automatically?
I am relatively new to Django and I am struggling how to go about a feature that I want to implement. For the feature, I need to get a set of secondary credentials (used to authenticate against third-party software API), hashing the credentials, and then storing it in the database. These creds can then be called by the authenticated user associated with those secondary credentials, unhashed, and then used to make the API connection. My question is, how do I allow the authenticated user to retrieve their API credential from the database automatically? Currently, I have a custom user model set up under a new app called users and in the models.py as: import uuid from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, unique_id, first_name, last_name, password, **other_fields): email = self.normalize_email(email) user = self.model( email = email, username = username, unique_id = unique_id, first_name = first_name, last_name = last_name ) user.set_password(password) user.save(user=self._db) return user def create_superuser(self, email, username, unique_id, first_name, last_name, password, **other_fields): email = self.normalize_email(email) user = self.model( email = email, username = username, unique_id = unique_id, first_name = first_name, last_name = last_name, password = password ) user.is_admin = True user.is_staff = … -
django site adminstration asking for CSRF Validation
I have been developing a django page and deployed the same on IIS. everything was working fine. there was no issue with CSRF validations. I then integrated the page in Sharepoint iframe and now I am facing an CSRF error. it is working fine via url but in iframe the site is not able to validate CSRF. I don't know what screenshots are required. let me know i will share accordingly. let know if someone faced the same issue and know how to resolve it. Thanks in advance. -
KeyError: 'Unable to find stateless DjangoApp called app'
Why the DjangoApp app can't be found? Given result After executing manage.py runserver in the console Django is starting properly but in case I'm calling http://127.0.0.1:8000/dash_simple/app1/ a KeyError was thrown: Django Version: 3.1.3 Exception Type: KeyError Exception Value: 'Unable to find stateless DjangoApp called app' Expected result After executing manage.py runserver in the console Django is starting properly and the related page is shown for http://127.0.0.1:8000/dash_simple/app1/ dash_simple/urls.py urlpatterns = [ path('', views.home, name='home'), path('app1/', views.app, name='app') ] dash_simple/views.py def home(request): return render(request, template_name='dash_simple/home.html') def app(request): return render(request, template_name='dash_simple/app1.html') dash_simple/templates/dash_simple/app1.html {% load plotly_dash %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App 1</title> </head> <body> <H1>I'm App 1</H1> <p> {% plotly_app name="app" %} </p> </body> </html> -
Data loss in an inline formset
I am developing an application which allows an administrator to create several projects and within those projects different tasks can go, the idea is that when the administrator creates a project within that form he can also assign multiple tasks, for this I am using inline formset because I feel That meets my needs, but I have a problem and it is that when I click the button to add more tasks, the select where are the types of tasks is lost. This is my template: This is my view: class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = 'users:login' template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = ProjectFormSet(self.request.POST) else: data['formset'] = ProjectFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super().form_valid(form) This is my template: {% extends "base.html" %} {% load materializecss %} {% load static %} {% block content %} <div class="container"> <div class="card"> <div class="card-content"> <h2>Agregar Proyecto</h2> <div class="col-md-4"> <form id="form-container" method="post"> {% csrf_token %} {{ form|materializecss }} <h2>Tareas</h2> <table> {{ formset.management_form }} {% for form in formset %} {% if forloop.first %} <thead> <tr> … -
Django Test with setting up DB extensions
For my project i'm using PostgreSQL with pg_trm and unaccented extensions that I enable by executing a script into the DB. Running tests results in error because the test database doesn't have those extensions, of course. How can I add those scripts into the test database before the migrations are applied? -
How to apply css classes to the TimeDurationWidget in Django
I am trying to apply css styling to my modelform. from durationwidget.widgets import TimeDurationWidget class WeightDistanceTimeModelForm(forms.ModelForm): weight = forms.DecimalField(widget=forms.NumberInput(attrs={'placeholder': 'Weight', 'class': 'form-control', 'step': 2.5})) distance = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'Distance', 'class': 'form-control'})) time = forms.DurationField(widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=True), required=False) My weight and distance fields are showing up how I'd like but does anyone know how I can apply a placeholder and class of form-control to each of hours, minutes and seconds. I can't seem to find any documentation that explains this anywhere. Alternatively, is there a better way to display this information? I have also tried adding the class directly into my template: <div class="form-control"> {{ form.time }} </div> But this didn't work either -
How to check certain headers exist in each request in Django Rest Framework?
I want to test api_key and secret against all requests of different models. Both fields exist in a table. I am using DefaultRouter which itself creates all CRUD based requests URLs. Will I need to create custom functions to check headers or there is some better way to do it? -
How to customize the selection form?
I have a model class Car(models.Model): class ModelChoise(models.IntegerChoices): Model_1 = 0 Model_2 = 1 Model_3 = 2 Model_4 = 3 name = models.TextField('Name') model_id = models.IntegerField('model id', choices=ModelChoise.choices, default=1) def __str__(self): return self.name And I created a form for it class CarForm(ModelForm): class Meta: model = ExtraUser fields = ['model_id'] I need to deduce both key and value from it {% for mykey,myvalue in form.model_id %} {{ mykey }} : {{ myvalue }} {% endfor %} <!-- Model_1 : 0 Model_2 : 1 Model_3 : 2 Model_4 : 3 --> How should I do it? I can only get the key. -
How would I be able to set an usb barcode scanner to compare the scanned id to the id in the database table in Django?
First of all, I'm pretty new to programming in general. I've been trying to learn Django/python. I've had an app in mind that i started building. The app would be used to track users coming in and exiting the building. The data that would be stored in the database is the User, date and time at the exact moment of entering/leaving the building, temperature, location of the building. Ok so I have my database set up with the tables. Now the User has an id which is represented in a barcode. The problem I have now is that I want to create a homepage that is empty with just a few words like: Please scan your barcode. And when the barcode is scanned I want the page to redirect to the form for adding a new database entry but is populated with the user data. I don't know how to do that, that's my problem here. -
Retrieve access_token subsequent to login with mozilla_oidc_connect
After I have logged in and authenticated a user with mozilla_django_oidc I need to subsequently use the access token to call an API. mozilla_django_oidc offers to store the access token in the session variable but this is insecure so I'd like to run a second call against the OIDC provider. I need to pull out the logic from OIDCAuthenticationBackend that will retrieve the access token in order to do the API call. I could re-authenticate but that sounds like it will be a pain. -
how to use django 3 with django-otp to send token sms using SMS service provider for user verification and redirecting to password reset form?
I have only been able to make the following changes in django code: settings.py: added along with other apps added in INSTALLED_APPS = [ ..... 'django_otp', 'django_otp.plugins.otp_totp', ] In additions to other middleware configurations, added: MIDDLEWARE = [ 'django_otp.middleware.OTPMiddleware', ] urls.py: from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice) urlpatterns = [ path('admin/', admin_site.urls), #otp app path('dadmin/', admin.site.urls), ] Then I ran: $ python3 manage.py migrate otp_totp --fake and runserver. Created a user and totp device. Scanned the qr code in google authenticator. Then tried logging in using the admin url to login for this new user. It asks for the token generated which I input, it says invalid token though user is authenticated. Seen other posts where the secret code needs to be converted to 32basecode etc, but don't know exactly and where to implement. What more code needs to be added to get this working? I will require detailed code and steps for my use case where i need to change the time for generating the code and send via sms using my service provider api and redirect to password reset form. Using django 3.1, django-otp 1.0.2 -
How to do MYSQL table partitioning in Django?
I need to do partitioning on the region field of my Street model.I want to have a table for each region (there are 10 different regions). I am using architect but it returns an error. Here is my model using architect : @architect.install('partition', type = 'range', subtype = 'integer', constraint = '1', column ='region') class Street(models.Model): region = models.PositiveSmallIntegerField(null=1) name = models.IntegerField() Here is the error : architect partition: error: unsupported partition range subtype "integer" in "Meter" model, supported range subtypes for "mysql" database are: date But what exactly I need is partitioning the table based on region field (streets in region 1, streets in region 2,... streets in region 10). Thanks a lot. -
Django Createview and redirect url to detailview
I'm looking to add a push buttom in my detailview for add some new documents or other stuff. I'm using a modal in ma detailview html which is vorking well. but when i click to submit form i'am not able to go back to my detailview ... my view.py class MissionsList(FilterView): pagination =22 model = Missions context_object_name = 'missions_list' template_name = 'missions/index.html' filterset_class = MissionsFilters # ADD YOUR filterset class ''' class MissionDetails(DetailView): model = Missions template_name = "missions/mission_detail.html" def get_context_data(self, **kwargs): context = super(MissionDetails, self).get_context_data(**kwargs) mission_pk = self.kwargs['pk'] documents = DocMission.objects.filter(mission = mission_pk) details= Missions.objects.filter(id=mission_pk) reservations = Reservation.objects.filter(mission = mission_pk) context['documents']=documents context['reservations'] = reservations return context class DocMissionsCreate(CreateView): template_name = 'missions/create_doc.html' form_class = DocMissionForm succes_url = reverse_lazy('mission_detail') ''' here my models.py ''' class Projets(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) commentaire = models.TextField() pi = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'projets' ordering = ["name"] def __str__(self): return str(self.name) class Missions(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) debut = models.DateField(blank=True, null=True) fin = models.DateField(blank=True, null=True) lieu = models.CharField(max_length=45, blank=True, null=True) navire = models.CharField(max_length=45, blank=True, null=True) nombre_participant = models.IntegerField(db_column='nombre participant') … -
Send email to user after password reset in django
I am using the Django native password reset functionality to reset account passwords. urls.py path('reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html', form_class=PasswordResetform), name='reset'), path('reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='account/reset_done.html'), name='password_reset_done'), path("reset/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(template_name='account/reset_confirm.html', form_class=PasswordResetConfirm), name='password_reset_confirm'), path("reset/complete", auth_views.PasswordResetCompleteView.as_view(template_name='account/reset_complete.html'), name='password_reset_complete'), now everything works fine, I get the password reset link in my email and when I open it I am able to reset my password, but after the user resets the password, I want to send them an email saying their password has been reset I tried to write an ajax function that is triggered when it goes to the 'password_reset_complete' template, but there I am unable to access the user's email or username. how do i retrieve the user's email or username in the 3rd or the 4th template of the password reset steps? -
Can't Upload Img Using concrete view django rest framework
Hope You Are Fine! How Can i Upload Img Using concrete view Django rest framework? i have a model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) headline = models.CharField(max_length=100, blank=True, null=True) maiden_name = models.CharField(max_length=100, blank=True, null=True) profile_picture = models.ImageField(upload_to='avatar/', blank=True, null=True) company_name = models.CharField(max_length=124, blank=True, null=True) proposal_comments = models.TextField(blank=True, null=True) associations = models.TextField(blank=True, null=True) interests = models.TextField(blank=True, null=True) website = models.URLField(blank=True, null=True) location = models.CharField(max_length=124, blank=True, null=True) bio = models.TextField(blank=True, null=True) state = models.CharField(max_length=124, blank=True, null=True) country = CountryField(blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username which had image field named profile_picture i have also registered this model to admin and when i upload img using django administration it automatically upload/added to media folder. but when i upload img using django rest framework it is not showing me any error. what django rest framework do just update the url of img. django rest framework is not uploading/adding img to my media folder. i'm uploading img by hand. settings.py .... MEDIA_ROOT = os.path.join(BASE_DIR.parent, "media") MEDIA_URL = "/api/media/" urls.py ..... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("username", "email", "first_name", "last_name",) read_only_fields = ("username",) def validate_email(self, … -
Expose GET-Params for django-filter als CamelCase
I was wondering if I can expose the GET-parameters required for django-filter somehow as CamelCase instead of snake_case. Meaning changing http://example.com/api/v1/object/list?my_parameter=hello to http://example.com/api/v1/object/list?myParameter=hello. I know that I can transform the output of djangorestframework to CamelCase with this neat package: https://pypi.org/project/djangorestframework-camel-case/ I googled around for some time but couldn't come up with a clean solution. Help much appreciated. -
When should I raise PermissionDenied and when return HttpResponseForbidden in Django
I'm struggling to understand the different use cases for django.http.HttpResponseForbidden and rest_framework.exceptions.PermissionDenied. When should I rather raise the exception than returning a response? Why the exception anyway, if it is later handled as a 403 response? -
'InMemoryUploadedFile' object is not subscriptable
i am getting 'InMemoryUploadedFile' object is not subscriptable can anyone please help me views.py def addFee(request): if request.method=="POST": form=FeeResources() dataset=Dataset() data=request.FILES['myfile'] if not data.name.endswith('xlsx'): messages.info(request,'wrong format') return render(request,'admin/fee.html') imported_data=dataset.load(data.read(),format="xlsx") for i in imported_data: value=FeeStructure( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8] ) value.save() return redirect('managefee') return render(request,'admin/fee.html') -
In WSL, How do I get the following command after the server runs?
I use WSL. I run the 'python manage.py runserver'. After, How do I get the following command after the server runs?enter image description here -
Render a selected image from the option in Django Template
I have been trying to figure out how to render an image in a img tag (id="show_file") when a user selected an option in Django Template. Below is the part in question of my source code: {% block content %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var changeImage = function() { document.getElementById("show_file").src = this.options[this.selectedIndex].value } var imageList = document.getElementById("already_exist_file"); imageList.addEventListener("change", changeImage, True); </script> . . . . <br> <label for="already_exist_file">기존 이미지 사용</label> <select id="already_exist_file" name="image_url" class="selBox"> <option value="없음">(없음)</option> {% for notice in notice_list %} <option id="image" data-style="background-image: url({{notice.image}})" value="{{notice.image}}"> {{notice.image}} </option> {% endfor %} </select> <img id="show_file"> <br> And this is what the page looks like: When the image URL is selected, the img tag still does not show the image. -
Python Django End_of_file
def upload(request): if request.method == 'POST' and request.FILES['myfile'] : myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) length=len(filename) # sheet.cell_value(0, 0) i=1 wb = xlrd.open_workbook(filename) sheet = wb.sheet_by_index(0) for i in range(2): db.push(sheet.row_values(i)) return render(request, 'HafrApp/welcome.html') return render(request, 'HafrApp/welcome.html') #This code working for me but if I change the range of loop like range(length) its not working and gives a error. -
django NoReverseMatch Error when trying to link template to a view function
I'm trying to add a delete object function to an app I'm building and when I try to link to it in my template, I get... NoReverseMatchError Reverse for 'delete_player' with arguments '('',)' not found. 1 pattern(s) tried: ['game/delete_player/(?P[0-9]+)$'] As far as I can tell, (I think) I'm using the correct format in my template. I'm thinking that there's an issue with the object's id not being passed correctly or just not passed at all. I've been looking around Stack overflow here and google to try and find a similar problem but I can't find anything that quite matches what I'm experiencing. Any advice is appreciated. The models object in question that I'm trying to pass to the delete function is a choices field and looks like this. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) The model uses a form in forms.py class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) runningback_name = forms.CharField(label='Runningback', max_length=100) widereceiver_name = forms.CharField(label='Widereceiver', max_length=100) tightend_name = forms.CharField(label='Tightend', max_length=100) kicker_name = forms.CharField(label='Kicker', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) runningback_name = self.cleaned_data.get('runningback_name') Runningback.objects.create(name=runningback_name) widereceiver_name = self.cleaned_data.get('widereceiver_name') Widereceiver.objects.create(name=widereceiver_name) tightend_name = self.cleaned_data.get('tightend_name') Tightend.objects.create(name=tightend_name) kicker_name = self.cleaned_data.get('kicker_name') Kicker.objects.create(name=kicker_name) My delete … -
nested django serialisation through multiple foregin key
I have three models, artist, album and tracks. Artists have many albums and every album have many tracks. I try to serialize into json so that i get all tracks of a artist. Here is my code simplyfied: class Artist(models.Model): name = models.CharField(max_length=128) class Album(models.Model): album_name = models.CharField(max_length=128) artist = models.ForeignKey("Artist", related_name="art") class Tracks(models.Model): track_name = models.CharField(max_length=128) album = models.ForeignKey("Album") And my serialiser class TracksSerializer(serializers.ModelSerializer): class Meta: model = Tracks fields = ["track_name"] class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ["album_name"] class ArtistSerialiser(serializers.ModelSerializer): albums = AlbumSerializer(many=True, read_only=True, source="art") class Meta: model = Artist fields = ["name", "albums"] Function: def get_json(): artists = Artist.objects.all() serialiser = ArtistSerialiser(artist, many=True) content = JSONRenderer().render(serialiser.data) return Response(serialiser.data) To get all album of an artist works fine (also to get all tracks of an album), and give me this output: [ { "name": xxx, "albums": [ { "album_name": "xxx" }, { "album_name": "yyy" } ] } ] But how can write this to get all tracks of a artist (go through 2 reverse relations) My desired output is something like this, how can i persive that? (i have tryed to make an TrackSerialiser into the ArtistSerialiser class but dont know hot to go through …