Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need help for implement a custom django login
I'm trying to develop a custom login in Django instead of using Django inbuilt login system. I don't know weather it's possible of not. If it's possible please help me to do this. I want to capture the value form the login template form. I have tried many ways but it's not working This is my backend code def login(request): if request.method == 'GET': context = '' return render(request, 'mytest/login.html', {'context': context}) elif request.method == 'POST': context = '' username = request.POST.get('username', '') password = request.POST.get('password', '') print(username) print(password) return render(request, 'mytest/login.html', {'context': context}) This is my login template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="{% url 'login' %}"> {% csrf_token %} <label>Email</label><input type="text" name="username" required><br> <label>Password</label><input type="password" name="password" required> <input type="submit" value="Login"> </form> </body> </html> please help me to get this work -
Django initial value for MultiChoice Field ignored for ModelForm
this is my first post here and I am very new to Django but I just can't seem to find a solution for this problem... I've searched stackoverflow and google but nothing seems to work for me... I have a wine-app and want to be able to add and remove wines from the user's stock. In the list of wines the user can choose a wine to add and the ID of this wine is passed in the POST data. Since the data is getting lost after the first time the view is rendered I saved the ID in a cookie, which is working, but the problem is when I work with ModelForm de user has to select the foreign key for the user and for the wine, which is bad, so I tried to make it hidden and set the Fk_user and Fk_wine after the user choose the number of bottles to be added but before validation. Here's the problem after google everyone suggested I should use the "initial" and pass that to the form, but this is clearly not working because if I make the fields visible in the form I can see that it is not preselected... … -
Need detailed guide for autocomplete/suggester for solr+django+haystack
I have made solr==6.x working with django==2.0.3 and haystack2.8 and now i need implement autocomplete/suggester for my search box. Can anyone please suggest article/link wherein i can get the full details to implement the same? -
How to make a pdf of a specific part of a html file in django
I want to generate pdf from html in django using xhtml2pdf. But xhtml2pdf seems to make a PDF of full HTML template. What I want to say is that suppose I have a side menu, a header, a footer and a table of some contents in my html file. Now, I want to only generate pdf of that table from the html file. How can I do that using xhtml2pdf ? Thank you. -
How to run python script with a video output from a flask web app?
I am trying to develop a web app that counts the no. of cars coming into a parking facility. The back end code is ready and is able to successfully get the no. of people coming in and out of the facility. How would i be able to run this python code from my app so that i can display the camera output and a few dynamically changing graphs on my interface? -
postgres queryis not working properly
select * from data_adultdata where sex='Male' when I am not giving space before 'Male', its return nothing. query not working select * from data_adultdata where the sex= ' Male' when I am giving space before ' Male' then it returns correct record. query working fine -
Django rest knox set ttl on basis of platform
I am using django-rest-knox for drf authentication. I have succesffuly implemented it but now I want to set token expiry based on the requesting platform. If a user is logged in from mobile I want to have different TTL as of logged in through web. How could I accomplish this. I am using header value to differentiate between platforms. -
In the following modelform how can i access currentuser detail in qureyset mentioned in program "CURRENT USER EMAIL ID"
modelform class Build_kbform(ModelForm): share_with=forms.ModelMultipleChoiceField(queryset=User.objects.filter (id__in=S etupuser.share_KB_with.through.objects.values_list ("user_id").filter(setupuser_id=Setupuser.objects.values_list ("id",flat=True).filter(email_id="CURRENT USER EMAIL ID")[0])) ,widget=forms.CheckboxSelectMultiple)knowledge = forms.Textarea() class Meta: model=Buildkb exclude=["email"] formview class Build_Kb(FormView): template_name = "pkm_templates/buildkb.html" form_class = Build_kbform success_url = '/thanks/' def form_valid(self, form): share_with=form.cleaned_data.get("share_with") instance = Buildkb.objects.create(keywords=keywords) for user in share_with: instance.share_with.add(user) instance.save() return redirect("/") I used class based view instead of function based view.Is there any simple way to access current user details in modelform. I am familiar to access request object with function based view but issue with class based view. should i go back to function based view . -
Django cannot detect GeoIP data from nginx
I am trying to get the country_code from people that visit my site, i decided to use nginx geoIP module to do this. I already set the nginx configurations, etc etc. But somehow it always keeps giving empty values. The nginx have "--with-http_geoip_module" when i used "nginx -V", so it's GeoIP function should work. I am using uwsgi for my django. This is my nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 210; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; geoip_country /etc/nginx/geoip/GeoIP.dat; # the country IP database geoip_city /etc/nginx/geoip/GeoLiteCity.dat; # the city IP database proxy_set_header GEOIP_COUNTRY_CODE $geoip_country_code; proxy_set_header GEOIP_COUNTRY_CODE3 $geoip_country_code3; proxy_set_header GEOIP_COUNTRY_NAME $geoip_country_name; proxy_set_header GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code; proxy_set_header GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3; proxy_set_header GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name; proxy_set_header GEOIP_REGION $geoip_region; proxy_set_header GEOIP_CITY $geoip_city; proxy_set_header GEOIP_POSTAL_CODE $geoip_postal_code; proxy_set_header GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code; proxy_set_header GEOIP_LATITUDE $geoip_latitude; proxy_set_header GEOIP_LONGITUDE $geoip_longitude; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } This is my /etc/nginx/sites-available: server { listen 80; listen [::]:80; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name www.testname.com testname.com; access_log off; error_log /var/www/log_nginx/error.log; gzip on; gzip_disable "msie6"; client_header_timeout 180s; client_body_timeout 180s; … -
allow post requests in django REST framework
I am creating a simple rest api using django REST framework. I have successfully got the response by sending GET request to the api but since I want to send POST request, the django rest framework doesn't allow POST request by default. As in image(below) only GET,HEAD, OPTIONS are allowed but not the POST request The GET and POST methods inside of views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from profiles_api import serializers from rest_framework import status # Create your views here. class HelloApiView(APIView): """Test APIView""" #Here we are telling django that the serializer class for this apiViewClass is serializer.HelloSerializer class serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Retruns a list of APIViews features.""" an_apiview = [ 'Uses HTTP methods as fucntion (get, post, patch, put, delete)', 'It is similar to a traditional Django view', 'Gives you the most of the control over your logic', 'Is mapped manually to URLs' ] #The response must be as dictionary which will be shown in json as response return Response({'message': 'Hello!', 'an_apiview': an_apiview}) def post(self,request): """Create a hello message with our name""" serializer = serializer.HelloSerializer(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = 'Hello! {0}'.format(name) return Response({'message':message}) else: … -
Django url regex hit end of url: *./something
I am geting 404 on different urls that end with the same string and instead of creating multiple redirects I would like to catch them all on the last string. It always appears at the same position, pattern goes like so: /some-of-my-urls/the-same-string No trailing slash there. I tried something like this: url(r'^[a-zA-Z0-9_]+/the-same-string', redirect_func), url(r'^./the-same-string', redirect_func), But that doesn't work. Probably obvious for somebody with more regex knowledge, I am not very advanced. Anybody ideas? -
Django: Secret Key in Production
What is the right way to keep the SECRET_KEY safe in production. I've seen people suggesting that load it from environment variable, but I have no idea what that is & how to load from it? I tried creating a separate new_settings.py file & stored the secret key in there. Like that, KEY = 'something' And then in original settings.py file, I did this, from new_settings import KEY SECRET_KEY = KEY But it's raising an error that, No module named 'base_settings'. So, what is the right way for setting this up? Thank You . . . -
Using Quill Editor on a form input in Django.
I want to use Quill Editor on a form input in Django. From the examples in Quill playground I see that always the container is a div. How can I make it work with a <textarea> instead of a div, and the text to remain in textarea, to work when I submit the form by Django; I know there is a django-quill package, but lastest commit was done in 2015, and is reported not working with new Django versions, beside I want to do it more custom. -
Django UpdateView get second form instance
I have two form for Update, the first is fine, but the second form . I am just get the fields but are empty using UpdateView, I need to set the instance: class UpdateFormView(UpdateView): model = To form_class = ToForm template_name = 'service.html' success_url = '/' def get_context_data(self, **kwargs): context = super(UpdateFormView, self).get_context_data(**kwargs) form_class = self.get_form_class() context['form'] = self.get_form(form_class) context['form_up'] = getattr(self, 'form_up', self.get_second_form()) return context def get_second_form(self): if self.request.method == 'POST': return UpForm(self.request.POST) else: return UpForm() Thanks. -
how to connect Django server with android app for conitnous sending of data bidirectionally?
I have developed a Django server and running on local host. now i want to connect my android app which collects some data in the background service and send that data to server. -
request.post with model in editable = false
I have a problem with request.post and editable = false my model created_by = models.ForeignKey(User, null=True, editable=False) my shell >>> r = requests.post(url, auth=('admin', '1234567!'), data = {"name":"John Coral","created_by":1}) >>> print(r.text) {"id":35,"name":"John Coral","created_by":null} my results: "created_by":null how to "created_by":1 with editable=False ??? -
Query In a detail view
There is a detail view displayed in a form of table. I want a write a search query that displays the found result. The data is displayed in a tabular form and has a search on the top. ClientInfo is the table that has all the information about the client. Models.py class ClientInfo(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE) insurance_name = models.CharField(max_length=250) cpt_code = models.CharField(max_length=100) subject = models.CharField(max_length=250) update = models.CharField(max_length=10000) date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) update_by = models.CharField(max_length=250) Detail.html <table class="table table-bordered table-hover"> <tr> <th scope="col"><small>INCURANCE NAME</small></th> <th scope="col"><small>CPT-CODE</small></th> <th scope="col"><small>SUBJECT</small></th> <th scope="col"><small>UPDATE</small></th> <th scope="col"><small> DATE</small> </th> <th scope="col"><small> UPDATE DATE</small> </th> <th scope="col"><small> UPDATED BY</small> </th> <th scope="col"><small>Edit</small></th> </tr> </thead> <tbody> <tr> {% for item in client.clientinfo_set.all %} <td><small> {{ item.insurance_name }}</small></td> <td><small>{{ item.cpt_code }}</small></td> <td><small> {{ item.subject }}</small></td> <td><small><p>{{ item.update }}</p></small></td> <td><small><p>{{ item.date }}</p></small></td> <td><small>{{ item.update_date }}</small></td> <td><small>{{ item.update_by }}</small></td> <td><small></small><a href="">Edit Info</a></td> </tr> <br> {% endfor %} </tbody> view.py class IndexView(generic.ListView): template_name = 'update/index.html' context_object_name = 'all_client' def get_queryset(self): return Clients.objects.all() class DetailView(generic.DetailView): context_object_name = 'client' model = Clients template_name = 'update/detail.html' class ClientCreate(CreateView): model = Clients fields = '__all__' class ClientInfoCreate(CreateView): model = ClientInfo fields = '__all__' class ClientUpdate(UpdateView): model = Clients fields = '__all__' class … -
Unapply migrations
I have app(example) and there is only one migrations. And I have changed it and I want to unapply and apply it again. If there are many migrations and I want to unapply 0002 migrations, I would use: django-admin migrate example 0001 but question is how can I unapply first migration? -
I am getting unknown geoip2 error
I am trying to test geoip but its not working, I did following steps:- $ pip install geoip2 In settings.py GEOIP_PATH = os.path.join(BASE_DIR, 'geoip') INSTALLED_APPS = [ 'geoip2', ] In terminal $./manage.py shell $ from django.contrib.gis.geoip2 import GeoIP2 $ g = GeoIP2() I got error i.e. raise GeoIP2Exception('GeoIP path must be a valid file or directory.') django.contrib.gis.geoip2.base.GeoIP2Exception: GeoIP path must be a valid file or directory. -
Static files on Django + Apache2 gives URLconf error
I am trying to integrate a downlaoded bootstrap theme into my live website aerocred.com. I have a /static directory at the root level of the django project (where manage.py resides) which contains all of my css/javascript files. From my settings.py STATIC_URL = '/static/' STATICFILES_DIR = '/var/www/html/aerocredRoot/static' In my index.html (% load static %) ...href="{% static 'assets/web/.......' %}"> and my urls.py urlpatterns = [ url(r'^%', views.index), url(r'^admin/', include(admin.site.urls)), ] using Django 1.11.13. On the network inspector with internet browser i keep getting Using the URLconf defined in Aerocred.urls, Django tried these URL patterns,in this order: ^$ ^admin/ The current URL, static/assets/bootstrap/css/bootstrap.min.css, didn't match any of these. I have tried moving the static folder to a subdirectory of my app, messing with STATIC_ROOT and doing collectstatic stuff to no avail. -
Send onetime password reset link to user as a django Admin
I am currently using the method in this link Django Password reset with djangos built in password reset view and a SMTP server on GMAIL to allow users to reset forgotton passwords through a link sent to email. I was wondering how I would send this one time link to reset password to a different email from django admin,if in case the user did not have access to his old email? -
django how to annotate count in other table
Using django2.0.2 python3.4 drf skip details ex)meta,password,postcontent ... models.py class Userinfo(models.Model) usersuid = BigAutoField(db_column='UserUID', primary_key=True) username = models.CharField(db_column='UserName') class Postinfo(models.Model) postuid = BigAutoField(db_column='PostUID', primary_key=True) useruid = models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) class Postreply(models.Model) replyuid = BigAutoField(db_column='ReplyUID', primary_key=True) useruid = models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) postuid = models.ForeignKey( 'Postinfo', db_column='UserUID', on_delete=models.CASCADE) replystep = models.IntegerField(db_column='ReplyStep') replydepth = models.IntegerField(db_column='ReplyDepth') replystep is Order of reply on posts replydepth is Order of replys on replys (like @username at facebook commtent) myviews.py usermodel = Userinfo.objects.get(useruid=request.get("useruid")) usermodel.postreply_set.all().values('replyuid','postuid','useruid','replystep','replydeth').annotate(re_replycount=('???')) re_replycount is like this query SELECT COUNT(*) FROM PostReply WHERE PostUID = t1.PostUID AND ReplyStep = t1.ReplyStep AND ReplyDepth > 0 i tried Postreply.objects.filter((Q(postuid=F('postuid')) & Q(replystep=F("replystep")) & Q(replydepth__gt=0))).count(), output_field=IntegerField()) this queryset in '???' but Strange result -
How to integrate new payment gateways with django-payments?
I want to integrate payments for a personal Django project that I'm working on. Saleor uses django-payments for payment processing. Unfortunately, most of them don't work here in India. Cybersource does work but their transaction fees are a bit higher compared to the payment gateways from India. I'd like to implement something like Razorpay or Instamojo into django-payments such that I don't end up breaking Saleor in any way but I don't have the faintest idea on how to start. I clone the package and then what? I was suggested to use the "dummy" as reference to implement the functionality but I've got no idea on how to test if it even works. How should I go about that? I don't see any contributing guidelines as well. I don't mind contributing back to the repo as well. I just want someone to point me in the right direction and I will take it forward from there. Thank you! -
Django - add widget option in form.py Meta class?
models.py from django.db import models class user(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) forms.py from django import forms from second_app.models import user class NewUserForm(forms.ModelForm): class Meta: model = user fields = '__all__' In a normal forms.py that doesn't inherit from the models, you can use field = forms.CharField(widget=forms.HiddenInput) to specify how the input field will be displayed to the users. How can this be done, when my forms.py is inheriting the class defined in models.py? -
Django Get POST id before assignment to database
views.py class Post(CreateView): fields = ('title', 'desc') model = models.Post def form_valid(self, form): self.object = form.save(commit=False) self.object.desc = self.object.id <---- self.object.save() return super(ModelFormMixin, self).form_valid(form) how to get object id from post before assignment? iam trying use self.object.id but return none