Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get client UUID from browser
I want to get client UUID, when user accesses my website. Actually, I am will be encrypting something a user can download and it will open in my application only. In my application I am getting UUID on the run and decrypting using this: os.popen('wmic csproduct get UUID').read() Everything it working fine, now the only limitation is that I couldn't find any way to get UUID of the client from my website, so that I can encrypt along with some other hashes that my application know and can add as salt and decrypt. My website id developed on Django. Note I think I need to write some script that user will download and it will send me the data all the time and then I will allow the user to download, anyone can guide me on this ? I know you can ask what if user changes the system etc. I just want to get UUID for now I have taken care of other things already. For now lets say I want to work on windows only, no Linux or Mac user -
How to solve Incorrect padding in Django?
I just installed 'clean_cachepackage in Django and after refresh my website i gotIncorrect paddingerror, here is the error codehttps://prnt.sc/u7y08g, so please let me know how i can solve this issues. I research a lot about it but i did not found base64.py` file in my file structure. -
I have a domain from GoDaddy and a Django app working on Linode with an IP address. How do I point the domain to the Django app using mod_wsgi?
I have a domain I bought from GoDaddy (example.com) and I have a Django app at an IP address. Without changing the nameservers on GoDaddy, how can I point the domain to the Django app? -
How can we create 'Story Like Feature' using HTML/CSS/JS
Suppose I have an array of Images or Videos like this var arr = ['1.jpg', '2.jpg', '3.mp4', '4.mp4'] I want to make a Story Like Feature like on Facebook or Instagram When a user clicks on Show Story it shows every pic for 10 seconds and if its a video it plays it till it is finished and then jumps to the next one. I want to add controls also.. For example if some clicks on the left side or right side the slideshow jumps to previous slide or next slide respectively... Any Idea how to implment it Using Just HTML/CSS/JS I am using Django Framework for my website -
Django error: "settings.DATABASES is improperly configured. Please supply the ENGINE value."
I am trying to follow the guide here for using multiple databases in Django 2.2, with the default database left blank. In my settings.py file I have # Set database routers DATABASE_ROUTERS = [r'myapp.db_routers.AuthRouter', r'myapp.db_routers.RemoteRouter'] # Database configuration - leave default blank DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'remote': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'MY HOST NAME', 'NAME': 'MY DB NAME', 'PORT': 'MY PORT NAME', 'USER': get_secret(Secrets.REMOTE_DB_USERNAME), 'PASSWORD': get_secret(Secrets.REMOTE_DB_PASSWORD), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'host_is_server': True } } } My db_routers.py file then contains the two database routers, as suggested in the documentation (but it should capture all of the django built-in apps): class AuthRouter: route_app_labels = {"admin", "sessions", "messages", "staticfiles", "auth", "contenttypes"} def db_for_read(self, model: Model, **hints) -> Optional[str]: if model._meta.app_label in self.route_app_labels: return "auth_db" else: return None def db_for_write(self, model: Model, **hints) -> Optional[str]: if model._meta.app_label in self.route_app_labels: return "auth_db" else: return None def allow_relation(self, model_1: Model, model_2: Model, **hints) -> Optional[bool]: if (model_1._meta.app_label in self.route_app_labels or model_2._meta.app_label in self.route_app_labels): return True else: return None def allow_migrate(self, db: str, app_label: str, model_name: Optional[str] = None, **hints) -> Optional[bool]: if app_label in self.route_app_labels: return db == "auth_db" else: return … -
Django error with redirect after registration or login
I am using the out the box standard Django authentication. Yet sometimes when I login or register, the page gets stuck on loading when it is supposed to redirect. I have checked my error logs, and there is nothing. Has anyone experienced this before, and how did you solve it? -
how to add new function to jquery.formset django
i want to know total price for each row input i make a script for that purpose , but it only write first row result , i've used inlineformset_factory with jquery.formset.js jquery.formset.js this is the script <script> $('tr').on('keyup','.qnt','.price',()=>{ totalPrice(); }) function totalPrice(){ let qnt=$(".qnt").val(); let price=$(".price").val(); $(".cash").val(qnt * price); } $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', addCssClass:'btn btn-info ', deleteText:'delete', deleteCssClass:' hide', added:function($row){ $('.item').select2(); } }) $(".item").select2(); }) </script> <tbody class="tbody tb1 "> {% for item in items.forms %} {{item.errors}} <tr class="p-0 col-12 tr"> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 text-center qnt'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 text-center price'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.cash | add_class:'col-12 text-center cash'}} </div> </td> </tr> {% endfor %} </tbody> i need to price * quantity and write the result into cash field , it works only for he first row , for the rest doesnt work ?! i appreciate your helps please -
Django Foreign key on Modelform
I'm working on the project that Django tutorial provides. I'm just trying to expand functionality like: login, registration, poll CRUD and so on. I have two models: class Question(models.Model): question_text = models.CharField(max_length=70) describtion = models.TextField(null=True, max_length=200) pub_date = models.DateTimeField(auto_now=True) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Thet connected via foreignkey. So, each choice has it's own question. And set up in admin dashboard,so if i try to create new question i can add as many choices i want. I just configured it in admin.py. Problem is this I want to have a form that user can submit a question and its choices. I've done first part that user can create poll question, but cannot handle to add choices while creating question itself. Choices should automatically connected to Question. Please help me solve this problem. My ModelForm looks like this class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_text','describtion'] widgets = { 'question_text': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'title'}), 'describtion': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'describtion'}) } -
Using PyTorch with Celery
I'm trying to run a PyTorch model in a Django app. As it is not recommended to execute the models (or any long-running task) in the views, I decided to run it in a Celery task. My model is quite big and it takes about 12 seconds to load and about 3 seconds to infer. That's why I decided that I couldn't afford to load it at every request. So I tried to load it at settings and save it there for the app to use it. So my final scheme is: When the Django app starts, in the settings the PyTorch model is load and it's accessible from the app. When views.py receives a request, it delays a celery task The celery task uses the settings.model to infer the result The problem here is that the celery task throws the following error when trying to use the model [2020-08-29 09:03:04,015: ERROR/ForkPoolWorker-1] Task app.tasks.task[458934d4-ea03-4bc9-8dcd-77e4c3a9caec] raised unexpected: RuntimeError("Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method") Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) … -
Create new user with Django Rest Framework JSON Web Token
I am using Django REST framework, with Simple JWT. I am trying to create a user registration page. Currently, I am getting this error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Full error message here: Under settings.py, I have added this: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), } My project urls folder: urlpatterns = [ path('admin/', admin.site.urls), path("", include("my_api.urls")), path('api-auth/', include('rest_framework.urls')), path('api/token', TokenObtainPairView.as_view()), path('api/token/refresh', TokenRefreshView.as_view()), ] And this is my app's view for my registration endpoint. def register(request): if request.method == "POST": email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "my_api/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: # Creates a hashed password. #password = make_password(password) user = User.objects.create_user(username=email, email=email, password=password) user.save() except IntegrityError as e: print(e) return render(request, "my_api/register.html", { "message": "Email address already taken." }) login(request, user) return HttpResponse("Successfully created account.") else: return render(request, "my_api/register.html") -
Django model - making db value as dependent from others values from db
i have models as follow: models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) cat = models.IntegerField() read_pages = models.IntegerField() total_pages = models.IntegerField() read_pages_of_book = models.FloatField(default=round(read_pages/total_pages, 2)) status = models.BooleanField(default=(False if read_of_book < 1 else True)) Please consider read_pages_of_book variable. Is this possible to have value like that as dependent from other values? Or maybe I shouldn't keep this value in db and just use both 'read_pages' and 'total_pages' on my views.py and the send it as a context? I'm really trying to understand this concept and to use it well so for any help i will be gratefull. -
How to handle uploaded excel file in Django
I try to display some data in console during the file upload. I have tested that I can convert uploaded excle files thrue a PANDAS script that way but error occureed. I used: in settings.py: FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] view: def excle_upload(request): if request.method =='POST': form = ExcleForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES['file'] path = filehandle.temporary_file_path df = pd.read_excel(path) print(df.head()) form.save() return redirect('excle_list') else: form = ExcleForm() return render(request, 'odo_correction/excle_upload.html', {'form':form}) Error: Django Version: 3.1 Exception Type: ValueError Exception Value: Invalid file path or buffer object type: <class 'method'> -
heroku django/react deployment not working correctly
I have deployed my django/react app to heroku but only the home page gets rendered but my data that I have in my sqlite database does not get rendered. If I were to go to /api then django shows me this HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "todos": "https://this-todo.herokuapp.com/api/todos/" } but when I go to that actual route with api/todos it still doesn't not show me my todos. What might I be doing wrong. I followed this tutorial to deploy https://librenepal.com/article/django-and-create-react-app-together-on-heroku/ -
URL redirect issue in python using Django framework
here we have redirect code return HttpResponseRedirect('/{}-meters-to-{}/'.format(value, unit)). value is not appending to URL some time but the output is showing. path('meters-to-centimeters/', views.functon1, name='convert_m_cm'),# landing page url path('meters-to-millimeters/', views.function1, name='convert_m_mm'),# landing page url path('<str:data>-meters-to-<str:to_units>/', views.function1_views, name='m_conversion_views'),# details page /output page url [i gave input as 5 and slect inches unit but URL is not related to that.] -
Can't get logged out
views.py file I can register and login but once logged in , the logout functionality doesn't work. To log out i must go to admin page and log out which is also only possible if the user is superuser to admin page def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user= auth.authenticate(username= username, password= password) if user is not None: auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('dashboard') else: messages.error(request, 'Invalid Credentials') return redirect('login') else: return render(request, 'accounts/login.html') def logout(request): auth.logout(request) messages.success(request, 'You are now logged out') return redirect('login') urls.py file urlpatterns= [ path('login/', views.login, name= 'login'), path('register/', views.register, name= 'register'), path('dashboard/', views.dashboard, name= 'dashboard'), path('logout/', views.logout, name= 'logout'), ] html content {% if user.is_authenticated %} <li class="dropdown mega-dropdown"> <a href="{% url 'dashboard' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Dashboard</a> </li> <li class="dropdown mega-dropdown"> <a href="{% url 'login' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Logout</a> </li> {% else %} <li class="dropdown mega-dropdown"> <a href="{% url 'login' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Register/Login </a> </li> {% endif %} -
Unhandled Rejection (TypeError): Cannot read property 'error' of undefined in Reactjs
plz help solving this err here is the image of the error -
Django unable to find page
For some reason, Django is not picking up a certain template and I am unsure why. Link in navbar.html <a class="dropdown-item" href="/course/posts/{{ course.slug }}">{{ course.title }}</a> views.py def posts(request, course_slug, *args, **kwargs): course = Course.objects.get(slug=course_slug) posts = Post.objects.filter(course__id=course.id) courses = Course.objects.all() context = { 'posts' : posts, 'courses' : courses, } return render(request, "course/posts.html", context) urls.py from django.conf.urls import url from . import views from . import admin_views app_name = 'course' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^posts/(?P<course_slug>\w+)$', views.posts, name='posts'), url(r'^admin/course/create$', admin_views.create, name='create'), url(r'^admin/course/update/(?P<post_id>[0-9]+)$', admin_views.update, name='update') ] Not sure where my problem is. -
How can I register a custom filter in Django
I want to register a simple filter in Django in order to concat two strings in a template. I found many questions about this here, but seemingly no answer solves my problem. settings.py 'MedAbrDirk.apps.MedabrdirkConfig', 'MedAbrDirk.templatetags', MedAbrDirk/templatetags/my_tags.py from django import template register = template.Library() @register.filter() def kette(arg1,arg2): return str(arg1) + str(arg2) MedAbrDirk/templates/MedAbrDirk/base.html {% load my_tags %} <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="dropdown"> <a href="#" class="dropdown-toggle-menu" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Rechnungen<span class="caret"></span></a> <ul class="dropdown-menu"> {{'test'|kette:'test2'}} <li><a href="{% url app_var|kette:'eingabe' %}">Rechnung eingeben<span class="sr-only">(current)</span></a></li> Still, in the browser I get: "Invalid filter: 'kette'" I have no idea what causes this. I have deleted the pychache folder, I have restarted my gunicorn several times. Any advice? -
Getting the following error: Could not find a version that satisfies the requirement command-not-found==0.3
I am deploying a Django app using Heroku. When I called "git push heroku master" in cmd, I got the following error: "Could not find a version that satisfies the requirement command-not-found==0.3". When I run "sudo apt-get install command-not-found", I find that command-not-found is version 20.04.2. However, pip freeze tells me command-not-found is version 0.3. -
Suggestion on Django, mySQL and charts
I will be starting a new project which will include Django, mySQL and the output of the DB tables would show some line and bar graphs. I need suggestion on which could the right tool to do so. The project will be an replacing Grafana (since its loading data very slowly and not reliable to me.) I never worked on Django mySQL to output on charts, I google a few like Chartjs, anychart, d3 which look to be good options. Are there any tools suggested to look after before giving them a green flag? -
I am getting objects in column to which I have applied foreignkey rather the actual string name.How to solve this error
I am having two tables one is myprofile and second is mypost .I am trying to user the username from my profile table into mypost table to keep in as the value of uploadedby but rather than getting the name of the user I am get objects like myprofile object(2) in my uploadeby column ,how to solve it. My models.py looks like: class MyProfile(models.Model): objects = None name = models.CharField(max_length = 100) user = models.OneToOneField(to=User, on_delete=CASCADE) age = models.IntegerField(default=18,validators=[MinValueValidator(18)]) email = models.EmailField(null=True, blank=True) address = models.TextField(null=True , blank=True) status = models.CharField(max_length= 20, default= "single", choices=(("single","single"),("married","married"),("commited","commited"))) gender = models.CharField(max_length= 20, default="female", choices=(("female","female"),("male","male"))) phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15,null=True, blank=True) description = models.TextField(null=True,blank=True) pic = models.ImageField(upload_to="images\\", null=True) def _str_(self): return "%s" % self.user class MyPost(models.Model): pic = models.ImageField(upload_to="images\\", null=True) subject = models.CharField(max_length = 200) msg = models.TextField(null=True, blank=True) cr_date = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True) def _str_(self): return "%s" % self.subject my views.py looks like: @method_decorator(login_required, name="dispatch") class MyPostCreate(CreateView): model = MyPost fields = ["subject", "msg", "pic"] def form_valid(self, form): self.object = form.save() self.object.uploaded_by = self.request.user.myprofile self.object.save() return HttpResponseRedirect(self.get_success_url()) Please help me to figure out my mistake and how to solve it -
How to add the appointment data from Angular Scheduler app to a local database?
I am using the syncfusion ej2 Angular Scheduler App, I want to know that how can i add the appointment data that i provided in it to my local database. What should be the correct approach to do it in django if i want to add the data to mongodb? -
Ajax pagination with class based view
I am trying apply ajax with pagination on my app .Using Class based Listview #views.py class HomePage(ListView): model = Video template_name = 'index.html' def get_context_data(self, **kwargs): context = super(HomePage, self).get_context_data(**kwargs) videos = Video.objects.filter(category='sub') paginator = Paginator(videos, 5) page = self.request.GET.get('page2') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) context['videos'] = videos if self.request.is_ajax(): html = render_to_string('videos/index.html', context, request=self.request) print(html) return JsonResponse({'form' : html }) The Home template script <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '.page-link', function(event){ event.preventDefault(); var page = $(this).attr('href'); console.log(page) $.ajax({ type: 'GET', url: , data: {'page':'{{ page.number }}'}, dataType: 'json', success: function(response){ $('#ajax_page_template').html(response['form']) console.log("success") }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> 1.The current error is in views.py local variable 'html' referenced before assignment 2.And what should I put in ajax --url: I tried to put url:page but that return url to 127.0.0.1:8000/?page=2/?page=2. -
environment variables not accessible to gunicorn
I have a django project and linux server. On the server, i have set my secret key in bash_profile as - export SECRET_KEY=<SECRET_KEY> Now, I am able to use this env variable in my django project as - SECRET_KEY=os.environ.get('SECRET_KEY') I use "python manage.py runserver" to run the project and everything works fine. Same project when I am trying to run using gunicorn server, SECRET_KEY=os.environ.get('SECRET_KEY') gives error. How can I use linux environment variables through gunicorn also? -
How to connect two objects of two models together in Django
This is my models.py from django.db import models class Movie(models.Model): title = models.CharField(max_length=50) release_time = models.DateTimeField() def __str__(self): return self.title class Ticket(models.Model): username = models.CharField(max_length=50) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) #movie_time = models.ForeignKey(Movie.release_time, on_delete=models.CASCADE) In class Ticket, I want to get get two objects from the Movie class, which are the title and the release_time. I managed to get one of them using __str__(self) function, I want Movie.title in the movie variable and also I need the selected Movie objects's release_time in the movie_time variable(I've written the pseudocode of what I want in the commented line). How can I do the same? Any help will be Appreciated!