Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Unit Test: mock the function wrapping other function? [duplicate]
This question already has an answer here: Python Mocking a function from an imported module 2 answers Here is what I want to test: test.py class MyTest(TestCase) def test1(self): data = crawl_data() Check data lengh and current data in DB... function2() Again, Check data lengh and current data in DB... And program code: a.py def crawl_data(): """ crawl data from web """ . . return web_crawled_data b.py from a import crawl_data def function2(): """ crawl data and store new data in database """ . . result = crawl_data() . . update data and update Database . . What I want to do is testing function2(). Problem is though function2() call crawl_data() inside. I don't want crawl_data() to crawl data from web in the test, So I tried mocking this function. @patch("a.crawl_data") def test1(self, crawl_data): crawl_data.return_value = [("112233", "ABCDEF"), ("222233", "EFGHIJ")] data = crawl_data() Check data length and current data in DB function2() Check the database whether new data stored in DB When I run the test, function2() still crawl data from the web in real! The reason that I don't want to mock function2 is that, when I start the test, test framework use virtual database (provided by django)! So, … -
Getting CSRF error when sending POST Request using Postman [LOGIN PAGE]
While the site loads smoothly through the browser,but when i send a POST request via postman or a REST API client, i am getting a csrf error. "CSRF cookie not set." IS THERE A WAY TO SEND A REQUEST SKIPPING CSRF? -
Raise 404 instead of 403 DRF permission
Is it possible to customize response status of a permission to ruturn other than 403? Docs say: When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned -
Where are django console output sent
My prod django server runs with command /bin/python manage.py runfcgi host=127.0.0.1 port=8003 where can I find standard console log messages which come on console while running server manually with runfcgi option. [07/Feb/2018 15:48:47] "GET /cms/content HTTP/1.1" 200 48502 │2018-02-07 16:08:02,386 INFO done in 0.02 seconds [07/Feb/2018 15:48:47] "GET /2.2/static/css/sidebar.css HTTP/1.1" 200 1207 │2018-02-07 16:10:02,404 INFO ------------------------------------------------------------------------ [07/Feb/2018 15:48:47] "GET /2.2/static/css/ie.css HTTP/1.1" 200 263 │2018-02-07 16:10:02,434 INFO [07/Feb/2018 15:48:47] "GET /2.2/static/css/responsive.css HTTP/1.1" 200 22106 │2018-02-07 16:10:02,435 INFO 0 sent; 0 deferred; [07/Feb/2018 15:48:47] "GET /2.2/static/css/dataportal.css HTTP/1.1" 200 13054 In settings Log path is defined but it only logs logger.info messages. I am having a new thread for a sending emails but it abrubtly stops in between with no trace of any error messages. -
How to display records belongs only for user instead for all users
I have a little problem. I want to to display in list only records belongs to user whos add it. In my app when I'am login as 'user' and I want to add new records incude records from list, I see all records in db from ForeignKey. How to make it correctly? In 'Strona www' when I expand the list I see all records, not only records added by user personally. My view for it is: @login_required def new_keyword(request): if request.method == "POST": new_keyword = KeywordForm(request.POST) if new_keyword.is_valid(): new_keyword=new_keyword.save(commit=False) new_keyword.user = request.user new_keyword.save() messages.success(request, 'Pomyślnie dodano słowo kluczowe') return render(request, 'konto/new_keyword_ok.html') else: new_keyword = WebsiteForm() return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword}) in forms.py I have: class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') models.py class Keyword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") www = models.ForeignKey(Website, on_delete=models.CASCADE, verbose_name="Strona www") keyword = models.CharField(max_length=250, verbose_name="Słowo kluczowe", unique=False) urls.py path('new-keyword/', new_keyword, name='new_keyword'), and html for display the form is: {% if request.user.is_authenticated %} <form action="." method="post"> {{ new_keyword.as_p }} {% csrf_token %} <p><input type="submit" value="Dodaj nowe słowo kluczowe" ></p> <a href="{% url 'dashboard' %}">Powrót do monitoringu</a> </form> {% endif %} -
how can I truncate text and remove html tags in django template
I've used truncatechars but if text contains a html tag, it will show the tag for me. {{content.text|safe|normal_text|truncatechars:140}} for example displays something like this: <p>hi</p> I want to remove p tag. -
Django filter by first letter of model
I have a problem and i dont know how to solve it. I got this template generating /list/a,b,c, etc. And i want to show in this a,b,c url only model with the same letter. list template <div class="panel-body anime-list text-center"> <div class="btn-group btn-group-xs"> {% for i in alphabet %} <a href="{{i}}" class="btn">{{i}}</a> {%endfor%} </div> </div> model's class Anime(models.Model): title = models.CharField(max_length=300, unique=True) ongoing = models.BooleanField(default=True) add_date = models.DateTimeField('date published') How can i filter that in another desired template -
Is it a good idea to use django and postgres only for authentication along with mongo engine?
I am currently working with mongoengine along with Django. The authentication happens with the Django authentication backend with PostgreSQL. The rest application data is stored in MongoDB. Is it a good idea to use a structure like this in a stable app? -
Django 1.11 how to resolve list_filter duplicates
In my Model, a __str__(self) that derives the quarter and year from the DateTimeField of when Response was created. Models.py class Response(models.Model): created = models.DateTimeField(auto_now_add=True) def __str__(self): msg = u"Q%d %d" %(((self.created.month-1)//3)+1, self.created.year) return msg In Admin, I want to be able to filter records based on the Quarter in which they were submitted (actually, I want to filter by who hasn't submitted a Response for a particular quarter, which I think I can achieve with a well placed tilde later), so I have the following: Admin.py class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') list_filter = ('response__created', 'response') def latest_response(self, obj): return obj.response_set.latest('created') I have submitted four responses so far in testing (through the def __str__ I have 2 x "Q1 2018", and 2 x " - "), and the result looks like this: Any ideas why I am getting 3 x "Q1 2018" and 1 x " - "? I want Only 1 x "Q1 2018" in the filter list Bonus question - any idea how to set a limit to the number of items listed in the filter_list (by response)? I want to limit them to the latest 4 which, might be problematic as I'm using a string. EDIT … -
Edit foreign key value in Django admin
I have model an Django model as follows: class BusinessUnit(models.Model): name = models.CharField(max_length=255) address = models.ForeignKey(to=Address) vat_number = models.CharField(max_length=50) telephone = models.CharField(max_length=50) email = models.CharField(max_length=50) manager = models.ForeignKey(to=User, null=True) def __unicode__(self): return self.name How can I change address directly from BusinessUnit in Django admin? Now I can only select the address, but I cant change it. I need to go to Address model and change it there, but I want to be able to change it directly in BusinessUnit model. Any idea how can I do that? -
How come the field value on the related object isn't updated after saving?
I have a one-to-many relationship in django. (one Author is to many Books) The problem is that when I update a field of an Author through a Book, I get the old value for the Author's field when retrieving the Book again. >>> book1 = Book.objects.get(pk=1) >>> book1.author.name u'Old Author' >>> book1.author.pk 1 >>> book1.author.name = "New Author" >>> book1.author.save() >>> book1.author.name u'New Author' >>> author1 = Author.objects.get(pk=1) >>> author1.name u'New Author' >>> book2 = Book.objects.get(pk=1) >>> book2.author.pk 1 >>> book2.author.name u'Old Author' # I'm expecting this to be u'New Author' What am I missing here? -
validating a form using get method in django
I am new to programming, I hope my question is not very basic. Here I am trying to taking the input and showing output on the same page. I went through an article that said I should use GET method to do so. my view def calc(request): if request.method == 'GET': form = CalculationForm(request.GET) if form.is_valid(): number1 = form.cleaned_data.get('first_number') number2 = form.cleaned_data.get('second_number') sum = number1 + number2 sum.save() return render(request, 'calculation\calculator.html', {'sum': sum}) else: form = CalculationForm() return render(request, 'calculation\calculator.html', {'form': form}) my HTML <body> <form method="get" action=".">{% csrf_token %} {{ form }} <input type="submit" name="Register" value="Submit" /> {{sum}} </body> Here I am showing the user simple form user input numbers in two fields Add the numbers showing it back to the user on the same page My form is getting rendered and the fields are displaying I am able to enter the number in the field but when I click submit I get an error. Anyone -
Django MTPP display recursive hierarchical category in REST API
I am trying to display my recursive category model in my Django REST API list view. This is how it is now: "results": [ { "pk": 3, "title": "Test", "category": 7, }, ... ]} I want to achieve something like this: "results": [ { "pk": 3, "title": "Test", "category": [ { "id": 5, "name": "Cat", "slug": "cat", "child": [ { "id": 7, "name": "Parser", "slug": "parser", } ] } ], }, ... ]} I am currently using Django MPTT to create a hierarchical Model. This is the Category in models.py: class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.SET_NULL) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name = "Category" verbose_name_plural = "Categories" def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i + 1])) return slugs def __str__(self): return self.name I am using generic views from Django Rest Framework to create the view. In views.py: class CaseListCreateView(generics.ListCreateAPIView): serializer_class = CaseSerializer def get_queryset(self): qs = Case.objects.filter(active=True) query = self.request.GET.get("search") if query is not None: qs = qs.filter(Q(title__contains=query) | Q(text__contains=query)).distinct() return qs def perform_create(self, … -
unable to complete django installation
I downloaded the necessary files from the link https://github.com/django/django.git and pasted them in to my virtual env directory After setting up and activating the virtualenv, when I run the following command: $ pip install -e django/ It produces this error: (ENV) C:\WINDOWS\system32>pip install -e django/ django/ should either be a path to a local project or a VCS url beginning with svn+, git+, hg+, or bzr+ I am a Windows user. I think the command is for bash not for cmd. Is it necessary to use this git tool to finally work with django ? As instructed on the Django website : -
using Filtered Count in django over joined tables retuns wrong values
To keep it simple I have four tables(A, B, Category and Relation), Relation table stores the Intensity of A in B and Category stores the type of B. A <--- Relation ---> B ---> Category (So the relation between A and B is n to n, where the relation between B and Category is n to 1) What I need is to calculate the occurrence rate of A in Category which is obtained using: A.objects.values( 'id', 'relation_set__B__Category_id' ).annotate( ANum = Count('id', distinct=False) ) Please notice that If I use 'distinct=True' instead every and each 'Anum' would be equal to 1 which is not the desired outcome. The problem is that I have to filter the calculation based on the dates that B has been occurred on(and some other fields in B table), I am using django 2.0's feature which makes using filter as an argument in aggregation possible. Let's assume: kwargs= {} kwargs['relation_set__B____BDate__gte'] = the_start_limit I could use it in my code like: A.objects.values( 'id', 'relation_set__B__Category_id' ).annotate( Anum = Count('id', distinct=False, filter=Q(**kwargs)) ) However the result I get is duplicated due to the table joins and I cannot use distinct=True as I explained. (querying A is also a must since … -
Django selecting data from model according to other model
i've got django database where is model X with attribute ManyToManyField(Y). Right now I need to select all the data from all the Y which are not related to one selected X. How can I do this by using database and not algorithm? I've used for-cycle but I would like to use more effective and advanced way. Thanks. -
What are the implications of making SECRET_KEY public? [on hold]
I know the SECRET_KEY for a website made in Django. The owner of the site has accidentally made the settings.py public. How can this be exploited by malicious people? And how do I make the owner aware that this is a serious issue, without being persecuted? From Django's official documentation: The secret key is used for: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. -
nginx proxy causing error when response takes too long to reply
I have an nginx configuration that redirects to a Django rest service (Through gunicorn). Everything works correctly, but when the response is too big (takes more than 30s to respond) I'm getting a 503 service unavailable error. I am sure it is because of this issue because it works correctly on other requests, and only on specific requests where the response is too big (and fetching the request from a third party api) takes too long. Below is my nginx configuration : server { listen www.server.com:80; server_name www.server.com; client_max_body_size 200M; keepalive_timeout 300; location /server/ { proxy_pass http://127.0.0.1:8000/; proxy_connect_timeout 120s; proxy_read_timeout 300s; client_max_body_size 200M; } location / { root /var/www/html; index index.html index.htm; } } I am sure the issue is from Nginx and not gunicorn, because if i do a curl from inside the machine i get a response. Thanks, -
how to use variable data to use in template tag in Django template
In views.py file class home(TemplateView): template_name='article.html' def post(self,request): file_path = '/u/vinay/checking.py' args={'file_path':file_path} return render(request,self.template_name, args) In article.html file {% load static %} <a href="{% static '{{ file_path }}' %}" download ><button class="button button2">Download plan</button></a> But i'm getting no file as output from GUI. As i'm creating download link for that file in file_path location.So how do i render text from views to article.html -
How do you do multiple joins simultaneously in Django ORM?
Given a bunch of graphical maps, I need to query which maps a user has access to, either because he owns the map or because he has been granted 'membership' of it. There is a Map_desc (Map description) model, and for each object in Map_desc, potentially many Mapmembership objects. Because it will later be fed to ModelChoiceFields in templates, I need a single QuerySet that will return all the Map_desc objects that have related Mapmembership objects, plus all the Map_desc objects that have 'owner' set to the current user. It's a simple join, but surprisingly difficult to pull off in Django. models.py (simplified) class Map_desc(models.Model): owner = models.ForeignKey(User, null=False, on_delete=models.CASCADE) class Mapmember(models.Model): member = models.ForeignKey(User, null=False, on_delete=models.CASCADE) ofmap = models.ForeignKey(Map_desc, null=False, on_delete=models.CASCADE) What I tried first that didn't work (in semi-pseudo code): shared = Map_desc.objects.filter(id=mapmember_set.ofmap) then a second query to get the Maps owned: owned = Map_desc.objects.filter(owner=thisUser) and tying them together with accessiblemaps = chain(shared,owned) The problem is that because there are multiple Map_desc objects, mapmember_set is not actually available. It does work if you limit the query to just one Map_desc, using .first(), and this is what all the tutorials and SO questions I've found do. So I came … -
Django not properly cleaning out test database
Every time I run ./manage.py test and the tests run, the db.sqlite3 gets a little larger. This is concerning; anyone know what might cause this? The file is about 500mb right now, and growing. The test case file extends class UploadFiles(LiveServerTestCase): And is using chrome driver with selenium -
Python- Django Tasypie - How to implement polling for requests that take a lot of time
My Tastypie rest API has a function that takes a lot of time to complete. How can I implement a polling mechanism with the client so that the request doesn't time out. Can you provide me an example or point me to material that I can use. -
Bootstrap modal doesnt show with location.href
I want the Bootstrap modal to pop up first and I will get some data from it and with that data I want to go a href location. function callModal(curr){ var currele = curr.id; alert(currele); switch (currele){ case "add_resource": { $("#myModal").modal('show'); window.location.href="add/resource"; break; } } } <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Modal Example</h2> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <div> <a href="#" onClick= "callModal(this)" id = "add_resource" >add resouce</a><br> </div> </body> </html> The issue is : only the href is being called, not the modal If I remove the href call , then the modal is getting called fine, but together its not getting called. ** In the Code snippet , you can ignore the undefined href location error -
Python Django - Why does Django make 2 calls to the DB for one request
For the below code I noticed that the backend is makeing 2 calls to the DB. userApps = CustomerUserMapping.objects.filter(user=user).values_list('customer__applicationName', flat=True) This results in [07/Feb/2018 12:51:30] DEBUG [django.db.backends:90] (0.004) SELECT "core_customers"."applicationName" FROM "core_customer_user_mapping" INNER JOIN "core_customers" ON ("core_customer_user_mapping"."customer_id" = "core_customers"."customerId") WHERE "core_customer_user_mapping"."user_id" = 'xxx' ORDER BY "core_customer_user_mapping"."user_id" ASC, "core_customers"."customerName" ASC, "core_customers"."customerId" ASC LIMIT 21; args=('xxx',) [07/Feb/2018 12:51:30] DEBUG [django.db.backends:90] (0.000) SELECT "core_customers"."applicationName" FROM "core_customer_user_mapping" INNER JOIN "core_customers" ON ("core_customer_user_mapping"."customer_id" = "core_customers"."customerId") WHERE "core_customer_user_mapping"."user_id" = 'xxx' ORDER BY "core_customer_user_mapping"."user_id" ASC, "core_customers"."customerName" ASC, "core_customers"."customerId" ASC; args=('xxx',) Can anyone provide a explanation for this. Or tell me what I am doing wrong ? -
Convert String to JSON in python
I am receiving a response from a service in text format unfortunately I cannot ask them to send me in JSON format) below is the reponse: '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}' I want to either convert this to dict or json but I am unable to do so, as the string inside the '{ }' does not have single or double quotes. I have tried using json.loads(), json.dumps(), ast.literal() and also few other methods, but was not able to achieve the desired output. The output desired is: {'message': 'Successfully sent data for processing', 'execId' : 'd03c96hg-4098-47b9-9e4b-3cb2c' }