Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
state of request object in middleware's process_response()
I need to query the request object (basically the session object) in process_response(). I find that the session object is missing some of the fields I'm expecting to find. Is that a normal Django behavior or is it local to my application? Thank you -
Django / Apache: How to limit my server to receive requests for a specific amount of time
I have a Django / Apache application which runs heavy and time consuming algorithms on server side. I want to limit my server in order to receive 2 requests per 3 hours from all users. I took a look in this excellent package: https://github.com/jsocol/django-ratelimit but I cannot find the way to block requests from all IPs for a specific amount of time. I feel that the answer is in front of my eyes but I cannot find it. Any solution ? -
django manytomany model linked to 'self' makes a link to both objects when selected. i would like only a one way link
I'm using a manytomany object in my model which is linked to 'self'. The reason for this is because i need to be able to select other objects from within the same class model. However my problem is this: If object A has object B selected within the manytomany field. If you go to edit object B, then A is also selected. The way i would like it to work is, if object B is selected from within object A then i do not want object A selected within object B. A linked to B, B not linked to A I hope this makes sense. -
How can we setup SAPUI5 as frontend locally with python backend on pycharm
I am trying to develop a project in which I am using SAPUI5 as frontend and I want to build my backend with. How can I setup it in my pycharm. Any help in this regard will be highly appreciated. -
What is exact data flow after 'py manage.py runserver'?
When i hit 'py manage.py runserver', it executes 'manage.py' then it routes to 'setting.py' and my app is ready to serve (Please correct me if required.) So my confusion is: How exactly my app triggers after network request bangs? and what's the reactions after receiving request? when does 'wsgi' enter in picture? I'm noob to forum and django. thank you for understanding. -
How to get the current Url within a Django Forms?
I would like to check the URL path so I can create the form base on it. In the view, we can use the request parameter to get the URL path, is there a similar way so we can get the current URL inside forms.py? URL=?? if URL == 'phones': brand_choises= (('Sumsung', 'Sumsung'), ('Iphon', 'Iphone'),) if URL == 'cars': brand_choises= (('Honda', 'Honda'), ('Toyota', 'Toyota'),) class Productform(forms.ModelForm): brand=forms.ChoiceField(choices=brand_choises,widget=forms.Select(attrs={'class':'products'})) class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['brand'].choices = brand_choises -
How to add select in Django Admin?
How can I add a a select field type in Django admin page of a table. How does it store in Database. -
Django models unique bank cheque number 6 digits
I try to set unique 6 digit cheque number by help of django doc. but still i dont want desired result means it accept any number or character but i want this will accept only 6 integer and also make sure that number should be unique for all users models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime from uuid import uuid4 import string from string import digits class Mvouchar(models.Model): cheque_no = models.CharField(max_length=6, null=True, blank=True, unique=True) dated = models.DateTimeField(auto_now_add=True,null=True, blank=True) def id_generator(size=6, chars=string.digits): return ''.join(random.choice(chars) for _ in range(size)) def save(self): if not self.cheque_no: self.cheque_no = id_generator() while Mvouchar.objects.filter(cheque_no=self.cheque_no).exists(): self.cheque_no = id_generator() self.dated = datetime.now() super(Mvouchar, self).save() def __str__(self): if self.related: return self.related.relation.username.title() else: return 'no related!' class Meta: verbose_name_plural = "Single Cheque Multiple Vouchar Of Users" #views.py def mvouchar(request): if request.method == "POST": userdata = User.objects.get(username = request.user) accountdata = Signs.objects.get(relation_id=userdata.id) chq_no = request.POST['chequeno'] mini = Mvouchar(related_id=accountdata.id, cheque_no = chq_no) mini.save() messages.success(request, "Your Cheque is Created") return HttpResponseRedirect("/mvouchar/") return render(request, 'cheque/mvouchar.html', {}) -
Django CMS : Integrating CMS with CDN for faster delivery of static files
Use-Case: Need to upload an image which is bigger in size ( using django cms image plugin ) . When I upload the image via CMS portal , where do the actual image is saved and in what format ? Can I configure it to save in static folder of my source repo , so that I can push the new image to CDN ? Also would like to know what is the standard practice for this use-case (image ? -
Query tangled array in Pymongo
I am trying to query a very tangled collection. This is my schema: {'tags': {'variables': [{'value': '3x9', 'var_name': 's'}, {'value': '12:00AM', 'var_name': 'x'}, {'value': 'goog', 'var_name': 'y'}]}, 'url': 'https://www.google.com'}] My Query: res = mycol.aggregate([{"$unwind":"$tags"} ,{'$match': {'tags.tag.name':'A A', 'aR': 98765}} ,{'$project': {'url': 1, 'tags.vars': 1, '_id': 0}},]) res = list(res) for x in res: pprint(res) Result: {'tags': {'variables': [{'value': '3x9', 'var_name': 's'}, {'value': '12:00AM', 'var_name': 'x'}, {'value': 'goog', 'var_name': 'y'}]}, 'url': 'https://www.google.com'}] Expected Result: {'value': '3x9', 'var_name': 's'}, {'value': '12:00AM', 'var_name': 'x'}, {'value': 'goog', 'var_name': 'y'}, 'url': 'https://www.google.com' I will use it as a HttpResponse and use it as a JSON object. Please Help! -
Django: Difference between using models.form and forms.form view
What is the main difference between models.form and forms.form? Do they have any runtime difference? -
Django: Difference between using class and method based view
I am concerned about whether having less code is the only benefit of using class-based views or they have also runtime benefits? -
django jquery autocomplete search box not displaying results
I went through a few resources online to make use of jquery autocomplete to populate my search box. However, as I type into the search box, instead of returning the search results, a No Results is being returned.. Another problem is that, this No Results is not displayed as the normal drop down below the search box. Instead, it appears as text below the search box instead. Any thoughts? add_new_schedule.html <!-- jquery, jqueryui, bootstrap4 cdn are used in the headers --> <input class="form-control" id="id_test" name="test"> <!-- this is the search box --> jquery $(document).ready(function () { $('#id_test').autocomplete({ source: "", minLength: 1, autoFocus: true, }); }); views.py import json ... ... def add_new_schedule(request): if request.user.is_authenticated: if request.GET and request.is_ajax(): q = request.GET.get('term') print(q) student_object = Student.objects.filter(first_name__startswith=q) results = [] for r in student_object: results.append(r.first_name) data = json.dumps(results) print(results) else: data = 'fail' mimetype = 'application/json' return render(request, 'static/html/add_new_schedule.html') At this stage, as I type into the search box, print(results) will print out a list of the possible matches from the Student database. However, this result is not being fed back into the search box... urls.py path('schedule/add-new-schedule/', views.add_new_schedule, name='add_new_schedule') -
Django+postgres auth_user duplicate key value violates unique constraint "auth_user_username_key"
try: django_user = User.objects.get(username__iexact=self.username) except User.DoesNotExist: django_user = User(username=self.username) django_user.is_staff=True django_user.save() Above gets the user by searching by username if present or create a new object if not present and updates its attribute and saves it back to db. This code ideally should handle the situation where the object is already present in the database. But it is throwing following error duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=(xxxxxxxx@yyyyy.com) already exists. I don't get the reason for this. Searched on the internet and found that It might be because of indices are corrupted and has to reset the sequence but Cannot find the exact reason and solution for this. Please help me with this. Thanks in advance -
Writing django tests that use the main database
My django project has several data migrations which take about 2 hours to be applied. Those data migrations constitute a series of transformations on a raw dataset (cleaning up, extracting new fields, etc.). The final state of the database consists of 15-20 tables. I also have code that imports new data on a daily basis which is also pushed to the existing database tables in the same format. I want to write tests that make sure that the contents of the database are correct at any given moment (after the initial data migrations have been applied, after a new import, etc.). The tests will check things like whether a particular column which is not expected to have null values indeed doesn't, if a derived field's value is correct, etc. My issue is that, django attempts to create a test database by applying all migrations every time I run the tests. But since the data migrations take a long time to be applied, running tests like that becomes very impractical. I also don't want to use the keepdb option, as I want to run those tests after changes to the original database as well. I'm not sure what the general best … -
Checking for substring match in django template
In my template I have: {% if form.non_field_errors %} <div class="alert alert-info" role="alert"> {% if "already exists" in form.non_field_errors %} You've already submitted your request once. Please wait for confirmation, or email us at support@relsoft.in {% else %} {{ form.non_field_errors }} {% endif %} </div> {% endif %} It seems that the {% if "already exists" in form.non_field_errors %} block isnt working. I'm getting the following in the output: <div class="alert alert-info" role="alert"> <ul class="errorlist nonfield"><li>Pendingclinics with this Name, Mobile and Email already exists.</li></ul> </div> -
Setting up every sentence (or string) in a text have its own URL
So I want to have a webpage that has a text - say a short story. I want every sentence in the short story to have its own URL and page. The idea would be to allow users to save and comment on each sentence. It would be similar to what RapGenius does for lyrics. I.e. a song has its own page (https://genius.com/Eminem-venom-music-from-the-motion-picture-lyrics). But each line in the song can also have its own URL/page (https://genius.com/15303513 or https://genius.com/15306806) What is the best way to approach this? Should I be splitting the short story into sentences beforehand, then import it into the database? Or should I be looking to upload the short story as a whole text (either onto the database or on the server) and then try to split it after the fact? Or is "splitting up" the story into sentences the wrong approach completely? Should I be looking to have the URL generate based off the sentence's location in the text? I'm currently leaning towards option 1. I would appreciate any help or guidance! Looking to build my first proper Django app (after doing a bunch of tutorials) and I would like to make sure I'm on the right … -
How do I test the foreign key object on Django model
I want to pass foreign key object(Category) on the model(Article) when testing.Currently, I create the category object and then i pass its variable to my article test data.I am currently gettting this error TypeError: Object of type 'Category' is not JSON serializable. My goal is to be able to create a category and then pass it into the article test data when testing creation of a new article.Any ideas into how i can implement this properly ? base_test.py class BaseTest: """ Class contains data to be used for testing """ def __init__(self): self.title = "How to tnnrain your flywwwwwwwwwwf" self.description = "Ever wondner how toddddd ddddwwwwd?" self.body = "You have to benlieve becausedddddddddcf" self.category = Category.objects.create( title='test category', ) self.category.save() """ sample article data """ self.create_article = { "article": { "title": self.title, "description": self.description, "body": self.body, "tags": ["reactjs"], "category": self.category } } test_article.py from rest_framework.test import APIClient, APITestCase from rest_framework import status from ..test_authentication.test_base import BaseTest from authors.apps.articles.models import Article, Category from authors.apps.authentication.models import User class ArticlesTest(APITestCase,BaseTest): def setUp(self): BaseTest.__init__(self) self.client = APIClient() """ method for testing creation of a new article """ def test_create_article(self): self.create_login_user() response = self.client.post('/api/articles/',self.create_article, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) Models.py class Category(models.Model): title = models.CharField(max_length=100) class Meta: … -
Django Rest Framework: Error when handle file upload by iOS Swift Client
I have an issue when handling file upload by iOS Swift Client. I describe it totally below My model: def avatar_photo_upload(instance, filename): if filename: ext = filename.split('.')[-1] filename = 'avatar.%s' % (ext) else: filename = 'avatar.jpg' return "avatar/%s/%s" %('profile', filename) class Profile(models.Model): avatar = models.FileField("Uploaded avatar of profile", storage=OverwriteStorage(), upload_to=avatar_photo_upload, null=True, blank=True) My serializer: class PhotoUpdateSerializer(ModelSerializer): file = ImageField(max_length=100000, allow_empty_file=False, use_url=False) class Meta: model = Profile fields = [ 'file', ] My view: class UploadPhotoAPIView(ModelViewSet): serializer_class = PhotoUpdateSerializer queryset = Profile.objects.all() parser_classes = (JSONParser, MultiPartParser, FormParser,) permission_classes = (IsAuthenticated,) def upload_avatar(self, request): serializer = self.get_serializer(data=request.data, context={"request": request}) logger.info('Information incoming!') if serializer.is_valid(): profile = Profile.objects.get(user=request.user) profile.avatar = request.FILES.get('file') profile.save() return Response({ 'status': 'ok', 'avatar': get_avatar_url(request, '300x300', 'user', profile.user_id) }, status=status.HTTP_201_CREATED) else: logger.error('Toan Error' + str(serializer.errors)) return Response(serializer.errors, status=status.HTTP_501_NOT_IMPLEMENTED) Finally, this is my url: url(r'^account/upload_avatar/$', UploadPhotoAPIView.as_view({'post': 'upload_avatar'})) I believed that I make it all the right way until test API in iOS Swift, it return error: [Request]: POST https://api.com/api/v1/users/account/upload_avatar/ [Response]: { URL: https://api.com/api/v1/users/account/upload_avatar/ } { Status Code: 501, Headers { "Content-Length" = ( 84 ); "Content-Type" = ( "application/json" ); Date = ( "Wed, 10 Oct 2018 10:41:31 GMT" ); Server = ( cloudflare ); Vary = ( Origin ); allow = … -
Pass a string to javascript function from render_field tag in Django
I can pass a string value to javascript function onblur when using plain html tag as shown below: <input type="password" name="l_password" onblur="passwordValidation(this,'id_lpassword_error')" /> but when i try to do the same thing for render_field tags it doesnt work: {%render_field form.password onblur="passwordValidation(this,'id_lpassword_error')" %} how can i pass the string 'id_lpassword_error' to a javascript function from render_tag in Django. -
Django: CreateView access request.user
class RiskCreate(CreateView): model = Risk fields = ['risk_title', 'probability_level', 'impact_level', 'degree', ] def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user return super(RiskCreate, self).form_valid(form) This is the code. For some reason, when I hit save in the template, the current user is not being passed to my record in the database. I want the model to be associated to the user by foreign key, which is already set up in a seperate file. How do I pass the current user to a CreateView form? -
unable to overwrite image generated using reportlab library for barcode on heroku
I have a simple function that generates image as svg Django when i run it locally all seems to work fine I am able to overite the image file by giving it the same name but when I run it via Heroku local web command it just returns the previous image with saving or rendering it. here is my view def barcode(request, stock_id): obj = get_object_or_404(Stock, id=stock_id) d = utility.MyBarcodeDrawing(obj.description,) d.save(formats=['svg','img'],outDir='static_root/media',fnRoot='barcode') barcodePicUrl = "barcode/barcode.svg" return render_to_response('barcode.html', {'url':barcodePicUrl}) -
In Django 2.1, how to use user.username in templates?
first, sorry for my Inexperienced English Proficiency. i want to use like this detail.html {% if user.username == obj.con_id %} <a href="{% url 'consignment:delete' obj.id %}">delete</a> {% endif %} but not working. delete tag invisible. In templates, i tested like this. it is works. {{user.username}} --> user1 {{obj.con_id}} --> user1 here is my views,models views.py def congsignmentDetail(request,detail_id): obj = get_object_or_404(ConsignmentInfo,id=detail_id) return render(request,'consignment/detail.html',{'obj':obj}) models.py class ConsignmentInfo(models.Model): con_id = models.Foreignkey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ...... -
Django Rest Framework does not output filtered Querysets
I am using a DRF ViewSet to search for a name, but only partial text. The problem is i use get_queryset to filter data out of DB with icontains: class CustomerViewSet(viewsets.ModelViewSet): serializer_class = serializers.CustomerSerializer permission_classes = [IsAuthenticated] lookup_field = 'full_name' def get_queryset(self): if self.kwargs: return models.Customer.objects.filter(full_name__icontains=self.kwargs['full_name']) else: return models.Customer.objects.all() The view sends me a 404 error, but when i print it in the terminal it shows existing data. -
@classmethod error: TypeError: __call__() got an unexpected keyword argument
I have a model/class like this: class MyModel(TimeStampedModel): some_field = models.CharField() @classmethod def my_class_method(cls, value): print(value) However, when I do this from another view: value = "Test" MyModel.my_class_method(value=value) I get an error: TypeError: __call__() got an unexpected keyword argument value I feel like I am going crazy. The model that I am doing this to has: class Meta: abstract = True