Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset rendering 3 formsets
I've made a formset that will update a model Client and a model ClientData,my problem is that instead of rendering a formset, it renders it 3 times and i can't identify why. views.py def client_data(request): data = dict() if request.method == "POST": form = ClientForm(request.POST) if form.is_valid(): client = form.save(commit=False) formset = ClientFormSet(request.POST, instance=client) if formset.is_valid(): client.save() formset.save() return redirect(reverse_lazy('core:index')) else: form = ClientForm() formset = ClientFormSet() data['form'] = form data['formset'] = formset return render(request, 'core/test.html', data) 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, fields=[ 'language', 'type', ]) template <form method="POST">{% csrf_token %} {{ form.as_p }} {{ formset }} <button type="submit" class="save btn btn-default">Save</button> </form> -
Get the change log for custom fields in Django admin
I have added two custom fields (Checkboxes) in a form under Django admin. These values are not fetching data from model, but I am fetching data from a micro service to show these checkboxes as checked/unchecked conditionally. Below is the sample code: class CustomFieldForm(ModelForm): first_custom_field = forms.BooleanField( label=_("First custom field"), widget=forms.CheckboxInput, required=False ) second_custom_field = forms.BooleanField( label=_("Second custom field"), widget=forms.CheckboxInput, required=False ) def __init__(self, *args, **kwargs): super(CustomFieldForm, self).__init__(*args, **kwargs) if self.instance and self.instance.user_id: if get_first_custom_field(self.instance.user.id): self.fields['first_custom_field'].widget.attrs['checked'] = 'checked' if get_second_custom_field(self.instance.user.id): self.fields['second_custom_field'].widget.attrs['checked'] = 'checked' Now the problem am facing is that every time, I call save_model method, and if these fields are checked, then these are logged in history every time although I haven't updated any of these. Here is the sample code for save_model def save_model(self, request, obj, form, change): super(ProfileAdmin, self).save_model(request, obj, form, change) update_custom_field(form.cleaned_data['first_custom_field'], obj.user) update_custom_field(form.cleaned_data['second_custom_field'], obj.user) After exploring the Django code, I came to know that Django form caches the initial field values and then compare these with submitted field values to know the change. But in my case, I am updating the form fields under __init__ method, based on data fetched from my micro service, so django form always caches my fields as unchecked. And every … -
How can I deploy multiple Python 2 and 3 Django projects on one apache server?
Problem: There is a similar question on StackOverflow: "Can I deploy both python 2 and 3 django app with apache using mod_wsgi?" From the answer there I know that it is possible two have multiple Django projects (written in Python 2 and 3) on one apache server. However, I can't manage to make this work. What I have so far: I'm using Linux (Debian/Ubuntu). Three Django projects are stored in three separate Python Virtual Environments (i.e. py3venv1, py3venv2, py2venv1): /var/www/ .........py3venv1/ <-- Python 3 venv ..................bin/ ..................include/ ..................lib/ ..................project1/ <-- Python 3 Django Project ........................../manage.py ........................../project1/wsgi.py ........................../myapp .........py3venv2/ <-- Python 3 venv ..................bin/ ..................include/ ..................lib/ ..................project2/ <-- Python 3 Django Project ........................../manage.py ........................../project2/wsgi.py ........................../myapp .........py2venv1/ <-- Python 2 venv ..................bin/ ..................include/ ..................lib/ ..................project3/ <-- Python 2 Django Project ........................../manage.py ........................../project3/wsgi.py ........................../myapp I installed mod_wsgi for Python3 (pip3 install mod_wsgi) Apache configuration: /etc/apache2/sites-available/000-default.conf for Projects 1 and 2 (Python3 only), Project 3 (Python 2) is not configured: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Project 1 (Python3) WSGIScriptAlias /project1 /var/www/py3venv1/project1/project1/wsgi.py process-group=group1 WSGIDaemonProcess group1 python-home=/var/www/py3venv1/lib/python3.5 python-path=/var/www/py3venv1/project1 WSGIProcessGroup group1 <Directory /var/www/py3venv1/project1/project1> <Files wsgi.py> Require all granted </Files> </Directory> # Project 2 (Python3) WSGIScriptAlias /project2 /var/www/py3venv2/project2/project2/wsgi.py process-group=group2 WSGIDaemonProcess group2 … -
what is attrs.get in Django REST serializers?
I am trying to understand and learn Django serializers. The give an example: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def restore_object(self, attrs, instance=None): """ Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. """ if instance is not None: instance.email = attrs.get('email', instance.email) instance.content = attrs.get('content', instance.content) instance.created = attrs.get('created', instance.created) return instance return Comment(**attrs) I can't figure out where 'attrs.get' comes from, or what it does. Even less clear are the lines like this: instance.email = attrs.get('email', instance.email) instance.content = attrs.get('content', instance.content) instance.created = attrs.get('created', instance.created) Which feels like a snake eating its tail...if 'instance' already has an 'email' attribute, what is the point of what looks like looking it up and then setting it to itself? -
Dynamic filtering on Django admin form
I have a three simple models: class Tag(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) tag = models.ManyToManyField(Tag) class Session(models.Model): task = models.ForeignKey(Task) It is hard to uers to select Task from all tasks in database. I want to allow user to reduce number of choices by filterting task by tag. So, user can select tag and then find task (in reduced amount of tasks). It is possible to implement? -
Django import-export how to replace integer ids with uuid ids?
I am building a django application where the user can export a json file of many models which are related to each other. Then the json fiele can be imported on another server. Since its an other database i can not use the ids which are exported in the file. I use django import-export for that. How can i replace the integer ids from my database with uuids to prevent double id problems? (especially when using foreign keys or many to many relations). In the following code does not work completely since Group.name is not unique. model.py class Group(models.Model): name = models.CharField(max_length=255) class Subgroup(models.Model): parent_group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(max_length=255) resources.py parent_group_widget = fields.Field( column_name='group_natural_key', attribute='parent_group', widget=ForeignKeyWidget(Group, 'name')) class GroupResource(resources.ModelResource): class Meta: model = Group exclude = ('id',) import_id_fields = ('name', 'measurement_widget') class SubgroupResource(resources.ModelResource): parent_group_widget = parent_group_widget class Meta: model = Subgroup exclude = ('id',) import_id_fields = ('name', 'parent_group_widget') I would like to get the following result: {"Group": [ { "id": "1c4d4824-d890-4021-bb24-18dd5a2cd618", "name": "Group_0", }] "Subgroup": [ { "name": "FOOBAR", "parent_group": "1c4d4824-d890-4021-bb24-18dd5a2cd618", } } -
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!