Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create link in django admin to custom django admin url?
how to create link in django admin to custom django admin url i have 2 apps in django admin and i want to link from app1 to custom url in app 2 admin.py APP1 class APP1Admin(ModelAdmin): list_display = ('xx','request_me') def request_me(self,obj): reverse_path = reverse("admin: APP2_TargetLink",args=(obj.pk,)) # My Problem is How to link to func APP2 target link return '<a href="%s"> link </a>'%(reverse_path) request_me.allow_tags =True admin.py APP2 class APP2Admin(ModelAdmin): def get_urls(self): urls = super(APP2Admin, self).get_urls() my_urls = [ url(r'(\d*)/target_link/$', self.admin_site.admin_view(self.target_link_view),name="TargetLink"), ] return my_urls + urls def target_link_view(self,request,id): ... return TemplateResponse(request, template, context) -
i am getting error 500 internal server on when using django with ngoku to host my facebook bot
# ------------------------ Fill this with your page access token! ------------------------------- PAGE_ACCESS_TOKEN = "" VERIFY_TOKEN = "2318934571" jokes = { -----code intentionally removed for brevity--- } def post_facebook_message(fbid, recevied_message): # Remove all punctuations, lower case the text and split it based on space tokens = re.sub(r"[^a-zA-Z0-9\s]",' ',recevied_message).lower().split() joke_text = '' for token in tokens: if token in jokes: joke_text = random.choice(jokes[token]) break if not joke_text: joke_text = "I didn't understand! Send 'stupid', 'fat', 'dumb' for a Yo Mama joke!" user_details_url = "https://graph.facebook.com/v2.6/%s"%fbid user_details_params = {'fields':'first_name,last_name,profile_pic', 'access_token':PAGE_ACCESS_TOKEN} user_details = requests.get(user_details_url, user_details_params).json() joke_text = 'Yo '+user_details['first_name']+'..! ' + joke_text post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s'%PAGE_ACCESS_TOKEN response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":joke_text}}) status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg) pprint(status.json()) class CryptsView(generic.View): def get(self, request, *args, **kwargs): #return HttpResponse("Hello World!") if self.request.GET['hub.verify_token'] == '2318934571': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle Facebook messages def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary incoming_message = json.loads(self.request.body.decode('utf-8')) # Facebook recommends going through every entry since they might send # multiple messages in a single call during high load for entry in incoming_message['entry']: for message in entry['messaging']: # Check to make sure the … -
Select a valid choice.[<selection>]is not one of the available choices. Error
What I want is multi-selected anwsers chosen to be saved and submitted to DB However I get this error on each of the questions. my models.py class preferences(models.Model): cuisine = ( (1,u'Italian'), (2,u'American'), (3,u'French'), (4,u'Japanese'), (5,u'Russian'), (6,u'Chinese'), (7,u'Mexican'), (8,u'Indian'), (9,u'Middle Eastern'), (10,u'Thai'), (11,u'Spanish') ) vegeterian = ( (1,u'Yes'), (2,u'No'), (3,u'I appreciate both') ) lunch = ( (1,u'Cafe'), (2,u'Restaurant'), (3,u'Fast Food'), (4,u'Takeaway'), (5,u'Grocery/Lunch Box') ) dinner = ( (1,u'Inexpensive Restaurant'), (2,u'Fine Dining'), (3,u'Takeaway'), (4,u'Fast Food'), (5,u'Delivery'), (6,u'Cooking at home'), (7,u'Cheeky Bar') #Make it with a hint that having a dinner w/ a cheeky pint ) Friday = ( (1,u'Bar'), (2,u'Night club'), (3,u'Karaoke'), (4,u'Netflix & chill'), (5,u'Video games'), (6,u'Cinema'), (7,u'Theater'), (8,u'Restaurant'), ) weekend = ( (1,u'Hiking'), (2,u'Sport activities'), (3,u'Attending sport events'), (4,u'Music events'), (5,u'Art/Science exhibitions'), (6,u'Chilling at the park'), (7,u'Video games'), (8,u'Cinema'), (9,u'Theater'), (10,u'Chilling at home') ) UserID = models.ForeignKey(User,related_name='User', null=True,default='') cuisine = models.ManyToManyField('self',choices=cuisine, max_length=20,blank=False,default='') cuisine_extra = models.CharField(max_length=25) vegeterian = models.CharField(max_length=15,choices=vegeterian) lunch = models.ManyToManyField('self',choices=lunch,max_length=20,blank=False,default='') dinner = models.ManyToManyField('self',choices=dinner,max_length=20,blank=False,default='') Friday = models.ManyToManyField('self',choices=Friday,max_length=20,blank=False,default='') weekend = models.ManyToManyField('self',choices=weekend,max_length=40,blank=False,default='') Here I use M2Mfield as we are storing multiple items and use it on the same model('self'). modelform.py class preferencesForm(ModelForm): """def __init__(self, *args, **kwargs): super(preferencesForm, self).__init__(*args, **kwargs)""" class Meta: model = preferences fields = ['cuisine', 'cuisine_extra', 'vegeterian', 'lunch', 'dinner', … -
PyCharm - remove green lines which appeared upon inserting language reference
I'm working with django in PyCharm and these green lines are really annoying me. They appeared when I inserted some language reference (I can't recall which one exactly...) and I don't know how to turn it off. I tried editing some PyCharm settings but to no avail... On the below picture I tried turning all inspections off, but it didn't work. What is this sorcery and how do I brake it? -
Save File Openpyxl with Django
I have an application developed with django 1.10, from which I am generating reports in excel with Openpyxl, what I need is to save the file in a server path before returning it in the response. I appreciate your collaboration -
Is there a simple way to upload images from my posts, header and avatar to imgur from Django?
I am looking for how to make users to make a post, or put an avatar and even an image of header this is uploaded to Imgur. What are the disadvantages of uploading images to imgur? Is it advisable to do so? My source code can be found in Github and the demo in Heroku. https://plxapp.herokuapp.com/ https://github.com/cotizcesar/plaxedpy If you get a bug in my code, do not hesitate to send a pull request. -
How to delete rows with duplicate columns in django
I have a model class Foo(models.Model): first = models.CharField() second = models.CharField() data I have is first second 1 2 1 2 1 2 3 4 Now I want to delete all duplicate rows and keep one entry. The end result first second 1 2 3 4 How do I do this? I checked this question but could not figure it out properly. Annotate I have tried foo_ids = Foo.objects.annotate(first_c=Count('first'), second_c=Count('second')).filter(first_c__gt=1, second_c__gt=1).values('first', 'second', 'id') Then try and figure out how to not delete one of each I list of duplicates. -
Django save field as NULL
I have form fields, I would like to keep them empty sometimes. The problem is that save() method in the views is expecting the filed and throwing error. my forms: from django import forms from cProfile import label class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file' ) time_from = forms.DateTimeField( label = 'select range of time, from' ) time_to = forms.DateTimeField( label = 'to:', required = False ) my models: from django.db import models import uuid from django.utils import timezone from celery.worker.strategy import default class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) time_from = models.DateTimeField(default=None, null=True, blank=True) time_to = models.DateTimeField(default=None, null=True, blank=True) my views: def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile'], time_from=request.POST['time_from'], time_to=request.POST['time_to']) newdoc.save() I am trying to keep time_to field empty when submitting, but it is giving me this error: Exception Value: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] I think the reason is that newdoc.save() is expecting the DateTimeField of time_to format as u'2017-05-05 12:02:02' and getting an empty string or something like: u'' -
Integrating login with facebook in swift using Django as backend
I am trying to integrate login with Facebook in my iOS app which I did successfully. After that I want to authenticate the user and save it in my backend which is Django. What I have done is that I have a web-app with: Django Rest Framework django-rest-framework-social-oauth2 Python social auth I have studied the OAuth2 flow and also tried the example given at: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 I created an application in my backend with the help of Django OAuth toolkit and with the given client id and client secret I was successfully able to send a POST request using curl with the access token provided by Facebook. It returns me a dictionary like this , {"access_token":"An access token over here","token_type":"Bearer","expires_in":36000,"refresh_token":"Refresh token over here","scope":"read write"} I have a lot of confusions so how do I go about getting the user from my front-end and then associating and making a user in my back-end and later on checking if all the actions are done by that user (like referencing the user). What I have understood is that in my front-end which is my swift-app I should be making my user login with Facebook. Facebook authenticates the user and then returns an access token. … -
How do you render JSON using this template in django?
I looked through the source code of the following page: http://visjs.org/examples/timeline//resources/data/basic.json and it only showed raw json data. How are you able to represent json data with the different headers "JSON", "raw data". Is this possbile with django? enter image description here -
Django ModelMultipleChoiceField not displaying correct Choice names
I am attempting to create a Multiple Choice Field from a view on my postgres db, however the webpage is displaying incorrectly. Specifically, while it provides the correct number of selections it does not name them by the "check_name" field, instead it names every selection 'Check object'. Here's my code: models.py class Check(models.Model): pkey = models.AutoField(primary_key=True) cif = models.CharField(max_length=255) check_name = models.CharField(max_length=255) description = models.TextField() class Meta: managed = False db_table = 'precheck_check' forms.py class ProcessFileForm(forms.Form): checks_to_run = forms.ModelMultipleChoiceField( queryset = Check.objects.all(), to_field_name = "check_name", widget = forms.CheckboxSelectMultiple, ) views.py def successful_upload(request): if request.method == 'POST': form = ProcessFileForm(request.POST, user=request.user) if form.is_valid(): return render(request, 'precheck/checks_successful.html') else: form = ProcessFileForm() return render(request, 'precheck/select_checks.html',{'form':form}) Of note, I am pulling the data from a view named 'precheck_check' in the postgres db. It seems to be seeing the view correctly since it is giving me the correct number of choices. -
Django second DB returns None
To set up the two databases I followed the documentation which includes: Adding the DB information in setting.py DATABASES={} Created a matching model of the model from another DB Run migrate (Which created a blank table for the model in second DB) from client_portal.models import client_names def try_names(request): cn = client_portal.objects.using('second_db').filter(client_id='170155').last() print(cn.last_name) cn is None. It shouldn't because the data exists in the second DB. My assumption is it's querying the data from the default db because I missed a step. Do I need to 'install' a router even if I will use using() exclusively? If so, where do I save the file? DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter'] That example was from the documentation. Where does Django expect the router file? Thank you for help. -
Django name 'kwargs' is not defined
I just want to make a redirection by calling a view and pass a variable. I have the following error : name 'kwargs' is not defined My view which is supposed to get the variable : def view_register(request, **kwargs): form = MinimumRegisterForm() My view which is supposed to pass the variable (at the end) : def view_games(request): media = settings.MEDIA if request.method == 'POST': form = MinimumRegisterForm(request.POST) if form.is_valid(): identifiant = form.cleaned_data['identifiant'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirm_password = form.cleaned_data['confirm_password'] sex = form.cleaned_data['sex'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.INFO, 'Cette adresse email est déjà utilisé.') return redirect(view_register) if password == confirm_password: strengh = password[0].isalpha() if all(c.isalpha() == strengh for c in password): messages.add_message(request, messages.INFO, 'Le mot de passe doit contenir au moins 8 charactères lettres et chiffres.') return redirect(view_register, identifiant=kwargs['identifiant'])** Did I miss something ? -
Can't get dynamic python ModelChoiceField to work
I'm new to python and trying to understand how to get a dynamic ModelChoiceField to work. It works fine when I select an object with all but I'm trying to get the dropdown to reflect a user's attribute. Here is my code: Forms.py class ViewByMake(forms.Form): dropdown = forms.ModelChoiceField(queryset=Make.objects.none()) def __init__(self, user, *args, **kwargs): user = kwargs.pop('user') super(ViewByMake, self).__init__(*args, **kwargs) qs = Make.objects.filter(user=user) self.fields['dropdown'].queryset = qs self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' Views.py def view_bymake(request): form = ViewByMake(request.POST or None, user=request.user) if request.method == 'POST': if form.is_valid(): make = form.cleaned_data['dropdown'] return HttpResponseRedirect(make.get_absolute_url1()) return render(request,'make/view_make.html',{'form':form}) This code works fine if I remove all user= references but then only returns the full make objects list which is not what I want. I found a very similar question on StackOverflow, but when I duplicated the code identically, it still doesn't work and it is giving me the following error: init() got multiple values for argument 'user' I searched the end of the internet on this topic. I'm open to other ideas if I'm approaching this poorly. I'm trying to basically get a filtered list based on criteria associated with a user's profile. I definitely need the drop down field to be specific to a … -
django context must be a dict rather than Context
please solve the issue of context must be a dict rather than Context in django. enter code here code def home(request): form=signinform(request.POST or None) title="Sign in" if request.POST: if form.is_valid(): password = form.cleaned_data['password'] username = form.cleaned_data['username'] user = authenticate(username=username, password=password) if user is not None: login(request,user) return redirect("/authencite_user_login=only/") return render(request ,"home.html", {"form": form, "title": title}) enter image description here -
Filter based on a amount of object returned by another query in Django
I have two classes in my model Painting and Hit. class Painting(models.Model): objectNumber = models.CharField(max_length=128) class Hit(models.Model): painting = models.ForeignKey(Painting) In this way, each painting can be connected to multiple hits, but each hit can only be connected to one painting. I wish to select each painting that's connected to 3 or less hits. How can I do this? Possible solutions: I figured I could do some sort of for loop... for painting in Painting.objects.all(): if len(Hit.objects.filter(painting=painting)) > 4: # and then append it to a list or something ... but I assume there's some native filter I can apply that I can't seem to find. Or else I could add a field to Painting to count how many hits are related to it, but that seems illogical. -
Datas misaligned from the headers when using bootstrap in django/python template
I'm using bootstrap in my django template and i tried to align correctly the headers and the datas got from a fobi form. First of all, i instanciate my bootstrap such as : <div class="row"> <div class="col-xs-9 col-sm-9 col-lg-9"> <!-- Form element plugins --> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-striped db-store-saved-form-data-entry-table"> Then I collected my headers with this first loop : <thead> <!-- cétait td à la place de th --> <tr> {% for entry in headers %} <th> {{ entry }} </th> {% endfor %} </tr> </thead> And i get all the datas with these loops too, everything working good until there : <tbody> {%for entry in headers%} {%for entry in entries%} <tr> {%for cle, valeur in entry.all_form_entry_json%} {%for key, valor in headersLoop%} {%if key == cle%} <td> {{cle}}{{valeur}}</td> {%if entry == 'picture'%} {%} {% endif %} {% endfor %} {% endfor %} </tr> {% endfor %} </tbody> The first result are aligned properly with the headers : name goes with name, geom with geom and so on. But after a few entry, the datas are switched to the previous row and here begins the misalignment : Now geom goes to name and value to geom ! … -
Retrieving path of referrer in Django template
I know one can get the path of a url in a Django template via {{ request.path }}. But is it possible to get the path of the referrer? {{ request.META.HTTP_REFERER.path }} wouldn't work. -
Problems to create a new model with other related models
I'm trying to create a Transaction, which has two other related models Account and Category, but I'm facing errors in the API. First the models.py: class Transaction(models.Model): user = models.ForeignKey(User, default=None) account = models.ForeignKey(Account, default=None) category = models.ForeignKey(Category, default=None) ... Then, the transactions' serializers.py contains the following: class TransactionSerializer(serializers.ModelSerializer): account = AccountSerializer() category = CategorySerializer() It allows me to display the related models as a whole object in the JSON response, which I need, but it's failing when attempting to create a new Transaction. The Meta class requires to have within its fields list, the account and category: class Meta: model = Transaction fields = ('id', 'user', 'account', 'category', 'name', 'amount', 'description', 'created_at') But if I keep things like this, it will show the error: Invalid data. Expected a dictionary, but got str.. I tried passing only the id of the related models but then the error django.utils.datastructures.MultiValueDictKeyError: "'account'" shows up, and I'm stuck with it. -
django:ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I am new to the programming and i have been trying to develop an audio player using jQuery/HTML5.The audio source to the jquery is being passed by AJAX response.The audio play is fine in my local host while using Laptop.But if i connect my smartphone and try to play the audio, i get the "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host" error. Can someone provide me a solution?. Thanks in Advance Exception details: Traceback (most recent call last): File "C:\Python35\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python35\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python35\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\Python35\lib\wsgiref\handlers.py", line 453, in _write self.stdout.write(data) File "C:\Python35\lib\socket.py", line 593, in write return self._sock.send(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [18/Jul/2017 18:04:21] "GET /images/mpthreetest.mp3 HTTP/1.1" 500 59 Exception happened during processing of request from ('192.168.1.35', 33876) Traceback (most recent call last): File "C:\Python35\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python35\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python35\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\Python35\lib\wsgiref\handlers.py", line 453, in _write self.stdout.write(data) File "C:\Python35\lib\socket.py", line 593, in write return self._sock.send(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by … -
Django: filter by DateField with db_index is a lot slower than filter by DateTimeField without db_index
In one of my models I have the following fields: creation_time = models.DateTimeField(auto_now_add=True) creation_date = models.DateField(db_index=True, auto_now_add=True) If I do the following filter using the creation time (DateTimeField field): MoModel.objects.filter(id__in=user_ids, creation_time__range=[start_date, end_date]).count() It takes few ms to run, as expected. But if I do the same filter on the creation date (DateField field with db index): MoModel.objects.filter(id__in=user_ids, creation_date__range=[start_date, end_date]).count() It takes few minutes to finish... Eventually I get almost the same result as above, but after a long time. I though both fields are stored the same way in the DB and the only difference is how django serialize / deserialize them into Python objects (and ofc date field getting default midnight time). So why using the date field is so much slower? Is it because of the db_index (if so, why)? Thanks, -
LDAP authenticatzion and page redirecd in Django
I'm trying to create an LDAP authentication page, whereby a user logs in and if the credentials are correct, is then redirected to another page, whereby the logged-in user then can search for a user in the LDAP server. The problem I previously faced was creating 2 or more views, where once the user is logged in, the conn object is then used as a parameter for another view function. But the conn object can't simply be passed from one view to another without the user then been logged out again, so I'm having to perform all these tasks and redirecting in one view only. See below: def ldap_authentication(request): if request.POST: username = request.POST['username'] password = request.POST['password'] domain_and_login = '{}\\{}'.format(DOMAIN_NAME, username) # Should be the same as conn.extend.standard.who_am_i() # Define the server server = Server(LDAP_SERVER, get_info=ALL) # Connection and Bind operation try: conn = Connection(server, user=domain_and_login, password=password, \ auto_bind=True,check_names=True) conn.start_tls() # Session now on a secure channel. return render(request, 'ldap_user_search.html') # Here do something so that after the page is rendered, the input data # from the form is used as searchFilter, for example: ''' if request.POST: searchFilter = request.POST['search_user'] conn.search( search_base=LDAP_AUTH_SEARCH_BASE, search_filter= '(cn={})'.format(searchFilter), # This is the user being … -
Access Django over OpenVPN
I am new to Django and OpenVPN also. I have created Django server on windows 7 system. This is working fine if I us server from IP address of LAN. But I am unable to access if I start Django server with IP address provided by Open VPN. I am unable to get how to resolve it. -
get null or empty queyset in django
def get_queryset(self): key = self.request.GET['search_text'] customer_list = customer_info.objects.all() # temp = for term in key.split(): temp = temp | customer_list.filter(Q(fName__icontains= term)|Q(lName__icontains= key)) return temp how can I assign the value of temp to null query set of customer_info objects so that I could union temp with the filter list then return it. Basically, i am splitting the search box text and then filtering the table with each string in the list and combining the result initial result -
AttributeError: 'NoneType' object has no attribute 'decide_threaded'
python3.4 scripts/diff_drive.py --remote=http://10.100.33.241:8887 --config=diff_vehicle Detected running on rasberrypi. Only importing select modules. Using TensorFlow backend. PiVideoStream loaded.. .warming camera /usr/lib/python3/dist-packages/picamera/encoders.py:544: PiCameraResolutionRounded: frame size rounded up from 160x120 to 160x128 width, height, fwidth, fheight))) Traceback (most recent call last): File "scripts/diff_drive.py", line 58, in <module> car.start() File "/home/pi/donkey/donkey/vehicles.py", line 41, in start angle, throttle, drive_mode = self.remote.decide_threaded(img_arr, AttributeError: 'NoneType' object has no attribute 'decide_threaded' Exception ignored in: <bound method Session.__del__ of <tensorflow.python.client.session.Session object at 0x6cea7ab0>> Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py", line 581, in __del__ TypeError: 'NoneType' object is not callable Running into this error while building a donkey car on Raspberry Pi 3, with an Adafruit DC Motor HAT. Will post necessary files as required. The Pi and the established remote are connecting nut only for a brief period of time. Here's a snippet of code from the vehicles.py def start(self): start_time = time.time() angle = 0. throttle = 0. #drive loop while True: now = time.time() start = now milliseconds = int( (now - start_time) * 1000) #get image array image from camera (threaded) img_arr = self.camera.capture_arr() angle, throttle, drive_mode = self.remote.decide_threaded(img_arr, angle, throttle, milliseconds) And here's the snippet with the definition of decide_threaded: def decide_threaded(self, img_arr, angle, …