Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Performance of Delete/Create vs Delete/Update
Trying to figure out best practice here. I am writing some end points that will essentially combine a group of objects if their dates become contiguous. Say there are three objects I want to group. obj1 = {id: 1, start: 1/1/18, end: 1/2/18} obj2 = {id: 2, start: 1/2/18, end: 1/3/18} obj3 = {id: 3, start: 1/4/18, end: 1/5/18} Are there any performance benefits or best practices to either of the following - Create one new object which is essentially the 3 previous objects grouped together by date. Then delete the three other objects. obj4 = {id: 4, start: 1/1/18, end: 1/5/18} obj1.delete() obj2.delete() obj3.delete() or Update one objects fields to represent the new dates. Then delete the other two objects. obj1.end = 1/5/18 obj1.save() obj2.delete() obj3.delete() Just pseudo code here, but this is in a django app. Thanks -
Forked django-oscar app with custom model unable to migrate
I am using django-oscar and forked some of the apps to use a custom model. Specifically with the catalogue model. By default there are products, product types and product categories. I am trying to extent the model to have a collections table, and to have each product be associated with a collection. I want to make the relationship so that when a collection is deleted all associated products are deleted, but so that deleting a product does not delete a collection. Aside from adding a new collection table, I extent the product table to have a multiplier field (which will contain an integer used to multiply the wholesale price...if there is a better way to do this please inform) and a foreign key to the collections table. Based on my understanding everything looks good. This is my models.py from the forked catalogue app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.IntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE) multiplier = models.DecimalField(max_digits=2, decimal_places=1) from oscar.apps.catalogue.models import * When I do makemigrations via manage.py, after asking for default values (something I will deal … -
Django dependent/ chained drop down form
I am trying to add a chained drop down form to a project I'm creating. I've tried numerous solution's including django smart select and using jQuery but I can't seem to get it to work.I want a drop down form where if one option is selected in one drop down menu more options will be displayed based on the the other drop downs. For example if I select the state as Texas the next drop down will show cities in Texas like Dallas. I'm using django 2.1.2 and most of the mentioned solutions are running on an older version of django. I attatched an image to clarify. Thanks example image -
How to implement tokenauthentication before views?
I have been learning how to use djangorestframework token authentication using different blog posts and youtube videos. As for reference, I was following the blog here: https://chrisbartos.com/articles/how-to-implement-token-authentication-with-django-rest-framework/ I could not understand how are we going to check the token before accessing any page. I mean, I am developing an app, that exposes the todos a user creates through the rest framework. I have added a login that saves a user and returns the token created for that person. Now,I want to check that token to find the todos api that the person created and view it in my browser in a seperate url. As an example: Once I login through localhost:8000/api/v1/login, I should get the todos created by me at api/v1/todos in json rest api format. And if I go to api/v1/todos/1/, it should give me the details of the todo, as I have created in the serializers. It would be great if someone could help. -
Using variable names rather than ints in a Django url path
I have a model called Label: class Label(models.Model): """The label a song was released on.""" name = models.CharField(max_length=100) def __str__(self): """String for representing the model object.""" return self.name And I am defining the url path(s) for each individual model instance of label: # Page for a single label. path('labels/<int:label_id>/', views.label, name='label'), Is it possible to use the label.name attribute rather than an int:label_id in the URL path? How can this be done? This is the corresponding code in views.py: def label(request, label_id): """Show a single label and associated songs.""" label = Label.objects.get(id=label_id) context = {'label': label} return render(request, 'great_songs_app/label.html', context) -
How to add a LogEntry for a Django data-migration?
Thinking of adding a Django admin log-entry in a data-migration, to ensure that the admin logs will reflect the fact that a data-migration has taken place. Assuming this could be done -- please correct me if I'm wrong -- using the approach described here and here , I have two questions: Does this make sense, or should these things be kept separate? What user should I use for the LogEntry (should I create a dedicated user)? The docs are not very forthcoming on the subject of LogEntry usage. -
Internal Server Error in Python Django using TastyPie
That's the error I've got Internal Server Error: /drawevent/ Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\tastypie\resources.py", line 211, in getattr return self.fields[name] KeyError: 'get' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Program Files\Python37\lib\site-packages\django\utils\deprecation.py", line 93, in call response = self.process_response(request, response) File "C:\Program Files\Python37\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: File "C:\Program Files\Python37\lib\site-packages\tastypie\resources.py", line 213, in getattr raise AttributeError(name) AttributeError: get [14/Dec/2018 12:01:21] "GET /drawevent/ HTTP/1.1" 500 64469 -
Nginx: Proxy_pass error to Django Project
Problem I have a Django project with Gunicorn that I am trying to deploy with Nginx, but it is erring on line 19 where I try to set the proxy_pass to my domain. proxy_pass <my_public_domain>.com; The error nginx: [emerg] invalid URL prefix in /etc/nginx/sites-enabled/default:19 My code My Gunicorn command is: /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app And then the Nginx config is the following. I have replaced by actual domain with <my_public_domain> upstream django { server 127.0.0.1:8001; } server { set $my_host $host; if ($host ~ "\d+\.\d+\.\d+\.\d+") { set $my_host "<my_public_domain>.com"; } listen 80; server_name <my_public_domain>.com; charset utf-8; error_log /dev/stdout info; access_log /dev/stdout; location / { proxy_pass <my_public_domain>.com; proxy_set_header Host $my_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } if ($http_x_forwarded_proto != 'https') { return 301 https://$my_host$request_uri; } } -
Django Soft deletion and generic relationship manager
I'm using Django 2.0 in a project and I'm implementing a soft delete function so I can recover deleted objects. I've used this this implementation of soft deletion in my Django project, and it works fine. But some models have GenericRelation with objects that may be soft deleted. Is there a way to implement a GenericRelationManager like the BaseModelManager, that will ignore soft deleted objects? For example, suppose I have the following code (borrowed from this site): from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class Activity(BaseModel): FAVORITE = 'F' LIKE = 'L' UP_VOTE = 'U' DOWN_VOTE = 'D' ACTIVITY_TYPES = ( (FAVORITE, 'Favorite'), (LIKE, 'Like'), (UP_VOTE, 'Up Vote'), (DOWN_VOTE, 'Down Vote'), ) user = models.ForeignKey(User) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() And from django.db import models from django.contrib.contenttypes.fields import GenericRelation from activities.models import Activity class Post(models.Model): ... likes = GenericRelation(Activity) class Question(models.Model): ... activities = GenericRelation(Activity) class Answer(models.Model): ... votes = GenericRelation(Activity) class Comment(models.Model): ... likes = GenericRelation(Activity) If I soft delete an activity, I would still be able to find the soft deleted activity through these GenericRelations. Can I … -
Django Context TypeError: context must be a dict rather than Context
template = loader.get_template('organizer/tag_list.html') context = Context( { 'tag_list': Tag.objects.all() } ) template.render(context) Running these things on terminal produces following error: Traceback (most recent call last): File "", line 1, in File "/home/noitanec/noitanec/django/django/lib/python3.6/site-packages/django/template/backends/django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/home/noitanec/noitanec/django/django/lib/python3.6/site-packages/django/template/context.py", line 270, in make_context raise TypeError('context must be a dict rather than %s.' % context.class.name) TypeError: context must be a dict rather than Context. What's wrong here ? -
How to specify Accept headers from rest_framework.test.Client?
I'm trying to set up an API endpoint to reply with HTML or JSON depending on the incoming request's Accept headers. I've got it working, testing through curl: > curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/ {"message":"feedback Hello, world!"} > curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/ <html><body> <h1>Root</h1> <h2>feedback Hello, world!</h2> </body></html> I can't figure out how to use the APITestCase().self.client to specify what content should be accepted, though. My view looks like class Root(APIView): renderer_classes = (TemplateHTMLRenderer,JSONRenderer) template_name="feedback/root.html" def get(self,request,format=None): data={"message": "feedback Hello, world!"} return Response(data) and my test code looks like class RootTests(APITestCase): def test_can_get_json(self): response = self.client.get('/feedback/',format='json',Accept='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.accepted_media_type,'application/json') js=response.json() self.assertIn('message', js) self.assertEqual(js['message'],'feedback Hello, world!') which dies on the test for response.accepted_media_type. What's the right way to do this? All I can find says that the format argument should be sufficient. -
libraria to generate graph
I am making an application in django for hypothesis testing, there is a jquery library that allows you to make a graph to represent the case -
How torrent sites live-update its torrent file's seeds and leeches? [on hold]
I'm new to programming through python. I like to create a Django based torrent sharing site. but I have a problem with seeds and leeches, It is, How torrent sites live update its torrent file's seeds and leeches. Is it some kind of Ajax technique? if you could, please describe it from python based examples. thank you. -
Django inline formset
I have a parent and several child forms using an inline formset. It works fine. Depending on a value in the parent form, I need to check that the right number of child forms has been submitted. I know I can access the parent form using self.instance.FOO when overriding BaseInlineFormSet and again this works fine, but I can't find a way to determine how many actual forms have been submitted and vitally have data in them. Anyone know how? Many thanks -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 6: invalid continuation byte
I tried a number of solutions on line, but still got the same error at my browser http://127.0.0.1:7000/json/json_data_dump. Can anyone please help? By the way, if I do below and only insert the non-French character in Teradata, my code will work. CREATE TABLE tablename( Category varchar(80) not null, -- CHARACTER SET UNICODE, Below is the python code: def json_data_dump(request): sql = """ select category as dept from db.tablename order by 1;""" df = pd.read_sql(sql, teradata_con()) df_dept = df[['dept']].drop_duplicates() dic = {'dept':[]} for index, row in df_dept.iterrows(): dic['dept'].append({ 'dept':row['dept'].decode('latin-1').encode("utf-8") #.encode("utf-8") #.decode('latin-1') #decode("utf-8") }) return HttpResponse(json.dumps(dic,encoding = "ISO-8859-1")) # return HttpResponse(json.dumps(dic,ensure_ascii=False) ) -
Where is User Class using MongoDB(Djongo) in Django
I am using Django2.1 with MongoDB, Djongo ORM. as you can see the documentation of Djongo is very short and incomplete. I want to write a custom user model that inherits from the django's original User Model. since it's nosql and MongoDB, I've installed djongo and all my models inherits from djongo.models.Model, not standard django.models.Model. and unfortunately this djongo.models unlike django.models has no such a class named User. but somehow there is a auth_user collection im my mongoDB after makemigration and migrate my project and registered normally in my admin panel. I understand probably there is no such a thing "inheritance" in nosql database, if that's so, where is this user model that creates auth_user collection ind DB and holds all my user's info. I want to manipulate it directly. Regards. -
Django calling a function and coming back to same function
Currently I have around 5 functions where I use a common code. I was trying to keep this common code as a function and call in these 5 functions. This will be my common function: def commonfunc(key): do something These are kind of my other 5 functions where I use this common code. To change something I have to edit all my 5 functions. I am looking to call this common function in these 5 common functions. def func1(request) do something... commonfunc(key) use commonfunc.... return httpsresponse(request,.....) In this code everything works till second line. Thereafter it does not comeback to func1 and do rest of things. What I am missing? -
Add Json data to Django model automatically and only once
I created a method that saves Json data to a Django model: models.py: class Object(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) @classmethod def save_json_data_to_model(cls): with open('data.json', encoding='utf8') as file: data = json.load(file) for obj in data: Object( name=obj['name'], address=obj['Street']).save() When i was testing the project I ran the method in the shell and everything is working fine. But I want the data to be populated in the model automatically and only one time. What is the best way to achieve this? I tried this in views.py: if __name__ == '__main__': Obj.save_json_data_to_model() -
Changing a function based view to a class based view
How would one change this function based view into a class based view? It represents a post view with a comments section. def post_detail(request, pk): post = get_object_or_404(Post, id=pk) comments = Comment.objects.filter(post=post).order_by('-id') is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(post=post, user=request.user, content=content) comment.save() resp = post.get_absolute_url() return HttpResponseRedirect(resp) else: comment_form = CommentForm() context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), 'comments': comments, 'comment_form': comment_form } return render(request, 'feed/post_detail.html', context) -
How to generate Bootstrap DatePicker datesDisabled dynimcally
Working with Django and Ajax. I have used Ajax to get my dynamic dates, now the issue is feeding the dates to the datesDisabled: [] array. When i alert(data) i get my dates alerted perfectly. Now i just need to pass the array to the datesDisabled. <script> (function($) { 'use strict'; $(document).ready(function() { $("#id_unit").change(function () { let unit_id = $(this).val(); $.ajax({ url: {% url 'unit_booked_date' %}, data: { 'unit': unit_id, }, success: function (data) { return data } }) }); $('.input-group.date').datepicker({ autoclose: true, todayHighlight: true, allowClear: true, datesDisabled: [ data ], }); }); })(window.jQuery); </script> -
Timezone randomly changes in Django admin
There are two instances of a Django project deployed using uWSGI server with NGINX proxy on Ubuntu server 14.04. In settings I have: TIME_ZONE = 'Europe/Moscow' # UTC +03.00 USE_TZ = True On one instance Dates and Times are displayed in correct time zone. On another instance time zone keeps changing between +03.00 and +12.00 and I didn't manage to notice any pattern in that. I checked: Ubuntu time zone with timedatectl status (the same on both servers) PostgreSQL timezone (the same on both servers) uWSGI and NGINX setting are kept in VCS, so they are the same as well (although doesn't seem to have anything time zone related) The only difference I can think of is that the properly working instance is on Azure, while the problematic one is physically hosted in UTC +03.00 (local cloud provider). However, other Django projects hosted there work properly. What else can I check to isolate and solve this problem? -
dj-stripe UpcomingInvoice usage
Towards the end of a free trial period I am trying to send customers a notification that they will soon be charged with dj-stripe. I am trying to use a webhook to initiate the notification and then UpcomingInvoice to retrieve the amount. I can see in my stripe dashboard that I have customers with trial ending tomorrow and an upcoming invoice, however dj-stripe always returns an empty queryset. In PDB when I try the code I also can't see any calls to the stripe api which would need to occur to pull the data. @webhooks.handler("customer.subscription.trial_will_end") def charge_upcoming(event, **kwargs): UpcomingInvoice(customer=event.customer).invoiceitems pdb.set_trace() <QuerySetMock []> What am I doing wrong? Thanks! -
Connexion impossible avec mon plist pour ipa (django)
Bonjour, J'ai fais un petit code pour télécharger mon ipa, son un iphone. J'ai utiliser plist, pour le télécharger. Cependant, quand j'essaye de le télécharger, il me dis "Connexion à monsite.com impossible". Je n'arrive pas a comprend d’où viens le problème? Voici mon code : return HttpResponse('<a href="itms-services://?action=download-manifest&url=https://polymission.polymont-itservices.fr/download/manifest.plist">Install ME!</a>') Merci d'avance :) -
Celery apply_async get get called multiple times
I have created a task @app.task(bind=True, max_retries=1) def notify_feedback(self, req_id): #some things I have called this task from my view with a delay of 1 hour like later = datetime.datetime.utcnow() + datetime.timedelta(hours=1) notify_feedback.apply_async((req_id,), eta=later) When I checked the SQS Messages in Flight it has 1 count pending after one hour this notify_feedback get called multiple times. Did any one encountered this kind of issue with celery? celery- 4.1.0 is used -
Pipenv installationError: Command "python setup.py egg_info" failed with error code 1 in
I have recently moved over to using pipenv and every now and then I get the following error when trying to install packages: $ pipenv lock --clear --verbose pipenv.patched.notpip._internal.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in $ pipenv install social-auth-core line 704, in from_line line, extras = _strip_extras(line) TypeError: 'module' object is not callable $ python setup.py egg_info (k, v) for k, v in attrs.items() File "/home/user/.local/share/virtualenvs/django-app-VE-name/lib/python3.6/site-packages/setuptools/dist.py", line 367, in __init__ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): AttributeError: module 'pkg_resources' has no attribute 'iter_entry_points' The github pages for the error have not been helpful, thank you