Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using IS NULL in PyMongo
I am trying to do an 'd': None in my pymongo query. But when I do None. I am not getting any results. My SQL: SELECT date, a, vt, b, c, d ,SUM(theSum) AS theSum FROM table where date between '2019-07-08' and '2019-08-08' AND a in ( 'abc', 'xyz') AND c IN ('qwe') AND b IS NOT NULL AND (d IN ('yo') OR d IS NULL) group by 1,2,3,4,5,6 order by theSum DESC LIMIT 25 PyMongo: {'$match': { '$and': [{ 'date': { '$gte': sd, '$lte': ed }, 'a': { '$in': a }, 'b': {'$ne': None}, 'c': { '$in': c }, }, { '$or': [{ 'd': {'$in': d} }, {'d': None }] }] } } { '$group': { '_id': { 'a': '$a', 'vt': '$vt', 'b': '$b', 'c': '$c', 'd': '$d' }, 'theSum':{ '$sum': '$theSum' } } }, { '$project': { '_id': 0, 'a':'$_id.a', 'vt': '$_id.vt', 'b': '$_id.b', 'c': '$_id.c', 'd': '$_id.d', 'theSum': '$theSum' } }, { '$sort': { 'theSum': -1 } }, { '$limit': 25 } ]) I get 43 records when I query in SQL but 0 when I query the pymongo code. What am I doing wrong in pymongo. -
How to use django's ORM as a stand alone package in AWS lambda?
For starters, I have tried the following posts & they did not help. Using Django ORM Inside AWL Lambda Using Only The Db Part Of Django Django Stand Alone Docs Following the django docs and using pieces of the above links I created the following standalone script to use django's ORM. import django from django.conf import settings def configure(): settings.configure(DEBUG=False, DATABASES={ # TODO: Change this to environment variables 'default': { "ENGINE": "django.db.backends.mysql", "NAME": "db_name", "HOST": "db_host", "USER": "admin", "PASSWORD": "db_pass" } }, INSTALLED_APPS=['my_models'] ) django.setup() In my handler.py file with my registerUser lambda functions from .django_orm.main import configure configure() from .django_orm.my_models import AppUser def registerUser(event, context): #Application Logic newUser = AppUser() newUser.save() return True When I run this I get the following error ... File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'my_models' My directory structure is the following: ./myServerlessProject ./djangoORM ./main.py ./manage.py ./my_models ./__init__.py ./models.py ./handler.py ./serverless.yml What am I doing wrong and how do I get the django ORM to be stand-alone? -
Error : type object 'Inventory' has no attribute 'objects'
I created a model and used random generator for it. Thus, I had to use UserManager for that model. Wen I am using this model in views, I am getting the above error. I have done this multiple times and never got an error. I don't know what is wrong. Please help. Thanks in advance! models def unique_rand(): while True: code = Inventory.objects.make_random_password(length=6, allowed_chars="1234567890") if not Inventory.objects.filter(code=code).exists(): return code class Inventory(models.Model): premises = models.ForeignKey(Premises, on_delete = None) item = models.CharField(max_length=255,blank=False,unique=True) code = models.CharField(max_length=255, null=True, blank=True,default = unique_rand) quantity = models.IntegerField(null = True, blank=True) is_defected = models.BooleanField(default = False) objects = UserManager() def __str__(self): return self.item views class Inventory(ListView): model = Inventory template_name = 'inventory.html' def get_queryset(self): pre = Premises.objects.get(userprofile__user = self.request.user) queryset = Inventory.objects.filter(premises = pre) return queryset I have already imported models and Usermanager. -
Whats the different between override the update method inside view and inside serializers?
I am new in django i know this is a naive question but im so confused about when exactly do we have to override update method located in view and when do we have to override update method located in serializer? -
How can i filter data retrieved from a Django Rest Framework endpoint
I have some data on a MongoDB database, it looks like this, where i have more records all looking like the following document: {"data":[{"one":"[[1756.53, 2.419583], [13755.95, 0.056274], [1755.62, 0.027065], [11755.59, 0.085065], [1175.28, 906], [11752.33, 0.333531], [11752.31, 0.5], [11752.03, 0.6], [11752.02, 0.107656], [1751.99, 1.288268], .... }], {"item: "one"} Those records are fetched from a DRF api endpoint: http://127.0.0.1:8000/market/myapi/ And then they are rendered into my template on a DataTable using an AJAX call: $(document).ready(function() { var table = $('#mytable').DataTable({ "ajax": { "type" : "GET", "url" : "/myapi/?format=datatables", "dataSrc": function(json) { return JSON.parse(json.data[0].one); } }, "columns": [ {"data":0, "title":"DATA"}, ] }); }); The problem with my actual code is that there are a lot of documents into the DB, and i don't want to display on my table all of them, just a certain one. For example, if the slug of my Django page is one, and i'm on http://127.0.0.1:8000/pages/one/, i need to retrieve the data of the record one. Here is how i figured it out, but i don't really know how to do it in terms of code. Should i do edit my AJAX call or is there a way to do it straight in Django? Any advice is appreciated -
nginx is trying to host my media files from the wrong location? How can I fix this?
I have created a django app and I am using digitalocean to host the site. I have a media directory. I have installed nginx. I have configured nginx to get my media files from match my server file list. -For some strange reason, nginx is changing the media file directory and trying to get files from the wrong location. I can not figure out how to change the nginx configuration to get media files from the correct location. -File serving works perfectly fine on my development box using localhost. As soon as I push the code to digitalocean with gunicorn and nginx, the media hosting directory magically changes. I am trying to find out if nginx has a secret configuration file? I have gone through all of the configurations on the Django settings.py and urls.py files to make sure they are pointing to the right directions. I have gone through my server files and my nginx configuration to make sure they are pointing to the right places. On the Django development side: -I have edited the settings.py to set the MEDIA_ROOT and MEDIA_URL: (My reputation isn't high enough for photos) -Django Settings.py -I have edited the URLS.py: -urls.py -On my … -
Cannot assign SimpleLazyObject in my code
I want to insert 'FineModel' data on 'ODE_Marks_Model' inserting time. model.py class ODE_Registation_Model(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) subject = models.ForeignKey(SubjectMaster,on_delete=models.CASCADE) ode = models.ForeignKey(ODE_List_Model,on_delete = models.CASCADE,verbose_name="which ode") exam_date = models.DateField() registration_date = models.DateField() class ODE_Marks_Model(models.Model): ode_registered = models.OneToOneField(ODE_Registation_Model,on_delete=models.CASCADE) marks = models.SmallIntegerField() verified_by = models.ForeignKey(User,on_delete=models.CASCADE) class FineModel(models.Model): fine = models.IntegerField() user = models.ForeignKey(ODE_Registation_Model,on_delete=models.CASCADE) admin.py @admin.register(ODE_Marks_Model) class ODE_Marks_Admin(admin.ModelAdmin): list_display = ('ode_registered','marks','verified_by') exclude = ['verified_by',] def save_model(self, request, obj, form, change): instance = form.save(commit=False) if instance.marks == -1: fine = FineModel.objects.create(user=request.user,fine=50) fine.save() instance.verified_by = request.user instance.save() return instance I expect the output to save FineModel object in save_model but, I got the error : ValueError at /admin/core/ode_marks_model/add/ Cannot assign ">": "FineModel.user" must be a "ODE_Registation_Model" instance. -
Django 'int' object has no attribute 'resolve_expression'
I tried to get profit here, but it gives me this error: 'int' object has no attribute 'resolve_expression' This is what I tried: def get_trades_queryset(self): trades = self.get_trades() print(trades) trades_sell = self.get_trades_sell() trades_buy = self.get_trades_buy() if trades_sell: traded_price_sell = trades_sell[0] print(traded_price_sell) traded_share_sell = trades_sell[1] else: traded_price_sell = 0 traded_share_sell = 0 print(traded_share_sell) if trades_buy: traded_price_buy = trades_buy[0] traded_share_buy = trades_buy[1] else: traded_price_buy = 0 traded_share_buy = 0 formula = traded_price_sell * traded_share_sell - traded_price_buy * traded_share_buy r = trades.annotate(traded_price_sell=traded_price_sell, traded_price_buy=traded_price_buy, traded_share_buy=traded_share_buy, traded_share_sell=traded_share_sell, profit=ExpressionWrapper(formula, output_field=models.CurrencyField()), ) return r I am very new to python. Should I use ExpressionWrapper only when I have F() expression? Because the QuerySet (trades, trades_sell and trades_buy are QuerySet here) initially is empty, so it gives 0 to formula here. I also tried profit = c(formula) which gives similar results. How can I fix it? Any help is appreciated. -
Django ListView: filter history based on chosen user
I've got a History ListView in which I'd like to let my Users filter the Historyitems based on which User they picked in the ModelChoiceFields I'm providing them My History View looks like this: class HistoryItems(ListView): model = HistoryItem template_name = 'history/history_table.html' context_object_name = 'history_items' def get_context_data(self, **kwargs): user_id = kwargs.get('user_id') query = {} if user_id: user = get_object_or_404(User, pk=user_id) query['changed_by'] = user else: user = None history_items = HistoryItem.objects.filter(**query).select_related('changed_by', 'content_type') return { 'filter_history_form': HistoryFilterForm(user_id=user_id), 'history_items': history_items, } It returns me the correct History items in a big table (see html below). And then I've got this form: class HistoryFilterForm(forms.Form): normal_user = forms.ModelChoiceField(User.objects.filter(special=None), label="Normal Users", empty_label="All normal users") special_user = forms.ModelChoiceField(User.objects.exclude(special=None), label="Special User", empty_label="All special users") def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') super(HistoryFilterForm, self).__init__(*args, **kwargs) self.fields['normal_user'].initial = user_id self.fields['special_user'].initial = user_id self.helper = FormHelper() self.helper.label_class = 'sr-only' self.helper.add_layout(Layout( Row( Div('normal_user', css_class='col-sm-3'), Div('special_user', css_class='col-sm-3'), ) )) This form simply creates two ModelChoiceFields of the same User object, just that one field shows all "normal" users and the other all "special users" My Urls looks lime this: urls = [ path('', views.HistoryItems.as_view(), name='history_index'), path('u=<int:pk>', views.HistoryItems.as_view(), name='history_index'), ] I figured that I would need to refresh my page all the time when … -
How to use django and mysql?
I want to use django with mysql but it alwyase give me error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. so I tried to download with pip install mysqlclient but it gived me error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ And when I tried to download visual studio it dosen't work,I'm using windows 7 32 bits,I tried it give the windows that it's downloading but it always suddenly stop and it doesn't download So I want to know if there is any visual studio for windows 7 or can I install the C++ package directly without installing visual studio -
How to equip a django html extension / Template extending with a view?
i want a Searchfield in in my Navigation Bar. The navigation bar is integrated via {% include 'includes/navbar.html' %} in the base.html. I use a SearchForm for the Searchfield and it is displayed well on my landingpage home.html If i start the Server the it looks like this: However the Forrm() is only displayed because it is in my myapp / view.py for my landingpage. def home(request): form = SearchForm() ... return render(request, 'home.html', context) So if i click on Company, no form will show up because it´s not in my view. But i don´t want to render on every single view or Page the SearchForm() because the navbar.html is an extension loaded in my base.html and will be always shown. So for every new page i have to include the form in the navbar: def newpage(request): form = SearchForm() ... return render(request, 'company / newpage.html', context) The Question is how to equip the navbar.html with a SearchForm()? It´s not an app with it´s own views, it´s just a template. Maybe is should write a own Navbar app? myapp ├── myapp │ └── views.py ├── media ├── static ├── templates │ ├── includes │ │ └── navbar.html │ ├── base.html … -
Static Files issue between local environment and aws
When deploying to AWS, I am having issues getting static files to load from different apps, also the admin styling is lost in AWS. Below what I list for locally is how it was working previously, then below that are the changes I made to get it to work in aws, though now some of the .css files are loading empty on my local environment when running it as it should be for AWS. Also if I try and leave STATICFILES_DIRS and have STATIC_ROOT, I get an error. When running locally I need settings.py to contain: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "Reporting/static/Reporting"), os.path.join(BASE_DIR, "Organization/static/Organization") ] When running in aws I need Settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "static") # ADDED for AWS STATIC_URL = '/static/' ebextentions: 02_collectstatic: command: "python manage.py collectstatic --noinput" leader_only: true Any assistance will be greatly appreciated. -
Django migration - seed database while defining model
I'm on Django 2.1 and am trying to create a db table with seeded/default values in one go. Django has good documentation on how to do a 'data migration' - https://docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations - This could be used to add the data I need to the table. I could do two migrations: 1) Regular migration Defines the model/table and 2) Data migration populates the data. Right now, I have to do it in two steps because the table doesn't exist until after the first migration has completed. Is there any way to do it in one shot? -
Docker-compose build give error during mysql setup
I was trying to dockerize my existing django project, I read a lot of blogs about it, I was taking a reference of https://medium.com/@minghz42/docker-setup-for-django-on-mysql-1f063c9d16a0. my docker-compose.yml version: '3' services: db: image: mysql:5.6.45 ports: - '3306:3306' environment: MYSQL_DATABASE: 'new11_uat' MYSQL_USER: 'rootd' MYSQL_PASSWORD: 'AKSHATGUPTa' MYSQL_ROOT_PASSWORD: 'AKSHATGUPTa' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3.5-alpine RUN apk add --update \ build-base \ gcc \ libc-dev \ libxml2-dev \ libxslt-dev \ mysql-dev \ musl-dev \ linux-headers \ mariadb-dev \ pcre-dev \ mysql \ mysql-client \ python3 \ python3-dev \ py-pip \ && rm -rf /var/cache/apk/* RUN pip install mysqlclient RUN mkdir /code WORKDIR /code COPY requirements_all.txt /code/ RUN pip install --no-cache-dir -r requirements_all.txt COPY . /code/ settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': 'db', 'PORT': 3306, 'OPTIONS' : { "init_command": "SET foreign_key_checks = 0;", }, } } But when I tried sudo docker-compose up, somehow there is a problem in mysql setup, I already tried to change the version of mysql but same problem db_1 | Initializing database db_1 | 2019-08-07 16:29:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp … -
How to filter cascading errors from Django log?
I am using django-pipeline to package static assets in my Django project. Currently there is a bug in django-pipeline that causes lots of VariableDoesNotExist errors. When this occurs, you will see a set of cascading errors in Django's default.log file like the following: [05/Aug/2019 23:18:24] DEBUG [django.template:925] Exception while resolving variable 'media' in template 'pipeline/css.html'. Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/context.py", line 87, in __getitem__ raise KeyError(key) KeyError: 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 888, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'Context' has no attribute 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'media' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/https/example.com/venvs/1d91509e90bdc90520749a9ade72dbcc9dd16f27/lib/python3.5/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [media] in "[{'False': False, 'None': None, 'True': True}, {'url': 'https://fs00.example.com/static/css/example.479c98677380.css', 'type': 'text/css'}]" Is there any way to filter out these errors such that when the … -
how to pass attr to forms.CharField
I want to pass some Html attr to a form field generated by crispy I try to this code in django 2.2.3 class AddForm(forms.Form): todo = forms.CharField(max_length=128, attrs={'placeholder':'What do you want to do?'}) but I got an error from .forms import AddForm File "C:\Users\HP\django_project\todo\forms.py", line 4, in <module> class AddForm(forms.Form): File "C:\Users\HP\django_project\todo\forms.py", line 5, in AddForm todo = forms.CharField(max_length=128, attrs={'placeholder':'What do you want to do?'}) File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\fields.py", line 214, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'attrs' -
Creating a Rest API to search particular item over list of items
I have a list of medicine stored in the SQL database. And I want to create an API using Django REST Framework that could return a medicine that matches my search else return the entire medicine list. I do not want to make a GET request with a search query parameter but a POST request with medicine name as the key. Kindly suggest a way to do it? -
python django pass post request data into dictionary
There is a POST request that sends data to django. python 3.7 if request.method=="POST": print(request.data) this prints out <QueryDict: {'file_id': ['2019_08_07_12_17_44.943792.csv'], 'HouseNumber': [''], 'Street': ['Address'], 'Borough': ['Boro'], 'ZipCode': ['Zip']}> for this file submission. I need to turn this querydict into a python dictionary. How do I accomplish this? -
How do I modify the web I deployed?
I finished my django project and deployed on digital ocean. (Followed a youtube video blindly) my question is how do I modify the web now? what I thought was make change on my local and do git push then on my ssh do git pull. is it this easy? what happened to db then? I'm using postgresql. am I doing it wrong? -
Html form on submit doesnot redirect to url in form action
It is a really simple thing. I am not sure why it is not working. So basically an html form which has a get attribute should redirect me to the url specified in the action = 'url'. But when I submit the form in my browser, instead of redirecting me to http://127.0.0.1:8000/blog/articles the browser stays on the home page. So after submitting, I should be on the page http://127.0.0.1:8000/blog/articles?q=tesla. Instead I stay on the page http://127.0.0.1:8000/q=tesla. I have already tried many alternatives such as replacing the django templating {% url %} tag with the actual url value 'http://127.0.0.1:8000/blog/articles'. None of these work. Is there something wrong with Django and html submit forms? <form action="{% url 'blog-articles' %}" method='GET'> <input class="search_input" type="text" name="q" placeholder="Search..." id ='textBoxSearch'/> <button type="submit" class="search_icon fabutton" id = 'btnSearch' value="Register"><i class="fas fa-search"></i></button> </form> Expected:http://127.0.0.1:8000/blog/articles?q=tesla Actual:http://127.0.0.1:8000/q=tesla -
Django management command does not show logs of my library
This question is a simpler version of this 4 years old question without answer Django management command doesn't show logging output from python library: I have a command: class Command(BaseCommand): def handle(self, *args, **options): ... MyParser(data) And in MyParser: logger = logging.getLogger(__name__) Class MyParser: def __init__(self, data): logger.info('hello') Why the logger does not display to stdout when I run the command? With a print it is OK but I need a logger PS: I tried this but it does not change anything from parser import logger root_logger = logger root_logger.setLevel(logging.INFO) MyParser(data) -
Creating a django api to read a file content and display on Angular frontend
I need to create a django api which will read the contents of a file and display it on the angular frontend all in a bash script This is on a centos7 machine and the file to be read is on a different centos 7 machine I expect the contents of that file to be displayed on the Angular Frontend -
I cant migrate and run my server successfully in django
I am getting an error whenever i want to migrate and run my server in django. File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) -
Django rest api to handle csv data
I am relatively new to Django and DRF, however I have managed to implement DRF and its working successfully with the default json content negotiation. Now I have been given a task where the api will receive some telemetry data in csv format without headers. The headers shall be hard coded as it won't change. Example, ads123,0,12.5,0,1,23,abcd Now I need to develop a rest api that can accept csv data, save it in a postgres/sqlite db and return the response in csv. I have searched the net have been unable to find a suitable solution. I found djangorestframework_csv but then i believe it needs a header in its csv data from what I saw. Kindly suggest if possible with an example. -
Data migration to replace instances of a word in a TextField?
I am writing a data migration to go through some general templates used to send notifications with the goal of changing all instances of 'word1' to 'word2'. 'word1' can occur in both the name of the template as well as the body. Currently, there is only one template with 'word1' in the name, so I am able to change that one easily with an if statement that grabs that exact name and replaces it with the desired name. The issue I am running into is swapping 'word1' with 'word2' when it appears in the body of a template. An additional note to make is that the occurrences of 'word1' in the body are independent entirely from the occurrences in the name. So far, I've tried using an if statement with a_notification.body.contains('word1') in my for loop to find which notifications contain that word. I've also tried splitting up the body into a list of words, splitting the textfield by space characters, and then using a for loop to check each individual word to see if it is equal to 'word1'. Currently, I am trying to use .replace() to find the instance and replace it with the desired word. Migration file: #Generated …