Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add python shell in our website to run script in webpage for practice?
I want to run python code on my own website just like w3school provide shell for practice. I also want to add pip in that shell so is there any way to do this ? -
Django: ValueError Table allauth_socialapp does not exist
I successfully followed this tutorial and everything seemed to be ok. I then created a Profile model and managed to create it's objects through POST requests and through the admin panel. I then created signals so the profile could be created as soon as the user registered. After some trial and error I finally made it and decided I'd flush the database. When I tried to do so and ran python manage.py flush I got this error: raise ValueError("Table %s does not exist" % table_name) ValueError: Table allauth_socialapp does not exist I already tried doing python manage.py migrate for each of the installed apps but nothing seems to work and already tried removing the Profile model and the receiver it is using but that doesn't solve the problem. My models.py file looks like this: class Profile(models.Model): GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) interests = models.CharField(max_length=100, null=True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, null=True) def __str__(self): return f"{self.user}'s Profile" @receiver(user_signed_up) def user_registered(sender, request, user, **kwargs): print(f"Created profile for { user}") Profile.objects.create(user=user) """Creates the Profile after user registers""" and my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', … -
Show Last month progress of user on base of actions on website django
I have designed my database like this user = models.ForeignKey(Profile, unique=True, on_delete=models.CASCADE) signup = models.FloatField(default=10) signup_from_user_link = models.FloatField(default=0) post_review = models.FloatField(default=0) total = models.FloatField(default=0) I am calculating overall progress of user by adding all these values . But Now I have to make a change and I want to show progress of last month. Like in last month how much user added in every filed . What will be easiest way to get value of last month addition into these filed. Any help would be highly appreciated. thanks -
Why customized django login form thows takes 1 positional argument but 2 were given
I was trying to customized django login form. but it throws error like this TypeError at /login/ __init__() takes 1 positional argument but 2 were given. I have created my own form and not using django built in forms. My Project structure looks like this project_name apps app1 app2 static templates app1 login.html app2 app1 contains the basic home, login, signup template file url.py file inside app1 looks like this from django.urls import path from .views import home from django.contrib.auth import views as auth_views app_name = "basics" urlpatterns = [ path('home/', home, name="home_page"), path('login/', auth_views.LoginView,{'template_name': 'basics/login.html'}, name="login") ] login.html file resides under templates/app1/login.html and its template looks like this. {% extends 'basics/home.html' %} {% block body %} {% load static %} <script src="{% static 'js/login.js' %}"></script> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body" style="background-color: azure"> <h3 class="card-title text-center">Log In</h3> <br> <br> <p class="text-center">How did you signup?</p> {{ error }} <div class="main" id="mainForm"> <br> <form class="form form-group" method="POST" action="{% url 'django.contrib.auth.views.login' %}"> {% csrf_token %} <input name ="username" class="form-control" placeholder="Enter Username" required="required"> </br> <input name="password" class="form-control" placeholder="Enter Password" type="password" required="required"> </br> <button class="btn btn-block btn-dark btn-sm" type="submit">Submit</button> <br> <a href="#" class="text-center" id="backlink">back</a> </form> … -
Django: how to set initial value for Date Range Filter in Admin Model
I am new developer in Django. I have a admin site with Django. I have a table with 1.600.000 registries. I need to filter by range of date, and i need define start date and end date in a Django filter Date Range Filter. I am using, Django==2.1.10 django-admin-rangefilter==0.5.0 virtualenv==16.7.2 python-3.7.3 class TrackAdmin(ExportActionMixin,admin.ModelAdmin): list_display = ('timestamp', 'get_tipomarca','get_point','get_emp') search_fields = ('point_id', 'attendancetext') list_per_page=20 list_filter = ( ('timestamp', DateRangeFilter), ) I view that filter in my site admin in Django.But I expect the textbox of "from date" has a value, example, 23/08/2019 and textbox of "to date" has a date today. With this parameters, I have a filter a query with only registry necessary and not all table. That is my current view: Current view with filter And expect that: Expect view with filer -
Reverse for 'str_team' with no arguments not found. 1 pattern(s) tried: ['str_application\\-1/(?P<startup_id>[^/]+)/$']
i have two models, one is startup where the startup name is created and second is team where dynamically extra team members are created. the process goes in steps and when the startup name is created and redirected to second step i get the following error: Reverse for 'str_team' with no arguments not found. 1 pattern(s) tried: ['str_application\\-1/(?P<startup_id>[^/]+)/$'] as far i was reading, a template tag must be added in order to pass instances from one template to another through URL. appreciate your help, below is my code: URLS: from django.urls import path from . import views urlpatterns = [ path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ) , path ( 'str_application/' , views.startup, name = 'str_name' ) , path ( 'str_application-1/<startup_id>/' , views.startup, name = 'str_team' ) , Models: from django.db import models class Startup ( models.Model ) : startup_name = models.CharField ( 'Startup Name' , max_length = 100 ) def __str__(self) : return self.startup_name class Team ( models.Model ) : name = models.CharField ( 'Name' , max_length = 100 ) position = models.CharField ( 'Position' , max_length = 100 ) startup = models.ForeignKey ( Startup , on_delete = models.CASCADE ) def __str__(self) : return self.startup FORMS: … -
Send data from Android to Django
Im trying to send some data from my android app to my django app, but i have nothing in querydict, that comming from android. My django view: class Users(View): def get(self, request): return JsonResponse({"success":True}) def post(self,request): email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') print(request.POST) return JsonResponse({"success":True}) if im printing request.POST i have: <QueryDict: {}> My android request: private void addUser(String user_email, String password, String firstname, String surname, String gender){ MediaType MEDIA_TYPE = MediaType.parse("application/form-data"); OkHttpClient client = new OkHttpClient(); String url = "http://10.0.2.2:8000/users/"; try { String json = new JSONObject() .put("email", user_email) .put("first_name", surname) .put("last_name", firstname) .put("password", password).toString(); System.out.println(json); RequestBody body = RequestBody.create(MEDIA_TYPE, json); Request request = new Request.Builder() .url(url) .header("Content-Type", "application/form-data") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { e.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()){ String resp = response.body().string(); System.out.println(resp); } } }); } catch (Exception e){ e.printStackTrace(); } } If im sending the same code to Django-Rest-Framework everything works fine (i use there 'application/json' header). But i need to handle request this way. Is it possible? And what im doing wrong -
It's possible to make django admin field filter with another fields data in same model
I want to generate models field date with another field with replace spaces with '-' on typing When i with write foo title field, slug field automatically get data from title field and replace space with - It's possible? Thank you class foo(models.Model): title = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique=True) -
Handle button and popup logic in Django views.py
I have an html table rendered using logic from a Django view. The table is created from a queryset and a selection of the Model's fields. In addition, the table creates a column which includes action buttons for each row. The buttons should allow the user to view select certain options which can then be sent back to a Django view via AJAX. I have tried two different approaches, and would I like to find a solution which has the best of both of these. Option 1: The buttons are created with an href tag linking to another Django view. This view can then decide which template to render and with what context. This approach works great, the only issue being that the second view must clearly redirect the user to a new page. My ideal solution would be to the second view somehow render as a popup, which I understand is not possible as a view returns an http response, and only one view http response can be viewed at once. Option 2: The limitations of option 1 led me to try working with modals. Let us say I have two buttons which both bring up different modals. I … -
In Django, how can I make a logout request from another domain?
What I want to do is make a request from website A to website B to logout the user in B. But now the request.session will be a different one than I direct visit B since it is initiated from a different domain. So the Django's default logout(request) method will not work. I tried to delete the session cached in redis. But when I revisit site B, I am still login, with a new session. I have no clue why. -
Not able to map Django admin properly in EB
I have Django application deployed on AWS EB. My DevOps team has given me the URL like https://load_balancer.com/api/application where they have mapped my application to a load balancer. I am not able to map my Django admin properly to this new URL. When I visit https://load_balancer.com/api/application/admin, it says PAGE NOT FOUND, while the APIs are working properly. My settings/production.py ADMIN_URL = "admin/" STATIC_URL = "/static/" url.py path(settings.ADMIN_URL, admin.site.urls), I changed the STATIC_URL and ADMIN_URL to ADMIN_URL = "api/application/admin/" STATIC_URL = "/api/application/static/" On doing this, static files are loading correctly and I can see Django admin too at https://load_balancer.com/api/application/admin/login, but on logging in, it redirects to https://load_balancer.com/api/application/admin/login?next=/api/application/admin/ saying PAGE NOT FOUND. -
Django authentication and authorisation
I am working on a django project and want to implement authentication with allauth. I want to understand following. Written with funny pseudo code but understandable. (A) if (allauth could use AbstractBaseUser implement) = True then How ? end if (B) if (allauth handles authentication AND authorisation = True) then How ? else Do I need to use django-guardian or django-roles with allauth for authorisation? End if (C) if (django-roles supports AbstractBaseUser implemnt) = True then How ? end if -
Passing the value to form from View - Django
I have a view in which i am rendering two forms. Both the forms are related to each other UpdatePayment(sim_form) and AddPaymentForm(payment_form). As you can see from the code that I am populating the form by fetching the ID of sim_form . I want the same ID of sim_form to be saved in model Payment which has a sim foreign key in it. But i am unable to pass the value and the form gives a validation error of having a null value for sim_id. The id is coming and i am able to use it as well. model class Payment(models.Model): deposit_date = models.DateField(blank=True, verbose_name='Deposit Date') file = models.FileField(upload_to=get_file_path) sim = models.ForeignKey(Sim, on_delete=models.DO_NOTHING, null=False, blank=False) View def updatePayment(request, id): sim = get_object_or_404(Sim, pk=id) payment_form = AddPaymentForm(request.POST, request.FILES) if request.method == "POST": sim_form = UpdatePayment(request.POST, instance=sim) try: if payment_form.is_valid() and sim_form.is_valid: sim_form.save() # I am trying to form the value from here payment_form.sim_id = id payment_form.save() messages.success(request, ("Payment has been updated")) else: messages.warning(request, ("Data in fields is incorrect, please try again")) except Exception as e: messages.warning(request, ("Error: {}".format(e))) else: sim_form = UpdatePayment(instance=sim) payment_form = AddPaymentForm(request.POST) context = {'sim_form': sim_form,'payment_form': payment_form,} return render(request, 'payment/updatePayment.html', context) -
Not able to download multiple files using XMLHttpRequest and Xhtml2pdf
Hi I am trying to generate and download multiple files using XXLHttpRequest but it's never getting into response of javascript's request. Here is my javascript code: {%block javascript%} <script type="text/javascript"> function exportPDFForAll(employees) { var employeesList = [ {% for emp in employees %} {% if not forloop.first %},{% endif %} { name: "{{ emp.name }}" } {% endfor %} ] alert(employeesList) for (var i = 0; i < employeesList.length; i++){ var params = 'selectedName='+employeesList[i].name+'&selectedDate='+$('#date').val()+'&csrfmiddlewaretoken='+$('input[name=csrfmiddlewaretoken]').val(); var req = new XMLHttpRequest(); req.open("POST", "/exportallsheets/", true); req.responseType = "blob"; //Send the proper header information along with the request req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); req.onload = function (event) { var blob = req.response; console.log(blob.size); var link=document.createElement('a'); link.href=window.URL.createObjectURL(blob); link.download=employeesList[i].name+"_" + new Date() + ".pdf"; link.click(); }; req.send(params); } } </script> {%endblock%} and here is my render class in Django: from io import BytesIO, StringIO from django.http import HttpResponse from django.template.loader import get_template import xhtml2pdf.pisa as pisa class Render: @staticmethod def render(path: str, params: dict): template = get_template(path) html = template.render(params) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: # return HttpResponse(result.getvalue(), content_type='application/pdf') response = HttpResponse(result.getvalue(), content_type='application/pdf') filename = "Invoice_%s.pdf" %(params['name']) content = "inline; filename=%s" %(filename) content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content print(response) return response else: … -
Securing Python source code via execution in RAM based filesystem with encryption / decryption process via license server
I have an idea for protecting my Flask / Django code base from theft in cases where a potential attacker may have physical access to the server ie: perhaps in the case of an onsite install for an enterprise level client. Let's assume the servers are all linux based. The idea has a couple of steps: Store code encrypted on disk. On startup load it into a RAM based filesystem still in this encrypted state. Contact license server and authenticate to get encryption key and store it in RAM. Decrypt code inside RAM based filesystem. Run webservice from this RAM based filesystem like any other wsgi service. Thus the unencrypted code only ever is present in the RAM while the server is on, meaning any hard disk based attacks from attackers with physical access to the machine would be thwarted, and any attack would have to target the contents of the RAM. How hard would it be to defeat this defense strategy? Is there some "easy" way to defeat this scheme given physical access to the server. Please no lectures on how I shouldn't be deploying to such a server, I am interested in a concrete technical reason for how … -
Creating dropdown buttons in django
I've been trying to figure out how to implement dropdown buttons in Django but has not figured out what works. What I created is: class AMLVideo(models.Model): LANGUAGE = ( ('LAN', 'Language'), ('FR', 'French'), ('EN', 'English'), ('HIN', 'Hindi'), ('SPA', 'Spanish'), ('GER', 'German'), ) LEVEL = ( ('BEG', 'Beginner'), ('INT', 'Intermediary'), ('ADV', 'Advanced'), ) CATEGORY = ( ('ANI', 'Animal'), ('ENV', 'Environmental'), ('MOR', 'Moral'), ('FOLK', 'Folktales'), ('ADN', 'Adventure'), ('POE', 'Poems'), ('FUN', 'Funny'), ) title = models.CharField(max_length=100, default=None) level = models.CharField(max_length=100, choices=LEVEL) language = models.CharField(max_length=100, choices=LANGUAGE) category = models.CharField(max_length=100, choices=CATEGORY) video = EmbedVideoField(verbose_name='Videos', help_text='URL of Video') def __str__(self): return self.title class Meta: verbose_name = "video" verbose_name_plural = "videos" Then, my views are: def home(request): amlvideo = AMLVideo.objects.filter().order_by("-category", "-language", "-level") context = {"amlvideo": amlvideo} return render(request, "aml/home.html", context) Basically what I want to do is to have default categories on the buttons and another user can add a category from his profile. These categories are then showed on the front end, from which the videos with the categories are "fixed" when a user chooses a category. The example is this site: https://www.planetread.org/anibooks Anyone can help me? -
How to update the browser, when new data is received through external post method(not from the browser) in django?
I am trying to show some blocks in the browser using django. The blocks are states which are marked by colors. Initialy have the data and I can run the server and see the blocks in the browser. There will be another python script which will post the updated data via rest api call. When the data is changed, I want to see the updated data in the browser. I used postman and sent some updated json to the rest api. But the problem is, the response of the post method goes back to postman and browser data is not updated. So actually I want to use the browser to visualize the data dynamically as it is changed and nothing else. And the data will be updated through rest call. Is it the proper way to do it? If so, how to do this? in views.py class myView(APIView): @csrf_exempt def get(self, request): # log.info("Request Received : %s", request) data = {'data1': 'data1', 'values': []} values= {'name': 'value1', 'config': 'value2', 'containers': [ {'name': 'container1', 'status': 'PENDING', 'color': '#69f0ae'}, {'name': 'container2', 'status': 'PENDING', 'color': '#69f0ae'}, ]} data['values'].append(values) return render(request, 'index.html', {'data': data}) def post(self, request): data = request.data return render(request, 'index.html', {'data': … -
uwsgi worker keep idle after respawning
I use nginx + uwsgi + django to setup web server, and some times I found the response is so slowly and I have to use the touch command which uwsgi provided to reload the sever. After using uwsgitop to monitor my uwsgi server, I found that some uwsgi workers keep idle after being respawned, and these workers' RSS and VSZ are zero, as the following image shows. I didn't find any error info in uwsgi log, the spawning info is normal like this: worker 6 killed successfully (pid: 14872) Respawned uWSGI worker 6 (new pid: 5545) worker 9 killed successfully (pid: 14878) Respawned uWSGI worker 9 (new pid: 3807) If I use kill -9 worker-pid command to respawn the worker, most time the workers can be respawned successful and own RSS and VSZ and start work, while sometimes just be respawned with zero RSS and VSZ and keep idle. I try my best but I can't get a clue what happened to the respawned worker. I post an issue to the uwsgi project, but get no response for a long time(It should not be an issue of uwsgi). Any suggestion to debug or inspect this problem? FYI, This is … -
how edit and delete rows from django_tables2 and make filter search in up of table and next and previous button
hello my friends i use django_tables2 and i show my data table and all it is ok ... i want now to edit and remove rows and make filters search in up of table .. make next and pervious ... i do not find good documentation about this so can you help me ? this is the view code of my table showing in view thank you def Immoblist(request): table = ImmobTable(Immob.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) RequestConfig(request).configure(table) return render(request,"immob_list.html", {'table': table}) -
i want to integrate "google sign in" in my google app engine project
I want the google sign in method in my webapp2 application. Currently i can't find any method (in google searches) to do that. You can easily do that in javascript (but that's on the client side), i want the data on my server side so i can add user to the database (if not present already). Some example snippets would be great help. and is there official documentation to do that? i want to do it in a controller like so from google.appengine.api import users import webapp2 class Google_sign_up(webapp2.RequestHandler): def get(self): # code for the google sign in goes here -
How to use a already built html template in django?
I have an already built HTML template for eCommerce to use in Django. But when i implemented it with all the static files are set, the template is not rendered when i run the server, the page is completely blank. However there was no error in the terminal as well as the debug console. When i view the page source, i can see all the HTML elements. I dont know what is the issue here. Please give me a hint, thank you! the page is blank page source base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Home</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% include "base/css.html"%} </head> <body class="animsition"> {% block content %}{% endblock %} {% include "base/js.html" %} </body> </html> home.html {% extends "base.html" %} {% load static %} {% block content %} <!-- my content here --> {% endblock %} views.py from django.shortcuts import render def home_page(request): return render(request, 'home_page.html', {}) urls.py from .views import home_page urlpatterns = [ re_path(r'^$', home_page, name='home'), ] -
What is the use of __table_args__ = {'extend_existing': True} in Flask-SQLAlchemy?
I have a flask application which I'm trying to convert into Django. In one of the models which inherit an abstract base model, it is mentioned as __table_args__ = {'extend_existing': True} Can someone please explain what this means in SQLAlchemy with a small example. I have gone through few articles but as I worked on Django and new to Flask-SQLAlchemy I couldn't understand it properly. https://hackersandslackers.com/manage-database-models-with-flask-sqlalchemy/ https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html -
I want to get the vote button with proper functionality but i'm unable to do that...i tried but fail...help me please, how to do that
Actually i want vote button that works properly, when user clicks that button it should increase the number of votes there itself... views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from . models import Question, Choice from django.urls import reverse # Create your views here. def base(request): return render(request, 'base.html') def home(request): return render(request, 'home.html') def quest(request): question_list=Question.objects.all() context={'question_list': question_list} return render(request, 'quest.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.base, name='base'), path('home', views.home, name='home'), path('quest', views.quest, name='quest'), ] base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/a076d05399.js"></script> <title>Voting World</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav ml-auto"> <a class="nav-item nav-link active" href="#">About us</a> <a class="nav-item nav-link active" href="#"><i class="fas fa-user"></i> Login</a> <a class="nav-item nav-link active" href="#"><i class="fas fa-sign-in-alt"></i> Signup</a> </div> </div> </nav> <div class="container"> {% block body %} {% endblock %} </div> </body> </html> quest.html {% extends 'base.html' %} {% block body %} {% if question_list %} <ul style="list-style: none;"> {% for question in question_list … -
Dynamic field logic
For example, on a product comparison site, each product does not have the same feature, so what I mean is that the car has the option of a gear while the phone has a memory option. Or in the lol tournament, teams fight with teams, but in fortnite players fight with players. The question is how do they keep it in the database. Can you send me a link to review how it's done? (Github project or Youtube video series) I'm new to web development and have no idea how it's done. -
Django, jwt authentication in django view, not just DRF
I'd like to use jwt with django (probably https://github.com/davesque/django-rest-framework-simplejwt) The library documentation and most web blogs on jwt talks about using jwt on DRF authentication. But we have Django regular views which are not DRF based. Can I still use one jwt authentication backend for both DRF and regular django views?