Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding multiple Django users with a blank email
I have a Django app using a PostgreSQL db, where the user migration has an email field with unique=True. My User model has: email = models.EmailField(_('email address'), unique=True, blank=True) I want to be able to create multiple users with blank emails, but when the email is not blank it has to be unique. Currently, when I create two users with a blank email I get this error: duplicate key value violates unique constraint "accounts_user_email_b2644a56_uniq" -
Displaying d3 chart in django
I was going through the library NVD3 and have found this as an example on the website: d3.json('cumulativeLineData.json', function(data) { nv.addGraph(function() { var chart = nv.models.cumulativeLineChart() .x(function(d) { return d[0] }) .y(function(d) { return d[1]/100 }) //adjusting, 100% is 1.00, not 100 as it is in the data .color(d3.scale.category10().range()) .useInteractiveGuideline(true) ; chart.xAxis .tickValues([1078030800000,1122782400000,1167541200000,1251691200000]) .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) }); chart.yAxis .tickFormat(d3.format(',.1%')); d3.select('#chart svg') .datum(data) .call(chart); //TODO: Figure out a good way to do this automatically nv.utils.windowResize(chart.update); return chart; }); }); The image is something like this: Check the live demo here: http://nvd3.org/examples/cumulativeLine.html The json file is here: Json file for example Now I was willing to include such charts in the django example. So I went on checking the implementation of Django-NVD3. But I could not find anything related to it and the documentation written by author is not understood by me. Please let me know how I can include d3 chart in the django frame in real time. -
the proper way to run django rq in docker microservices setup
I have somehow bad setup of my docker containers I guess. Because each time I run task from django I see in docker container output of ps aux that there is new process created of python mange.py rqworker mail instead of using the existing one. See the screencast: https://imgur.com/a/HxUjzJ5 the process executed from command in my docker compose for rq worker container looks like this. #!/bin/sh -e wait-for-it for KEY in $(redis-cli -h $REDIS_HOST -n 2 KEYS "rq:worker*"); do redis-cli -h $REDIS_HOST -n 2 DEL $KEY done if [ "$ENVIRONMENT" = "development" ]; then python manage.py rqworkers --worker-class rq.SimpleWorker --autoreload; else python manage.py rqworkers --worker-class rq.SimpleWorker --workers 4; fi I am new to docker and wondering a bit that this is started like this without deamonization... but is it a dockerish way of doing thing, right? -
Django complex query through builder
I have not been able to make a complex query using ORM for some time. I know that this is possible, so I will forgive help. class Game(models.Model): no matter class Competition(models.Model): game = models.ForeignKey(to='game.Game', verbose_name=_('game'), related_name='competitions', on_delete=models.PROTECT) class User(models.Mode): no matter class Balance(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE, primary_key=True) class BalanceTransaction(models.Model): TYPES = ( (TYPE_COMMISSION, _('commission')), } balance = models.ForeignKey(to=Balance, on_delete=models.CASCADE, related_name='transactions') amount = models.DecimalField(_('Transaction amount'), default='0.0', max_digits=28, decimal_places=18, null=False, blank=False) type = models.CharField(_('type'), max_length=10, default=TYPE_DEPOSIT, choices=TYPES, null=False, blank=False I have to return a queryset of games, where each element will have an additional "income" field that stores the sum of all transactions of this game with the type "commission" Game.objects.filter(publisher__owner=self.request.user.pk).annotate( income=Sum(Case( When( Q(publisher__owner__balance__transactions__type=BalanceTransaction.TYPE_COMMISSION), then=???, ) )) It seems that this way it will not be possible and I have to use subquery, but so far I haven't succeeded. -
Object of type Company is not JSON serializable when writing tests
I'm having an issue in Django RestFramework in testing. I have the following test: def test_update_coupon(self): response = self.make_coupon_request( kind="put", version="v1", id=2, data=self.valid_coupon_data ) self.assertEqual(response.status_code, status.HTTP_200_OK) Where make_coupon_request has a return of: return self.client.put( reverse("coupon", kwargs={ "version": kwargs["version"], "pk": kwargs["id"] } ), data=json.dumps(kwargs["data"]), content_type='application/json' ) and valid_coupon_data where the problem is occurring is: self.valid_coupon_data = { "company": Company.objects.get(id=1), "name": "Coupon Updated", "added": "2018-11-30", "code": "TESTCODE" } The error I am getting is in make_coupon_request that json.dumps cannot serialize valid_coupon_data: "TypeError: Object of type Company is not JSON serializable" I have a serializer for Company: class CompanySerializer(serializers.ModelSerializer): coupons = CouponSerializer(many=True, read_only=True) class Meta: model = Company fields = ("name", "coupons") And for coupon: class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = ("company", "name", "added", "code") Basically I know that somehow I need to use a serializer in order to make my test work, as json.dumps isn't accepting the raw Company object... but I am not sure how nor do I quite understand why. Here are my 2 models for reference: class Company(models.Model): name = models.CharField(max_length=255, null=False) class Meta: verbose_name_plural = "Companies" class Coupon(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name='coupons') name = models.CharField(max_length=100) added = models.DateField(auto_now_add=True) code = models.CharField(max_length=255, null=False) -
Ansible django_manage throws UnicodeDecodeError on ubuntu server 18.04 but running the command manually works fine
I have a project (python 3.6, django v2.1) that I deploy using Ansible v2.4.6 to my VM ubuntu server 18.04 (on the old ubuntu server 16.04 there is no problem, everything works fine). I have a custom Django management command called ensure_initial_data: from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): perm_list = [ { 'content_type': ContentType.objects.get( app_label='app_accounting', model='account'), 'codename': 'account_list', 'name': 'ver lista de cuentas', }, { 'content_type': ContentType.objects.get( app_label='app_accounting', model='summary'), 'codename': 'summary_list', 'name': 'ver lista de resúmenes', }, ] self.stdout.write('Creating missing permissions ...') for i, kwargs in enumerate(perm_list): p, _ = Permission.objects.get_or_create(**kwargs) self.stdout.write(' {:03d} {:15s} {:40s} {}'.format( i + 1, p.content_type.app_label, p.codename, p.name)) Which I try to call it in Ansible like this: - name: run django "ensure_initial_data" django_manage: command: 'ensure_initial_data' app_path: '{{ django_app_base_dir }}' virtualenv: '{{ django_app_base_dir }}/.venv' notify: restart gunicorn app in supervisor it throws the following error (because of the letter with accent in the second Permission, in the word resúmenes): TASK [webserver : run django "ensure_initial_data"] ****************************************************************************************************** fatal: [ubuntu1]: FAILED! => { "changed": false, "cmd": "./manage.py ensure_initial_data", "failed": true, "msg": " stdout: Creating missing permissions ... 001 app_accounting account_list ver lista de cuentas contables stderr: … -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty - Even when SECRET_KEY is set in settings.py
I'm having this error while trying to run my Teonite_project/web_scrapper.py script: File "C:/Users/kfhei/Desktop/Teonite_project/Teonite_project/web_scrapper.py", line 9, in <module> django.setup() File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\kfhei\Desktop\Teonite_project\Teonite_project\Teonite_project\settings.py", line 15, in <module> django.setup() File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 125, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My script: from bs4 import BeautifulSoup from urllib.request import Request, urlopen #import simplejson as json import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Teonite_project.settings") import django django.setup() from words.models import Word from authors.models import Author URL_DOMAIN = 'https://teonite.com/blog/' def get_links(url): ''' Returning the array of links to blog articles … -
Postgres: subdivide table by a field
I have a spatial table with 100 million ish rows. When updating my data, I have often had to update all the rows that fall in some US state. I find that trying to do any operations on the 100 million record table is very slow. All of the rows have a state field (e.g. state_code=RI), but I can't figure out how to make good use of it. However, if I create a new table with just the rows in the state that needs updating, all read and update operations are very fast (maybe 100x faster). My question: is there a good way to quickly index by state, or should I just make a different db or table for each state? -
Get model attribute from other class in same model
How do I get value of another class in the same model? Can I also use properties? I want to use Finance.net_income and Finance.net_margin inside the Stats Class. I tried searching for an anwser but I couldnt find it, I am also new to django. class Stats(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE) shares_outstanding = models.FloatField(default=0) @property def earnings_per_share(self): ####### ISSUE IS HERE ##### return Finance.net_income / self.shares_outstanding class Finance(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE) total_revenue = models.FloatField(default=0) operating_income = models.FloatField(default=0) date = models.DateField(null=True, blank=True) net_income = models.FloatField(default=0) cash = models.FloatField(default=0) total_debt = models.FloatField(default=0) @property def operating_margin(self): if self.total_revenue: now = (self.operating_income / self.total_revenue)*100 else: now = 0 return now @property def net_margin(self): if self.total_revenue: now = (self.net_income / self.total_revenue)*100 else: now = 0 return now -
gunicorn and Django project
I just followed instructions from DigitaL Ocean. After: sudo gunicorn --bind 0.0.0.0:8000 nameofmyproject.wsgi:application bind Gunicorn my site is not available.I tried to change port from 8000 to 80, and then site is reachable, but without any static files like css and images. Don't know why this happens. sudo ss -naptu state listening | grep :80 Output is: tcp 0 128 *:8000 *:* users:(("gunicorn",pid=18461,fd=5),("gunicorn",pid=18455,fd=5)) What can I do? -
Django queryset values to be altered and sent to user in plain txt copy
This is my code able to sent plain text file to user with all queryset results but requirement is alignment of results by removing symbols. def save_search(request,q="deve"): filename = "mytext.txt" content =Buildkb.objects.values("text","knowledge","created_by_email"). filter(Q(knowledge__icontains=q)|Q(text__icontains=q)) response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename{0}'.format(filename) return response output:- {'knowledge': 'Deve Category.', 'created_by_email': 'user1@gmail.com', 'text': 'Deve'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realized and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough knowledge on how to choose the SDLC model based on the project context and the business requirement.', 'created_by_email': 'user3@gmail.com', 'text': '1.1'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realised and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough … -
Reducing Django's rendering time
I wanted to render 100 items on the page but it took 14050.60ms. Is there any ways to reduce the rendering time in Django? -
Two fields related in Django
I need to update my table every time a new value of "sku" is entered (not to create a new entry), but it does have to happen only if the "client" selected is the same. If the "client" is different, then the model should add a new object with the same "sku", but with different "clients". I have tried to do the following in my models.py: class ProductList(models.Model): id_new = models.IntegerField(primary_key=True) sku = models.CharField(primary_key=False, max_length=200) client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) class Meta: unique_together = (('sku', 'client'),) But it is not working. How can I make that work? -
Any Database update refreshes React + Django app
I'm currently a beginner with React and I'm currently building a React application that is run on top of Django Framework. My strategy is that I have a single Django template where I attach the whole React application. Basically in my urls.py in Django, I have a list of URLS for all my REST API's and a URL for the single template. I have been stuck with this for quite sometime. There's this weird behavior where any update I do with the database refreshes the website, whether this update is through a form in React (even though I do e.preventDefault()) or doing an update in the Django built-in admin panel page (either Creating, Updating, or Deleting something). I don't exactly know what to share with you (i.e. which part of my code) because I don't even know what the problem is in the first place, but I would be happy to comply to any of your requests. Thank you in advance! -
Read message from django channel while unit testing
I'm writing unit tests for a python method which makes use of Celery worker and Django Channels. Python method @task(name="export_to_caffe", bind=True) def export_caffe_prototxt(self, net, net_name, reply_channel): net = yaml.safe_load(net) if net_name == '': net_name = 'Net' try: prototxt, input_dim = json_to_prototxt(net, net_name) randomId = datetime.now().strftime('%Y%m%d%H%M%S')+randomword(5) with open(BASE_DIR + '/media/' + randomId + '.prototxt', 'w+') as f: f.write(prototxt) Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'success', 'action': 'ExportNet', 'name': randomId + '.prototxt', 'url': '/media/' + randomId + '.prototxt' }) }) except: Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'error', 'action': 'ExportNet', 'error': str(sys.exc_info()[1]) }) }) I have added the python method for which I have to write the tests. So basically what I need to do in unit testing is that I need to open that file which is being generated by the python method export_caffe_prototxt and read the contents of the file and then match it with the desired output. But I'm not able to figure out how do I get that file URL because the method is not returning this URL, it's rather sending a message to the channel so how do I read the message and derive the URL? If someone can write a sample test case for this, it'd be great. Thank you -
How to use VUEJS in Django WITHOUT npm/nodes
I have a huge problem. Please do not judge if it is obvious for you, but I did not develop in JS for years. So here is the context: I have a Django Rest API (which works fine) with Django Rest Framework. The aim of my app is to use VueJS as frontend (and so, execute API Calls). BUT here a constraint: I cannot use npm/node, but only import the scripts in my Django server (in /static obviously) and inport them in the index.html file thanks to the Django template render. Imports works fine, but only these imports (I had to take care to change VueJS delimiter because they are in conflict with Django ones). Anyway, I want to use VuesJS components to store each resource instance and, as my colleague asked me, see/check if we could implement a generic routing (I instantly thought yes with vue-router which was well imported as well). But I have issues while I try to create separate files for the router and the components: I always have import issues. So to ask a concise question: Is it possible to make Django and VueJS work together without node and npm ? And so, can someone … -
Django. Check `unique_together` only if both Model fields were provided for create and update calls
I need to check unique_together only in case both fields were supplied to admin creation Form or via API request for both create and update calls. In case this happens and fields are not unique_together I need to propagate Exception to django-admin creation Form and RestFramework's Serializer/ViewSet. Here's a simplified example of my model: class MyModel(models.Model): time = models.TimeField(null=True, blank=True) date = models.DateField(null=True, blank=True) some_other_field = models.BooleanField(default=False) ... As you can see at the level of model both time and date are not required and are nullable. Application logic on the other hand requires at least one of those fields to be provided and if both are supplied – this pair should be unique for entire table to avoid duplication of datetime composition. This model is accessed through these nodes: django-admin and DjangoRestFramework's endpoint using ViewSet. Creation of new record does not seem to be a problem from API perspective, I can override validate method of Serializer: def validate(self, data): if not data.get('time') and not data.get('date'): raise serializers.ValidationError( "At least one of this fields is required: time, date" ) if OpenTable.objects.filter( time=data.get('time'), date=data.get('date')).exists(): raise serializers.ValidationError('Duplicates for date or datetime not allowed') return data But this becomes a problem when I … -
Post method in angular giving error 406 (Not Acceptable)
I am trying to call post XML data in angular & get posted XML in python(Django) and save it to mongodb, but its giving mi error 406 (Not Acceptable) and detail":"Could not satisfy the request Accept header. In component.ts : let headers = new Headers(); headers.append('Content-Type', 'application/xml'); headers.append('Accept', 'application/xml'); let body = '<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Dont forget me this weekend!</body> </note>'; this.http.post(url, body, { headers: headers }) .subscribe(data => { console.log(data); }); In views.py def post(self, request): original_response = request.data save_response = LenderResponse(lender_response=str(original_response)) return Response(original_response) -
Django: method in view " if ... is '...': " is not working [duplicate]
This question already has an answer here: Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? 14 answers i'm searching for a few days and i can't find any help. I'm new in django and i'm playing around to learn it. My problem is that the users are loggedin but after that, they have to log in with a specific ID to get those contents. For example, me is logged in as bender and now i have to log in with an id to get to more content. I tried to check these ID's in my views. Here's an example: def check_in(request): if request.method=='POST': user_id = request.POST['user_id'] if user_id is '662532': return HttpResponseRedirect("/test/new/content/") else: return HttpResponse("False, there went something wrong.") The error-handling and the HttpResponseRedirect might not be that professional but in this case it returns the else-statement and not the if-statement. If i change the code in if user_id is not "...": it gives me the HttpResponseRedirect commando. What can i do? Thank u guys -
forum on an intranet share drive?
I work for a major company, and in said company, each division has access to their own share drive (lets call it L:). In an ideal world, We would have access to share point or a wiki we could communicate through so we would all know where to find that one f**kn reference file that someone found that one time. But corporate said no, stick to the L: drive. So I want to covertly create a forum or a BBS style app on the L: drive for everyone in my division to communicate and ask questions on. At This point i'm at a loss for what to even look for. I considered a Django web app in standalone mode, but that requires its own server. I considered PHPBB, but again, the server. Sugestions? -
How to add extra validation to Waffle App in Django?
I'm using Waffle App in Django to use FeatureFlags. I'd like to force users to always add a description in the "Note" field, which is by default allowed to be left blank. I think I can do this using a form validation probably creating a clean_note() function, that I should add to the corresponding FormView. Has anyone done something similar before? -
Creating automatic objects in the Database (Django)
i am working on train booking system project and i want to access the seat number and location so i made a seats class that will help. the issue is that i want when the admin adds a new train from the admin panel the seats class automatically adds 100 seat into the DB because i don't think it makes any sense that the admin will add the 100 seat manually -
Django Statics not accessible (Digital Ocean)
I've build a Django site on a Digital Ocean droplet but the static files seem to be inaccessible. Looking around for solutions I've think the problem lies in the server settings (Nginx), but as this is even newer for me I would like to verify this before I mess it up. The CSS is placed within `django_project/static/css', this folder is not accessible using a browser (IPadress/static/css/style.css serves a '404 Not Found' error on the CSS). -
Why use URL parameters over request body in API?
When making an API endpoint in Django Rest Framework for example, why would I ever use URL parameters to receive data rather than just putting everything in the request data? I don't get the difference between the two. -
What is the proper way to design a notification system database?
For example, I have following models class User(models.Model): username = ... avatar = ... class Article(models.Model): user = models.ForeignKey(User) title = ... content = ... class Comment(models.Model): user = models.ForeignKey(User) # 'Comment' or 'Article' target_type = models.CharField() target_id = models.IntegerField() content = ... class Like(models.Model): user = models.ForeignKey(User) # 'Comment' or 'Article' target_type = models.CharField() target_id = models.IntegerField() And the Notification: class Notification(models.Model): actor = models.ForeignKey(User) receiver = models.ForeignKey(User) # 'Comment' or 'Like' or '@' verb = models.CharField() # Where the notification happens source_type = models.CharField() source_id = models.IntegerField() is_read = ... time = ... source_type indicates which table I need to look up and source_id is the id of that object (it might be a Comment or a Like or something else) And I need serialize the notification as below: [ { "actor": { "username": "Yriuns", "avatar": null }, "verb": "Comment", "source": { "pk": 542, "user": { "username": "Yriuns", "avatar": null }, "content": "this is a reply", "time": "2018.11.30 02:38", "target": { "pk": 540, "user": { "username": "Someone", "avatar": null }, "content": "this is a comment" } }, "time": "2018-11-30 02:38:08", "is_read": false }, ... ] The problem is: I don't know the efficient way to query database(MySQL) to …