Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pycharm starting runserver after external tool - bash script
I am trying to get pycharm to start postgres and redis before it launches the local runserver. When the external tool is not there, the runserver opens the browser and connects correctly, having started the two services outside of pycharm. I added a bash script to the run configuration and it works, as evidenced in pycharm's console log. However, it doesn't launch the browser or the runserver itself. How do I get it to go theis extra step? Thanks -
Google oauth fail with "Code was already redeemed" error
I am trying to make authorization from Google on my website. And at the step of exchanging code to access_token I obtain error: Code was already redeemed It happens with using django-allauth lib aswell as with using recommended by Google libs and code: redirect_uri = 'http://example.com/accounts/google/login/callback/' config = {u'web': {u'redirect_uris': redirect_uris, u'token_uri': u'https://accounts.google.com/o/oauth2/token', u'auth_uri': u'https://accounts.google.com/o/oauth2/auth', u'client_id': client_id, u'client_secret': client_secret, } } flow = google_auth_oauthlib.flow.Flow.from_client_config( config, scopes=['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'] ) flow.redirect_uri = redirect_uri flow.fetch_token(code=code) When I am using test config with localhost url on my local machine, authorization works fine. But when I use production server i got error. In google web application I have both redirect URIs: http://localhost:8888/accounts/google/login/callback/ http://example.com/accounts/google/login/callback/ As I can see, code exahnging only once, so why it could happens and how to fix it? -
filter not working inside for loop in django
I am trying to fetch data inside the for loop in my view.This is my code: def func(request): list = UserBookmark.objects.values('bookmark').filter(tag = "a") print list for i in list: print i tag_ids = UserBookmark.objects.values('tag').filter(bookmark = i) print tag_ids return render(request,'index.html') I am getting a value of i when i print i.Also i have records where bookmark = i print i gives values like these: {u'bookmark': u'https://classroom.udacity.com/courses/cs101/lessons/48753036/concepts/487183640923'} and when i run this query in shell: tag_ids = UserBookmark.objects.values('tag').filter(bookmark = 'https://classroom.udacity.com/courses/cs101/lessons/48753036/concepts/487183640923') i get value for tag_ids too but i am getting an empty query set in the for loop.This looks like some silly mistake but i am not able to figure it out. -
django templates syntax mixed with javascript code
My js code is in the .html django template inside a block, this way: {% estends 'base.html' %} ... some blocks here ... {% block javascript %} <script> $(document).ready(function () { ... }); </script> {% endblock %} Now I need to use in the js code some context vars passed from the view to the template. I used a option where I declared in an html element a data attr using django template syntax {{ ... }} <div id="order_id" data-order-id={{order.id}}> and with jq I got this element and read the data value. This way: var orderId = $("#order_id").data('order-id') this works fairly well, but I realized if I have the code in the same .html I can use the django template expressions as part of my js code. This way: var orderId = {{ order.id }}; var changeStatusUrl = "{% url 'orders:change_status' %}" This works fairly well too, so my question is if this is a good practice to follow with, or if this has some drawback that I will face in the future. -
How can I fix Forbidden (CSRF cookie not set.)?
I am using Django Rest Framework on backend and React on frontend. I want to upload file on server. I used "react-fileupload" before and everything worked, but now I want to use "react-dropzone" and my code doesn't work. Here is view: @api_view(["POST"]) def upload_file(request): return Response({'overview': read(request.FILES.values())}, status=status.HTTP_200_OK) Here is action: import axios ... export const upload = (file) => async dispatch =>{ const res = await axios.post('api/upload_file',{file}); dispatch({type: 'FETCH_OVERVIEW', payload: res.data.overview}) }; And my error: Forbidden (CSRF cookie not set.): /api/upload_file [13/Dec/2017 15:56:12] "POST /api/upload_file HTTP/1.1" 403 2857 -
Django inline forms cannot query, must be mode instance
I'm trying to make inline forms with class based views, i followed the instrunctions from here. The only change i've made was to give self.request.user instead of self.object to instance: models.py class Client(models.Model): user = models.OneToOneField(CustomUser) translate = models.BooleanField(default=False) class ClientData(models.Model): client = models.ForeignKey(Client) language = models.ForeignKey(Language) forms.py class ClientForm(ModelForm): class Meta: model = Client fields = '__all__' exclude = ['user', ] class ClientDataForm(ModelForm): class Meta: model = ClientData fields = '__all__' exclude = ['client', ] ClientFormSet = inlineformset_factory(Client, ClientData, form=ClientDataForm, extra=1) views.py class ClientView(LoginRequiredMixin, UpdateView): model = Client fields = '__all__' success_url = reverse_lazy('core:index') class ClientDataView(LoginRequiredMixin, UpdateView): template_name = 'core/client_data.html' model = ClientData form_class = ClientDataForm success_url = reverse_lazy('core:index') def get_object(self, queryset=None): profile = get_object_or_404(ClientData, client__user=self.request.user) return profile def get_context_data(self, **kwargs): context = super(ClientDataView, self).get_context_data(**kwargs) if self.request.POST: context['client_data'] = ClientFormSet(self.request.POST, instance=self.get_object()) else: context['client_data'] = ClientFormSet(instance=self.get_object()) return context def form_valid(self, form): context = self.get_context_data() client_data = context['client_data'] with transaction.atomic(): self.object = form.save() if client_data.is_valid(): client_data.instance = self.object return super(ClientDataView, self).form_valid(form) Whenever i try to enter the page i get: ValueError: Cannot query "asd@gmail.com": Must be "Client" instance. [13/Dec/2017 15:48:36] "GET /client-data/ HTTP/1.1" 500 143759 for this line: context['client_data'] = ClientFormSet(instance=self.get_object()) -
Can I have a main models file in a django project?
The Problem I'm working on a django project in which I need to share the same database models over multiple apps, for example when a user opens a page the page is displayed depending on user settings, which can be changed by the user in a different app than the one which displayes the page At the moment I've made the browser app which contains most of my models (because it's the one I started with) and I've got other apps like watch_file and user_settings which then import This is working but I'm noticing that I'm running into organization problems where I'm hopping from file to file to check models and I'm importing all over the place... My potential Solution I was thinking about making one big model file somewhere and just importing the models I need for every app in it's own model file, however, I read this question in which someone in the comments stated that generally this is not done Also I red this question which said that sharing models between apps isn't a good idea at all in regards to organization The question In regards to it not being a good idea to make a general … -
Prevent braintree form submit in django form wizard
I'm using a braintree drop-in UI form in a django-formtools session wizard. I have a few questions regarding this. The first of which is that in the drop-in UI the only item im storing in my form (and hence back through session data since I'm using a session wizard_) is the payment method nonce. Is this fine that doesn't seem too insecure? However, if I moved to hosted fields I'd have to ake my own form and all of these fields would then be stored in the session no? That's insecure. Second question: Whenever hitting the back button on the form wizard it automatically submits the braintree drop-in form since the wizard requires a filled form checking for validation before you can go back. How do I prevent this? What if my user decides to go back and deselect the paid option? Edit: Think using teardown on the form will work, but leaving this open for alternatives. -
django TemplateView use search filters
i am trying to make 4 different filters for a table in the template...I am using multiple models in this table. this is the code from views.py class TestView(FormView, TemplateView): template_name = 'home/main.html' context_object_name = 'pages' form_class = DomainsForm def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) list_tables = Domains.objects.all() context['lists'] = list_tables tbls_id = list_tables.exclude(status=0).values_list('id', flat=True) context['alerts_list'] = Alerts.objects.all() data = [] data_alert = [] data_page = [] for row_id in tbls_id: cron_info = get_cron_info(row_id) data.append(cron_info) context['data'] = simplejson.dumps(data) tbl = Domains.objects.get(id=row_id) t_pages = create_pg("Pages_" + tbl.tablename) query_pages = t_pages.objects.all() get_alerts = create_alerts('Links_' + tbl.tablename + '_Alerts') filter_alert = get_alerts.objects.all() page = self.request.GET.get('page', 1) paginator = Paginator(filter_alert, 10) try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) data_page.append(query_pages) data_alert.append(details) context['pages'] = data_page[0] context['all_alerts'] = data_alert[0] print context['all_alerts'] print "*" * 100 return context def form_valid(self, form): print "*" * 100 form.id print form.id return super(TestView, self).form_valid(form) this is the part from template main.html (only the form for the search filters) <form class="row" id="alertHistoryReport" method="get"> {% csrf_token %} <div class="col-sm-4"> <div class="form-group"> <label>Domains</label> <select class="form-control select2" style="width: 100%;" name="sk_dmn"> <option selected="selected">None</option> {% for list in lists %} {% if list.status == 1 %} <option value="{{ list.id … -
How to filter values on foreign key field editing?
I have a three simple models: class Task(models.Model): code = models.CharField(max_length=200, unique=True) tags = models.ManyToManyField(Tag, blank=True) class Session(models.Model): tasks = models.ManyToManyField(Task, through='TaskInSession') and class TaskInSession(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) count = models.IntegerField() For session editing I have: class SessionAdmin(admin.ModelAdmin): inlines = [TaskInSessionInline,] exclude = ('tasks', ) Is it possible to add tasks filterting by tag possibility, for easy task selection on session editing? -
Insert Ads Code (Like Google Adsense) in Django Website
I have developed a newsportal with Django.Now I want to insert adsense code / any ads code in my site.How can I do that? -
Django OAuth as separate service
Is it possible to configure Dajngo App to put OAuth Provider to separate service (different machine, micro service) and bridge authentication requests to that one? I couldn't find anything helpful in django-oauth-toolkit documentation, but based on the source code, it seems it should be possible to bridge all /oauth/ requests to another server and only use authentication middleware on the current one. Would be this good approach, or is there better way to do it? ps. Problem is that code base I work on uses older Django version and python. I would like to start split functionality to "microservices" with up-to-date versions, and this would be my first try. -
Show only one field in Django Admin panel?
I have the following two classes declared in admin Django files. On the admin panel 3 inline inputs are shown, I only want to show 1 input. Any guesses on why 3 inline inputs are shown instead of just one? class OriginURLInline(ViewPermissionMixin, admin.StackedInline): model=IncentiveReferrerURL verbose_name = 'Promotion URL' verbose_name_plural = 'Promotion link' fields = ('origin_url',) class IncentiveReferrerURL(TimeStampedModel): # The TimeStampedModel will provide self-updating 'created' and 'modified' fields on the inherited model incentive = models.ForeignKey( Incentive, on_delete=models.PROTECT, null=True, blank=True, ) origin_url = models.CharField( max_length = 100, verbose_name = 'Promotion Name:', help_text='Please e' ) -
How to run Django test with module located at parent directory?
I want to run Django test with module located at parent directory. Though I tried relative path, it failed, generating an Exception. For example like the below. root ├── project │ ├── __init__.py │ └── manage.py └── tests ├── __init__.py └── test_module.py $ pwd /root/project $ python manage.py test ..tests.test_module Traceback (most recent call last): File "manage.py", line 78, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 393, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 209, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 121, in build_suite tests = self.test_loader.loadTestsFromName(label) File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) ValueError: Empty module name -
Django-registration reset password error
I'm using django-registration in my Django application with HMAC workflow. An email is sent with the activation link to the user after registration. I'm using the versions bellow: Django==1.11.1 django-registration==2.3 I saw here that there are two different views (function ou class) that could have being used. I put a breakpoint in the auth_urls.py and saw that in my application the registration.auth_urls_classes that are being used. I've created a link to go to my reset password page: <a class="g-font-size-12" href="{% url 'auth_password_reset' %}">Esqueceu a senha?</a> This link sends to the template password_reset_form.html, it is in the image bellow: After typing the email address and send the form, the email is sent correctly (email arrived to me), but the error bellow occurrs: My urls are defined as bellow: Note that the name of the success url (auth_password_reset_done') was "appended" in the link, instead of being replaced by the pattern. I couldn't figure out why, though. -
django 1.11 Template can't not load static file
i set it up STATICFILES_DIRS STATIC_URL in settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'projectName', 'static'), ] and i want to use javascript files in template but it is not working. js file path is app/static/app/new.js and i used it in template using this code {% load static %} <script type="text/javascript" src="{% static "app/new.js" %}"> $(document).ready(function(){ alert(1); new_function(); }); </script> function in new.js as well as alert does not working. If I delete the src part in script tag, the alert works fine. I can see the new.js script by accessing the path that appears in the chrome developer tool. What did I do wrong? -
Connect to two cloudsql instances from GAE
I can't figure out the syntax to connect my AEF environment to multiple cloud_sql instances. These are the two configs that I have tried: beta_settings: cloud_sql_instances: - pore-gdic:europe-west1:a-django - pore-gdic:europe-west1:a-airflow-5 Failed: ERROR: (gcloud.app.deploy) Error Response: [13] Invalid Cloud SQL name: [] based on the response from this question: Connecting to multiple CloudSQL instances using Cloud sql proxy? beta_settings: cloud_sql_instances: pore-gdic:europe-west1:a-django,pore-gdic:europe-west1:a-airflow-5 Doesn't fail on deployment, but doesn't work as a webpage at all. Does anyone have a working solution to this problem. For completeness, one db is running MySQL and the other postgres. So ports isn't an issue. -
How can I use a custom namespace in a Spyne Fault?
I'm using Spyne to offer a SOAP WS in my django application. My goal is to replicate an existing WS, and one thing I cannot do yet, is add a custom namespace for the FaultCode. I want something like that: <faultcode xmlns:a="NAMESPACE_X">a:InternalServiceFault</faultcode> By default, Spyne adds the namespace of the envelope (xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/"): <faultcode>soap11env:InternalServiceFault</faultcode> Is it possible? -
How, with Python, can i retrieve the data content of a POST request ?
I have a WooCommerce webhook who sends a POST request to a specific URL (https://po.tic.ch/test.py) for every order on my website. This WooCommerce is running on https://vi.tic.ch. For each order, i want to retrieve the informations of the POST like user ID = 12, product ID = 234, price = 50CHF, etc. to save it in my server po.tic.ch. The server po.tic.ch runs Django with Apache2. He have the port 80 open and receives all the POSTS but i don't know how to get the his content on my test.py file. I tried this on my test.py file: r = requests.POST('id') return[r] but it make a 500 error Thank You! -
django TemplateView use pagination and getting only 1 result
i want to make pagination out of filter_alert only. And i also get only the last result out of filter_alert. I will explain more below the code. This is my code in views.py class TestView(FormView, TemplateView): template_name = 'home/main.html' context_object_name = 'pages' paginate_by = 10 form_class = DomainsForm def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) list_tables = Domains.objects.all() context['lists'] = list_tables tbls_id = list_tables.exclude(status=0).values_list('id', flat=True) context['alerts_list'] = Alerts.objects.all() data = [] for row_id in tbls_id: cron_info = get_cron_info(row_id) data.append(cron_info) context['data'] = simplejson.dumps(data) tbl = Domains.objects.get(id=row_id) t_pages = create_pg("Pages_" + tbl.tablename) query_pages = t_pages.objects.all() context['pages'] = query_pages get_alerts = create_alerts('Links_' + tbl.tablename + '_Alerts') filter_alert = get_alerts.objects.all() context['all_alerts'] = filter_alert return context So in the table Domains i have 3 id's, 1 of them has the status=0. I want to get the other 2 id's and pass them through the for loop. But when i pull out the results in the template...i only get the last id. I also want to implement the pagination...i usually use this code...but it doesn't work in the TemplateView. all_alerts = get_alerts.objects.all() page = request.GET.get('page', 1) paginator = Paginator(all_alerts, 10) try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) context['all_alerts'] = … -
searching multiple elements in different django models using haystack search
Any help on how to search multiple elements input in Django separated by comma. I have two fields of the same names in all my models. I got this ajax.js code: $(function(){ $('#search').keyup(function(){ $.ajax({ type: "GET", url: "/predictgene/search/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } My search index. I have about 25 search indexes, I just need to be able to search multiple input text separated with a comma or space. The results should show the name of the models and all the elements search for. my search_index.py class ArthrogryposisIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) gene = indexes.CharField(model_attr='gene') # prediction = indexes.CharField(model_attr='prediction') # pub_date=indexes.DateTimeField(model_attr='pub_date') content_auto = indexes.EdgeNgramField(model_attr='gene') def get_model(self): return Arthrogryposis def index_queryset(self, using=None): """used when the entire index for model is updated.""" return self.get_model().objects.all() -
how to handle httpresponseredirect
test2/urls.py from django.conf.urls import url from .import views from .forms import forms urlpatterns=[ url(r'^$',views.index,name='index'), url(r'^thankyou/$',views.thankyou,name='thankyou') ] test1/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test2/',include('test2.urls')), ] views.py this view should redirect to /test2/thankyou/ but why it is going to /thankyou and what to do enable the view given by redirect method from django.shortcuts import render from django.http import HttpResponseRedirect,HttpResponse from .forms import Get_name # Create your views here. def index(request): if request.method == 'POST': form = Get_name(request.POST) if form.is_valid(): return HttpResponseRedirect('/thankyou/') else: form = Get_name() return render(request, 'test2/name.html' , {'form':form}) def thankyou(request): return HttpResponse('sai chaitanya') name.html after submitting the form it should redirect to test2/thankyou but it is going to /thankyou. <form action="/thankyou/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> forms.py from django import forms user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')] class Get_name(forms.Form): user_name = forms.CharField(label='user name',max_length='50',required=True) pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password') pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password') email = forms.EmailField(label='email',max_length='100') mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10') address = forms.CharField(label='Address',max_length='100') user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice)) -
Accessing JSON key & value passed as variables in Django views
What i am trying to do ? I am trying to check if the entered email or username already exists in the database by passing JSON Key and Value as variables from signup form ( using ajax ) to Django views. The Key holds either the 'username' or 'email' and Value holds the required value (eg: 'dave' or 'example@gmail.com'). What is the problem ? For some reason Django always return false even for the user that is already registered in the database. jQuery: function validateInputs(inputNameId){ var value = $(inputNameId).val(); var inputName = inputNameId.replace("#input",""); if (inputName == 'Username' || inputName == 'Email') $.ajax({ type: 'GET', url: '/authenticate/register/', data: { 'inputName': inputName, inputName: value, // passing Key & Value as variables 'is_taken': false }, dataType: 'json', success: function(data){ console.log(data['is_taken']); }, error: function(xhr){ alert("An error occured: " + xhr.status + " " + xhr.statusText); } }); } function validateSignUpModal(){ $("#inputEmail, #inputUsername, #inputPassword, #inputConfirmPassword").change(function(){ var $this = '#' + $(this).attr('id'); validateInputs( $this ); }); } views.py: class registerForm(View): form_class = signupForm def get(self, request): data = {} inputName = request.GET.get('inputName', None); inputVal = request.GET.get(inputName, None); // this returns None why ? Isn't that how you access JSON Value from Key which are passed as … -
SEO in Django. Can Django give better results than other language and framework
Does Django support SEO. can django give dynamic urls like abc.com/mobile/smart if yes then it will give effective results like other give. I'm new to Django and python as well. -
Invalid filter error in django custom template filter
I'm trying to create a custom template filter but, getting Invalid filter error. TemplateSyntaxError at /attainment/reportcard/ Invalid filter: 'get_item' Request Method: POST Request URL: http://127.0.0.1:8000/attainment/reportcard/ Django Version: 1.11.5 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'get_item' Exception Location: /media/itsd/ITSD/ROFI/Projects/Rise/venv/lib/python3.5/site-packages/django/template/base.py in find_filter, line 606 Python Executable: /media/itsd/ITSD/ROFI/Projects/Rise/venv/bin/python Python Version: 3.5.2 I've created a filter in and registered. template_filters.py from django.template.defaulttags import register # Custom template filter to get data from a dictionary using key in template @register.filter def get_item(dictionary, key): return dictionary.get(key) And I've used the filter in the template as follows. <tbody> {% for subject in subjects %} <tr> <td>{{ subject|get_item:"subject" }}</td> <td>{{ subject|get_item:"efffort" }}</td> <td>{{ subject|get_item:"homework" }}</td> <td>{{ subject|get_item:"marks" }}</td> <td>{{ subject|get_item:"grade" }}</td> </tr> {% endfor %} </tbody> What am I missing ?? N.B: I've followed this answer.