Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ManyToMany Field - Make a correct link
after an python3 manager.py inspectdb (mysql) and a look on few helps and tuto, i still have somes mistakes and incorrect results. models.py class A(models.Model): ida = models.AutoField(db_column='idA', primary_key=True) col1 = #an another column has_B = models.ManyToManyField(B, related_name='a', through="AHasB", through_fields=('a_ida', 'b_idb')) #I had add this line after a tuto in django book for the manytomayfield class B(models.Model): idb = models.AutoField(db_column='idA', primary_key=True) col1 = #an another column class AHasB(models.Model): a_ida = models.ForeignKey(A) b_idb = models.ForeignKey(B) col1 = #an another column view.py def myview(request): for element in b.filter(idb__in=a.values('has_B').distinct()): print(element) In my database i have, A : ida | col1 1 | ... 2 | ... 3 | ... B : idb | col1 1 | ... AHasB : a_ida | b_idb 1 | 1 But when i will display result (ida -> idb) like a classic (SELECT idb,ida FROM A, B, AHasB WHERE AHasB.a_ida=A.ida AND AHasB.b_idb=B.idb), i have this ... 1 -> 1 2 -> 1 3 -> 1 And in normal case, i will just have 1 -> 1. Maybe the model dont fit with my real database in back. -
Django social auth disable for admin
In python social auth library: I am making a social auth for my django project. I want to disable social auth for admin. how it works by default: social auth url is visited and permissions granted new Python Social Auth › User social auths object is created for Admin this social account logs in admin How I want it to work: social auth url is visited and permissions granted new Python Social Auth › User social auths object is created along with new regular user, as if admin was not logged in this social account logs in a regular user Is there an elegant way of doing this? Overriding the least amount of pipeline functions as possible. -
Another file's modules cannot be used
Another file's modules cannot be used.I have 2 filed of test1.py and test2.py .I want to use test2's class in test1. test2.py is class Test2(object): def data(self, Test): self.user =user test1.py is class Test1(test2.Test2): def __init__(self): Test.__init__(self) But when I run these codes,NameError: name 'test2' is not defined happens.So I wrote codes import test2 as tein test1.py and I rewrote class Test1(te.Test2): but te is not defined error happens.What is wrong in my code?How should I fix this? -
Django - getting context dict from FBV
Does anyone know how we can get access to context dict in middleware via FBV? For CBV we can use process_template_response and use "context_data" variable there. In case with FBV - it doesn't work! So, any help would be appreciated. -
Add django template tags to templates with Beautiful Soup
I've got a django management command which is modifying templates & I'd like to include a django {% if template tag to conditionally exclude a block so that if message_url is not defined, exclude the following content; <tr> <td> If you cannot view this message, please go to the <a href="{{ message_url }}"> Members Hub </a> </td> </tr> The <a> tag is passed to a function to be modified so this seemed like the perfect place to include the condition string; def replace_tag(template, string, template_origin, template_type): """ :param template: HTML content :type: str or unicode :param string: new string for HTML link :type: str or unicode :param template_origin: :type: str or unicode :param template_type: MessageType.key of template :type: str or unicode :return: modified HTML content :rtype: unicode """ soup = BeautifulSoup(template) link = find_link(soup, template_type) if link is not None: link.string.replace_with(string) row = link.parent.parent if '{% if message_url %}' not in row.contents: row.contents.insert(0, NavigableString('{% if message_url %}')) if '{% endif %}' not in row.contents: row.contents.append(NavigableString('{% endif %}')) # '{% if message_url %}' + row + '{% endif %}' At first I just added my tags as plain strings to the content and they were added to the Tag contents, but … -
testing a filtering view - django
I am relatively new to testing and I am wondering how I can test this view method that filters a player(s). def player_results(request): player = Player.objects.player_filter(name=request.POST.get('name'), height=request.POST.get('height'), weight=request.POST.get('weight')) return render(request, 'sports/search_results.html', {'player': player}) This is the filter that goes with this: class PlayerManager(models.Manager): def player_filter(self, **filtering): filtering = {k: v for k, v in filtering.items() if v is not None} query_set = self.get_queryset() return query_set.filter(**filtering) -
i wanna update my formset factory images post, i am able to update posts text fields but formset factory images are noot updating
I have searched this issue but couldn't get the right answer where as there are so many questions being asked before related to that. i am using a model for post with multiple fields and other model (having foreign key of post model) for multiple image fields.I Want to update the posts i create. Here's my views.py for update_post def update_post(request, post_id): ImageFormSet = modelformset_factory(PostPicture, form=AddPictures, extra=10, min_num=1) post_form = get_object_or_404(Posts, pk=post_id) if request.method == "POST": form = AddFile(request.POST, instance=post_form) formset = ImageFormSet(queryset=PostPicture.objects.filter(post=post_id)) if form.is_valid() and formset.is_valid(): form.save() formset.save() for form in formset: if form: image = form['image'] photo = PostPicture(post=form, image=image) photo.save() messages.success(request, 'Post updated Successfully!') return render(request, 'vehicles_app/update_post.html', { 'form': form, 'formset': formset, 'post_form': post_form, 'post_id': post_id, }) else: print(form.errors, formset.errors) else: form = AddFile() formset = ImageFormSet(queryset=PostPicture.objects.none()) return render(request, 'vehicles_app/update_post.html', {'form': form, 'formset': formset, 'post_form':post_form, 'post_id': post_id}) here's the views.py for my post(addfile) def addfile(request): query = request.POST.get('form-0-id') ImageFormSet = modelformset_factory(PostPicture, form=AddPictures, extra=10, min_num=1) if request.method == 'POST': form = AddFile(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=PostPicture.objects.none()) if form.is_valid() and formset.is_valid(): post_form = form.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: if form: image = form['image'] photo = PostPicture(post=post_form, image=image) photo.save() messages.success(request, 'Post submitted Successfully!') return render(request,'vehicles_app/addfile.html', … -
How to display a comment after posting it without page refresh in django?
What I am trying to do ? I am trying to display a comment after posting it without page refresh. What is the problem ? I am able to successfully post the comment but I am not able to display it without page refresh. My code:- html <form id='articleCommentForm'>{% csrf_token %} <textarea placeholder='write comment'></textarea> <button type="submit"> Comment </button> </form> {% for comment in comments %} <br /> <br /> <div class="row" class="commentStyle"> <div class="col-xs-10"> <span class="userName"> {{ comment.user }} </span> <br /> <br /> <div class="comment-box"> <textarea class="form-control" readonly> {{ comment.text }} </textarea> </div> <br /> <div class="row"> <div class="col-xs-6"> <span class="comment-footer-text"> {{ comment.date }} </span> </div> <div> <div class="comment-control"> <span> {{ comment.likes }} </span> <span></span> </div> </div> </div> </div> </div> {% endfor %} ajax $.ajax({ type: 'POST', url: '/articles/postComment/', data: { 'comment': $('#articleCommentForm textarea').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', success: function(data){ var comment = JSON.parse(data['comment']); $('.commentStyle .userName').val(comment.user); $('.commentStyle textarea').val(comment.text); $('.commentStyle .comment-footer-text').val(comment.date); $('.commentStyle .comment-control span:first-child').val(comment.likes); } }); views.py def postComment(request): if request.user.is_authenticated(): comment = Comment() comment.user = request.user comment.text = request.POST.get('comment') comment.date = datetime.now() comment.save() curComment = serializers.serialize('json', [comment]) data['comment'] = curComment return JsonResponse(data) I could Any help would be highly appreciated. -
Perl command which needs user input is not printing in django application
I am executing perl cmd through perl script as follows def(request,self): args_str1 = "flexiserver/build/svnenv.sh -j 'svntasktag.pl ss_fvnteste'" args1 = shlex.split(args_str1) pi = subprocess.Popen(args1, stdout=subprocess.PIPE) print("*********Before out err *****") out, err = pi.communicate() print(" OUT is %s " , out) context = {'out':out, 'err':err} return render_to_response('pai_app/create_tag.html', {'out':out, 'err':err}, context_instance=RequestContext(request)) Here this script is waiting for user input like 'i', 'm', 'c' like arguments until we r giving any input it is not printing and not showing in webui. My question is, any possibility to run such perl or shell scripts in webui itself ? or else any resolution is there for the above problem could anyone help me in this as i am struck -
Django get student id from html file
How can i get student id from the html file? Since i want populate the student field in the create view. index.html {% for student in studentList %} <tr> <td>{{ student.name}}</td> {% for resource in resourceList %} {% if student.id == resource.student_id %} <td><a href="{% url 'web:resource_detail' resource.id%}" class="btn btn-danger" role="button">Details</a></td> {% else %} <td><a href="{% url 'web:resource_book' %}" class="btn btn-success" role="button">Book Resource</a></td> {% endif %} {% endfor %} </tr> {% endfor %} views.py class ResourceCreate(CreateView): model = Resource template_name = 'resource/resource_form.html' fields = ['student', 'teacher', 'week'] def get_initial(self): """ Returns the initial data to use for forms on this view. """ initial = super(CreateView, self).get_initial() initial['student'] = self.request print(self.request) return initial -
pythons `vars()` function in Django tempalte
In a template I created for my Django view I pass an extra variable called Item. This Item object has a string representation of the value it holds. It kinda looks like this: class Item: value = '' previous_item = Item def __str__(self): return '%s > %s' % (value, previous_item) This way you can get a chain of items: `value_x > value_y > value_z' The problem is that now I want to be able to just print the vars of the Item object I injected into the template, much like the vars() function in Python: >>> item = Item('FooBar', None) >>> vars(item) Is there a way to do pythons vars() in the template? -
How to access key values in ordered dictionary
How to access the values in this Ordered Dictionary..I want to access the values inside the cost_price which is 0.92. OrderedDict([('0', OrderedDict([('cost_price', '0.92'), ('quantity', '0'), ('sell_price', '1.69'), ('text', '6oz')]))]) -
DRF BooleanField to like
I'm have problem with "Like" buttom. I'm trying to have possibility to as user like or not other users, for this i would use BooleanField(True=Like, False=Dislike. And would like to exclude already voted user from future voting. So i need to save votes somewhere/somelike, have to work on that. But for now i have problem just to vote, because im getting IntegrityError. My model: GENDER_CHOICES = ( ('M', 'male'), ('F', 'female') ) class User(AbstractUser): created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=30, blank=False) email = models.EmailField(blank=False) age = models.IntegerField( validators=[MinValueValidator(16), MaxValueValidator(99)], null=True, blank=True) description = models.TextField( validators=[MinLengthValidator(52), MaxLengthValidator(500)], blank=False) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) interest = models.ManyToManyField(Interests, blank=True) vote = models.BooleanField(default=False) serializer: class VoteUserSerializer(serializers.ModelSerializer): vote = serializers.BooleanField() class Meta: model = User fields = ('id', 'first_name', 'gender', 'age', 'images', 'vote') read_only_fields = ('id', 'first_name', 'gender', 'age', 'images', 'interest') views: class VoteUserViewSet(viewsets.ModelViewSet): serializer_class = VoteUserSerializer permission_classes = (IsAuthenticated,) queryset = User.objects.all() def get_queryset(self): if self.request.user.gender == 'M': return User.objects.all().filter(gender='F', id=pick_random_object()) elif self.request.user.gender == 'F': return User.objects.all().filter(gender='M', id=pick_random_object()) Traceback: File "/home/bartek/PycharmProjects/FWD/venv/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/bartek/PycharmProjects/FWD/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 303. return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: users_user.username) was the direct cause of the following exception: File "/home/bartek/PycharmProjects/FWD/venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner … -
Multiple app in http.conf and assertion error
i'm working with python/Django web app and after my last project i had to setup my apache http.conf to handle two app at the same time. Both apps run as intenteded when alone in the httpd.conf, but when i put them both in the file i start having issues with asertion error. httpd.conf part with app : <VirtualHost 200.1.2.11:8080> ServerName 200.1.2.11:8080 WSGIScriptAlias / "E:/Applications/var/www/YYY/YYY/wsgi.py" Alias /static/ "E:/Applications/var/www/YYY/static/" Alias /templates/ "E:/Applications/var/www/YYY/templates/" <Directory "E:/Applications/var/www/YYY/static"> Require all granted </Directory> <Directory "E:/Applications/var/www/YYY/YYY"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> <VirtualHost 200.1.2.11:8081> ServerName 200.1.2.11:8081 WSGIScriptAlias / "E:/Applications/var/www/XXX/XXX/wsgi.py" Alias /static/ "E:/Applications/var/www/XXX/static/" Alias /templates/ "E:/Applications/var/www/XXX/templates/" <Directory "E:/Applications/var/www/XXX/static"> Require all granted </Directory> <Directory "E:/Applications/var/www/XXX/Axereal_Gestion_Mouvement"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> WSGIPythonPath E:/Applications/var/www/YYY;E:/Applications/var/www/XXX; WSGIPythonHome "C:/Python27" For example if i make a change on App A and restart apache, the A app will work but if i try to use the B app, i'm getting assertion error. Anyone who could help me figure out where this assertion bug come from ? -
username validation in django
I'm tying to validate the username whether it is present in the database or not? If it is there it should show validation error and not there it should proceed to next step.But my code is not working I don't know where i'm wrong.Thanks in advance. from django.contrib.auth.models import User from django import forms from .models import Core from django.core.exceptions import ValidationError class Registrationform(forms.ModelForm): username = forms.CharField(max_length=15, label="Username") firstname = forms.CharField(max_length=15,label="Firstname") lastname = forms.CharField(max_length=15,label="Lastname") email = forms.EmailField(required=True) password = forms.CharField(widget=forms.PasswordInput, label="Password") password1 = forms.CharField(widget=forms.PasswordInput ,label="PasswordConfirmation") class Meta: model=Core fields=("username","firstname","lastname","email","password","password1",) def clean_username(self): username = self.cleaned_data.get('username') username_qs = User.objects.filter(username=username) if username_qs.exists(): raise ValidationError("Username already exists") return username def clean_password1(self): password = self.cleaned_data.get('password') password1 = self.cleaned_data.get('password1') if password and password1 and password != password1: raise ValidationError("Password did n't match") return password1 -
Despite Adding Error Tags, Form Not Submitted and No Error Printed in Template
I want to preview all data submitted by a user before saving the form in the database. I wrote the below code, but it's not submitting and it's not showing me an error. Even when I insert print to the code so as to print data inputted, it didn't print any data. So the logic is this, when a user add the data and click confirm order, he/she will be taken to 'preview.html' where the data submitted will be displayed. And when the user is satisfied, he/she will click on save button. The form action in the preview.html is /add_buy_order/'. VIEWS @login_required def add_buy_order(request): newbc = None template_name = 'ctrade/buycurrency.html' if request.method=="POST": form=BuyCurForm(request.POST) if form.is_valid(): data=form.cleaned_data requested_amount_needed = request.POST.get('amount_needed') deck_am_needed = Decimal(requested_amount_needed) fixed_amount = Decimal('999.0') requested_amount_to_pay = request.POST.get('amount_to_pay') requested_disc_code = request.POST.get('discount_code') requested_disc_value = request.POST.get('discount_value') requested_cur_one = request.POST.get('cur_address') requested_cur_two = request.POST.get('cur_address_two') requested_bank = request.POST.get('deaccount') tapde = DEAccount.objects.get(bank_name= requested_bank) if not str(requested_cur_one) == str(requested_cur_two): messages.info(request, 'Address to fund mismatch. Cross-check again') return redirect('add_buy_order') if '_preview' in request.POST: newbc=BuyCur( buyer=request.user, cur_type = data['cur_type'], amount_needed = data['amount_needed'], deaccount = tapde, amount_to_pay = data['amount_to_pay'], cur_address = data['cur_address'], cur_address_two = data['cur_address_two'], rate_bought = data['rate_bought'], cur_note = data['cur_note'], pub_date=datetime.datetime.now(), modified_date = datetime.datetime.now(), discount_code = data['discount_code'] ) print … -
url: Reverse for 'contract_update' with arguments '('',)'
I can't understand why the following isn't working: Please help me figure out what I am doing wrong. template data-url="{% url 'dashboard:contract_update' contract.pk %}" urls.py url(r'^(?P<pk>[0-9]+)/contract-update/$', views.contract_update, name='contract_update'), views.py def contract_update(request, pk): ''' Updates instance of contract ''' contract = get_object_or_404(Contract, pk=pk) template = 'dashboard/includes/contract/modal/partial_contract_update.html' print(contract) if request.method == 'POST': form = ContractForm(request.POST, instance=contract) print("contactperson_update: request.method = post") else: form = ContractForm(instance=contract) return save_contract_form(request, form, template) console.log(url) = /1/contract-update/ error message: django.urls.exceptions.NoReverseMatch: Reverse for 'contract_update' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/contract-update/$'] I have the same code for contactpersons and it is working. data-url="{% url 'dashboard:contactperson_update' contact.pk %}" url(r'^(?P<pk>[0-9]+)/contactperson-update/$', views.contactperson_update, name='contactperson_update'), -
react.js dynamically generated forms based on DRF HTTP OPTIONS
Is there any package for rendering forms in react based on django-rest-framework OPTIONS? I mean to have the form rendered based on smth like this: { "name": "Spots Rating List", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "pk": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "created_at": { "type": "datetime", "required": false, "read_only": true, "label": "Created at" }, "updated_at": { "type": "datetime", "required": false, "read_only": true, "label": "Updated at" }, "is_enabled": { "type": "choice", "required": false, "read_only": false, "label": "Is enabled", "choices": [ { "value": false, "display_name": "Not allowed" }, { "value": true, "display_name": "Allowed" } ] }, "friendly_rate": { "type": "choice", "required": true, "read_only": false, "label": "Friendly rate", "choices": [ { "value": 1, "display_name": "terrible" }, { "value": 2, "display_name": "poor" }, { "value": 3, "display_name": "average" }, { "value": 4, "display_name": "very good" }, { "value": 5, "display_name": "excellent" } ] }, "opinion": { "type": "nested object", "required": false, "read_only": true, "label": "Opinion", "children": { "pk": { "type": "field", "required": true, "read_only": false, "label": "Rating" }, "created_at": { "type": "datetime", "required": false, "read_only": true, "label": "Created at" }, "updated_at": { "type": "datetime", "required": false, "read_only": true, … -
Django SECURE_SSL_REDIRECT breaks unit tests that use the in-built client
I am working on a project that already has hundreds of unit tests, many of which use either the built in django Client, or the django rest framework APIClient for making requests and testing responses. Having recently implemented the necessaries to make SSL work locally, and setting the SECURE_SSL_REDIRECT to True (trying to make our dockerised dev and test environments as close to production as possible), I have come a cropper to find that so many unit tests fail, due to the (API)Clients requesting, by default, always using http, not https. Many (most) requests look like this: response = self.client.get(some_url) I am aware that I could use: response = self.client.get(some_url, secure=True) But this does mean changing a lot of unit tests. The same is true for using follow=True, but had the added disadvantage that this could produce some other undesired behaviour. I cannot see a way of setting the use of secure requests as a default behaviour in the Django Client. I could make my own SecureClient (and SecureAPIClient), but I would then have to make sure that I make a new base TestCase (possibly multiple) to inherit from, and change this everywhere for all the tests - still a … -
Django Autocomplete Light widget Select2Multiple returns a string of a list instead of a list of values
I'm using Django Autocomplete Light widget Select2Multiple for a form field for tags. In form.clean(), the corresponding value is a string of list of the pk's of the tags, which looks like this: form.clean()['tags']: "['1','2']" Now, I can convert this to a list of integers and process the pk's individually but I feel like there should be a more obvious way to handle this. Relevant field in forms.py: tags = CharField(label='Tags', max_length=50, required=False, widget=autocomplete.Select2Multiple(url='tag-autocomplete') ) PS: I can't use ModelSelect2Multiple as this form is for an object that hasn't yet ben created. -
Django best practice to get object from id in POST request
In my API, sometimes you make HTTP request with id of objects (like update preferred address you put the id of your new default address). I retrieve it like this: address = get_object_or_404( Address.objects.filter(...), pk=request.data['address_pk'] ) This is completely functional, however it doesn't feel as the best way. I tried to search for the best practice, however I was not able to find proper search term which would satisfy my curiosity. Is this a good practice? Or should I change it? -
Serving multiple static images in django template
I have a template with dozens of static images in it. Is there any way to combine all the GET requests for these images into one request? I am currently using django_compressor for css/js, but have no clue how to do it for images. -
My form field percieves String input as invalid
I have a form that keep track of prospect and current deals being made with a sale consultant. However, I am stuck at a process of creating a deal because django keep giving me error of "ValueError: invalid literal for int() with base 10:" when I try to input customer last name with strings. The form work when i try creating with integer lastname though. Models.py class Deal(models.Model): name = models.CharField(max_length = 50) lastname = models.CharField(max_length = 50,blank=True) booked_car = models.ForeignKey('BookedCar', on_delete = models.SET_NULL, null = True) prospect = models.ForeignKey('Customer', on_delete = models.SET_NULL, null = True) is_credit = models.BooleanField() car_price = models.PositiveIntegerField() final_accessories = models.PositiveIntegerField() final_campaign = models.PositiveIntegerField() final_spending = models.PositiveIntegerField() views.py def booking_create(request,customer_id): customer = get_object_or_404(Customer,pk=customer_id) template_name = 'customerDB/booking_create.html' if request.method == 'POST': form = BookingCreate(request.POST) if form.is_valid(): customer.deal_set.create(name = form.cleaned_data['name'], lastname = form.cleaned_data['lastname'], booked_car = form.cleaned_data['booked_car'], is_credit = form.cleaned_data['is_credit'], car_price = form.cleaned_data['car_price'], final_accessories = form.cleaned_data['lastname'], final_campaign = form.cleaned_data['final_campaign'], final_spending = form.cleaned_data['final_spending'] ) else: form = BookingCreate(initial= {'name':customer.name}) return render(request,template_name,{'form':form}) forms.py class BookingCreate(ModelForm): class Meta: model = Deal fields = '__all__' -
Generate access token by google login using oauth2
My front end in Angular JS. It sends me google token after user logs in with gmail In backend I verify the token and extract information from it as below @csrf_exempt def check(request): CLIENT_ID = 'xxxxx' try: json_data = json.loads(request.body.decode('utf-8')) idinfo = id_token.verify_oauth2_token(json_data['google_token'], requests.Request(), CLIENT_ID) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') print("idinfo") print(idinfo) Now I got the user details here and want to generate an access token to access my API's for every request. Is there any built in function from oauth2 to generate an access token. Any suggestion that would help me. Thanks. -
Speed of django-server with celery
I have a Django-server running. On the server, I have a view, which calls a celery task. def add_seat(request, booking_id): seat_id = request.GET.get('seat_id') Booker.select(booker, booking_id, seat_id) return JsonResponse({}) @staticmethod def select(booking_id, seat_id, user_id): return t_select.apply_async((booking_id, seat_id, user_id)) Where t_select is a celery task. Now, when I am running the celery worker thread, I am able to handle 7 requests per second, but if I close the thread and let the broker(redis) store the request, I am able to handle 300 requests per second. Shouldn't it be the same and how can I improve it?