Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
`python manage.py runserver` will termination in the remote server.
Whether the runserver have time limit? In my remote server virtual environment, I use runserver command to start my development server(by my Mac, my Mac use ssh connected to the remote server) : (venv)$ python3 manage.py runserver 183.97.12.26:8001 and after scores of minutes, it will broken up by itself, if I do not use my Mac(my Mac maybe dormancy). So, how can I make it do not break off. Who can tell me the issue is cause by the command or by the virtualenv? -
How can i use limit offset pagination for viewsets
Views.py class CountryViewSet(viewsets.ViewSet): serializer_class = CountrySerializer pagination_class = LimitOffsetPagination def list(self,request): try: country_data = Country.objects.all() country_serializer = CountrySerializer(country_data,many=True) return Response( data = country_serializer.data, content_type='application/json', ) except Exception as ex: return Response( data={'error': str(ex)}, content_type='application/json', status=status.HTTP_400_BAD_REQUEST ) Settings.py i have added 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', in my urls.py router = routers.DefaultRouter(trailing_slash=False) router.register(r'country', CountryViewSet, base_name='country') urlpatterns = [ url(r'^', include(router.urls)), ] When i try with this url http://192.168.2.66:8001/v1/voucher/country its returning all data. But when i am trying with this url http://192.168.2.66:8001/v1/voucher/country/?limit=2&offset=2 but it is returning 404 error. I am new to django.kindly help me :) -
Nginx. Point two domains to the same location
I have pretty basic nginx configuration which routes all requests to somebot.io to gunicorn server on port 8001. I own another domain some.bot. How to configure nginx to route requests to both domains to the same gunicorn server? I tried to change server_name to server_name somebot.io some.bot; but this didn't help and some.bot responded 400. Should I have separate server block for the second domain? server { listen 443 ssl; server_name somebot.io; ssl_certificate ... ssl_certificate_key ... ... if ($http_host != $server_name) { return 400; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://localhost:8001; } } server { listen 80; server_name somebot.io; return 301 https://$http_host$request_uri; } -
Getting python malloc segmentation fault when start running django runserver after update macOS to High Sierra
I'm struggling to run Django app server in my local. And it does not work since I've updated my macOS to High Sierra from Sierra yesterday morning. I'm using Django 1.10.5 Python 2.7.14 When I run the ./manage.py runserver, it shows the error message like below. Performing system checks... System check identified no issues (0 silenced). python(4381,0x70000269c000) malloc: *** error for object -x7fe76b38a860: Non-aligned pointer being freed (2) *** set a breakpoint in malloc_error_break to debug [1] 4359 abort ./manage.py runserver And I found one issue from here Dynamic library problems with Python and libstdc++ the error message looks quite similar, but couldn't find any similarity so far. -
Precedence in saving in Django Admin with TabularInline
I have 2 models Company and Product. class Company(SEO, MetaData): is_active = models.BooleanField(default=False) class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) is_active = models.BooleanField(default=False) With the following rules: 1) If the Company is_active is False, a Product can't be come active 2) If a Company that active was True becomes False all the Product is_active become False Rule 1, in Product Model: def clean(self): super().clean() if self.is_active: if not self.company.is_active: raise ValidationError( {'is_active': 'The Company need to be checked an validated first'}) return self.is_active Rule 2, in Company Model: (with help from the stackoverflow): def save(self, *args, **kwargs): # if the active state was changed and is False if self.__original_is_active != self.is_active and self.is_active is False: # update does direct changes in database doesn't call save or signals self.products.update(is_active=False) super().save(*args, **kwargs) The issue: I added the Product Model in Company Admin as TabularInline. For Rule 2, when I toggle is_active for Company from True To False and try to save, the Rule1 (ValidationError) appear, and can't be saved. This is strange for me because the update to the product is_active is done before the Company Form is saved, so it should have the previous value. I think that is_active for Product … -
Django Many To Many field with filter
I am trying to add a filter to my ManyToMany field. I have a model User and a model Notification. Notification is connected with User by a ManyToMany field. I want to be able to send a Notification to all users that are for example located in Bulgaria or filter them based on another property in the user model which is not predefined(i.e. The person who creates the Notification does not know pre-creation the filter field). I tried using raw_id_fields for User in Notification admin page. I can then chose and filter Users I want to add based on filters in the Model but I can only choose one user at a time and if I have to add, for example 10k users this can be quite inconvenient. I want to be able to either use raw_id_field and select multiple instances at once, or add some field filtration to filter_horizontal or I don't know. -
How should i implement custom counter of instances with some type?
Here's my model: class MyModel(BaseModel): no = models.PositiveIntegerField() # Human-friendly no -> counter that starts from 1 for every type type = models.ForeignKey(MyModelType) I set the value for the no field in model's pre_save signal: @receiver(pre_save, sender=MyModel) def mymodel_pre_save(sender, instance, *args, **kwargs): if not instance._state.adding: return obj_count = MyModel.objects.filter(type=instance.type).count() instance.no = obj_count + 1 The bug with this code is that it produces different objects having same no number. Probably it happens when multiple users create objects at the same time. What's the best way to fix it? Would moving assignment to .save() method of the model suffice in high-load environment? -
Copy InMemory file to remote server
Is there a way to copy a file in request.FILES to a remote location such as 100.100.1.100/home/dbadmin/EncFiles in Django? I have consulted from this and this questions but I don't need to log on to the server to copy file. I have a simple file in my memory that I need to send to another server. How do I do that? -
how to grab the hour from a timefield - django
I have a model and form with a TimeField and I want to make a change for the hour once the timefield is extracted from the form that was submitted and stored. I want to update the hour in the time. can anyone help me with this... here is the view start_time = cd['start_time'] update_time = start_time update_time.hour = update_hour update_time.save() So the start_time is a timefield that submitted. I want to grab the hour from that start time to change it. how can i do that... -
How to stop Django to create lot of unnecessary tables
I have two databases defined in my setting.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'monitoring', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', }, 'source' :{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'source_db', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '****', } } I need to access some tables in source_db which django is not allowing to do so unless I migrate the db. So, once we run command python manage.py migrate --database=source , Django is creating some tables in server db. Since we are not allowed to create tables in server db, is there any way to stop django doing so? This is the list of tables which we don't want to create. +--------------------------------+ | Tables_in_source_db | +--------------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | dashboard_monitoring_features | | dashboard_monitoring_modelinfo | | dashboard_monitoring_product | | django_admin_log | | django_content_type | | django_migrations | | django_session | +--------------------------------+ -
Django add brackets to django models field
I was trying to add brackets to my django fields how to do it Only with brackets there is syntax error models.py class Customer(models.Model): name = models.CharField(max_length=1000) Region =models.CharField(max_length=1000,choices=Region, default='-') Status =models.CharField(max_length=1000,choices=Option, null=True) APP_SERVER\(Prod\)=models.CharField(max_length=1000,blank=True, null=True) -
Which row is deleted in DISTINCT ON in postgresql
When I use DISTINCT ON in postgresql (distinct in django) which rows are deleted in the group of rows with same fields? -
Easy_install virtualenv/Pip install virtualenv - not working
I am working on the company's server and pip install or easy_install is not working. I am not able to install virtualenv. This is the result for easy_install: PS C:\> easy_install virtualenv Searching for virtualenv Reading https://pypi.python.org/simple/virtualenv/ Download error on https://pypi.python.org/simple/virtualenv/: [Errno 11001] getaddrinfo failed -- Some packages may not be found! Couldn't find index page for 'virtualenv' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [Errno 11001] getaddrinfo failed -- Some packages may not be found! No local packages or working download links found for virtualenv error: Could not find suitable distribution for Requirement.parse('virtualenv') PS C:\> This is what I get when I run the pip install command: PS C:\> pip install virtualenv Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600ED0>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': /simple/virtualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600E10>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': /simple/virtualenv/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600FF0>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': … -
How do I define multiple objects of the same type (django-places placesfield object) in a model in django?
Here's what I mean. I have this model: from places.fields import PlacesField class Lol(models.Model): source = PlacesField() destination = PlacesField() The issue is that whenever I select the source location, the same is selected for the destination and vice versa. What I have tried: I created two extra models to which Lol will be the foreign key, but I don't want to do that. Is there any other solution to this issue? -
Custom javascript to elements of django-summernote widget dont work?
I have some problems with django-summernote application. In toolbar of widget I have button (.btn-fullscreen). I want to change some blocks when user click this button, so I add javascript but unfortunatly it dont work. $(".note-toolbar").on("click", ".btn-fullscreen", function () { // Some code console.log('CLICK'); <!-- Dont work }); $(".btn-fullscreen").click(function(){ // Some code console.log('CLICK'); <!-- Dont work } I notice that this problem happens only when I'm trying to contact with elements of the widget. There is no problems with elements outside of widget. What can be the reason of this strange behavior? This is how I load static files: CSS: <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/codemirror.min.css"> {# Codemirror CSS #} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/theme/monokai.css"> {# Monokai CSS #} <link rel="stylesheet" type="text/css" href="{% static "summernote/summernote.css" %}"> {# Summernote CSS #} <link rel="stylesheet" type="text/css" href="{% static "summernote/django_summernote.css" %}"> {# Django-Summernote CSS #} JS: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/codemirror.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/mode/xml/xml.js"></script> <script src="{% static 'summernote/jquery.ui.widget.js'%}"></script> <script src="{% static 'summernote/jquery.iframe-transport.js'%}"></script> <script src="{% static 'summernote/jquery.fileupload.js'%}"></script> <script src="{% static 'summernote/summernote.min.js'%}"></script> <script src="{% static 'summernote/ResizeSensor.js'%}"></script> <script type="text/javascript"> $(".note-toolbar").on("click", ".btn-fullscreen", function () { // Some code }); $(".btn-fullscreen").click(function(){ // Some code } </script> -
I'm unableto install django
enter image description here I tried install the django by using regular commands.but it is not installing -
Django python manage.py runserver giving exception Datafile not found, datafile generation failed
After upgrading one of my packages (django-registration), I received this error while trying to run python manage.py runserver The output was as I have shown below. I thought that python3.5/site-packages/confusable_homoglyphs/categories.py might be missing and I re installed the package confusable_homoglyphs , but to no avail .It threw the same error Also after that, a file name =3.0.0.txt was created inside my project folder which had this written below Requirement already satisfied: confusable_homoglyphs in ./myvenv/lib/python3.5/site-packages I tried to remove the package and add that package (even inside n outside my virtual env). But it threw the same error as below. (myvenv) shubhendu@shubhendu-HP-Pavilion-g6-Notebook-PC:/home/foodballbear$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f320538d400> Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 141, in <module> categories_data = load('categories.json') File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 33, in load with open('{}/{}'.format(os.getcwd(), filename), 'r') as file: FileNotFoundError: [Errno 2] No such file or directory: '/home/foodballbear/categories.json' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 144, in <module> if generate(): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 111, in generate file = get(url) File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 24, in get return urlopen(url).read().decode('utf-8').split('\n') File "/usr/lib/python3.5/http/client.py", line 461, in read s = self._safe_read(self.length) … -
What is require knowledge and practice to develop MVC applications
I am trying to develop MVC application with php but I am not able to understand how to start with database development. Do I need to develop database first approach or other? -
Blockchain API Error: Wallet Password incorrect [And It's correct]
I want to work with blockchain api in my django web app. After installing the blockchain-service module and starting the server, I input the right wallet password and I'm getting error: main wallet password incorrect The endpoint http://localhost:3000/merchant/d536-46464-9575756-38474646/enableHD?password=pooo Versions: Nodejs: 8.9.1 npm: 5.5.1 wallet-service: 0.26.0 Could this be a bug with blockchain module or what am I missing? -
Django automatically converting datetime stirng to local timezone
I am adding timestamp in my payload and storing it in the database for every record. Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}] This is how I process it. content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True) My model has timestamp field as : timestamp = models.DateTimeField(null=True) When I check in my database it stores timestamp field as : 2017-12-12 13:35:30 Which should be stored as it is as per my requirement. 2017-12-12 08:05:30 i.e it stores the timestamp field + my local timezone(+5:30) hours. I want it to store the timestamp field as it is. I tried other posts where they suggest using del os.environ['TZ']. Any help is appreciated. -
Django form with checkbox is always False
I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template- <form action="annotate_page" method="post">{% csrf_token %} <input id="repeat" type="checkbox" > <label for="repeat">Repeat Sentence?</label> <br> <button type="submit">Next</button><br> </form> Here is my forms.py- from django import forms class AnnotateForm(forms.Form): repeat=forms.BooleanField(required=False) Here is my views logic- if request.method=="POST": form = AnnotateForm(request.POST) if form.is_valid(): print(request.POST)#prints only csrf_token in Query_dict print(form.cleaned_data["repeat"])#Always false Irrespective of weather the checkbox is checked or not,the print statement always gives False. I know there are questions similar,but they don't solve my problem. -
'User' object has no attribute 'student_set'
class BasicInfo(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=250) class Student(Basicinfo): ... When I query : user=user.objects.get(user="name") student=Student.objects.get(username=user) But : user.student_set.all() gives error 'User' object has no attribute 'student_set'?? -
Python Django Model inheritance and display form by selected subclass type which are populated to the dropdown list
I'm beginner on django. I want to make a form which will be dynamic. I wrote a code like below but could not work it properly. models.py class Parca(models.Model): parcaAdi = models.CharField(max_length=200) parcaFiyati = models.IntegerField() iscilikUcreti = models.PositiveIntegerField() def __str__(self): return self.parcaAdi class Kaporta(Parca): boyananParca = models.CharField(max_length=100, default="") boyamaUcreti = models.PositiveIntegerField(default=0) def __str__(self): return self.parcaAdi + "\t" + self.boyananParca class Motor(Parca): pass class Elektrik(Parca): pass forms.py class ParcaForm(forms.ModelForm): class Meta: model = Parca fields = ( 'parcaAdi', 'parcaFiyati', 'iscilikUcreti', ) # sub-classes class KaportaForm(ParcaForm): class Meta(ParcaForm.Meta): model = Kaporta fields = ParcaForm.Meta.fields + ('boyananParca', 'boyamaUcreti') class MotorForm(ParcaForm): class Meta(ParcaForm.Meta): model = Motor class ElektrikForm(ParcaForm): class Meta(ParcaForm.Meta): model = Elektrik As you can see 'KaportaForm' will get extra fileds. myhtml file <form method="post"> {% csrf_token %} <table class="tablo_parca"> {{ form }} </table> <br/> <input class="submit" type="submit" value="Kaydet"/> </form> <br/> <br/> <label style="margin-left:10px;"><b>Parça Türü : </b></label> <select class="dropdown" id="dropdown" name='parcaAdi'> <option value="">Parça Türü</option> <option value="kaporta">Kaporta</option> <option value="motor">Motor</option> <option value="elektrik">Elektrik</option> </select> my ajax file: $(document).ready(function(){ $('#dropdown').on('change',function(e){ e.preventDefault(); var parca_turu = $(this).val(); console.log("Secilen: "+parca_turu); $.ajax({ url:"", method:'GET', data : {'parcaAdi' : $(this).val()}, success:function(gelen_parca_turu){ //console.log(gelen_parca_turu); } }); }); }); and my views.py def parca_kayit(request): if request.method == 'GET' and request.is_ajax(): parca_turu = request.GET.get('parcaAdi') print(parca_turu) if … -
Celery ImportError: No module named tasks while running celery process
I am trying to run a celery process using the command: /opt/vso/orchestration/uat/bin/celery -A tasks worker --loglevel=debug --config=/opt/vso/orchestration/config/celeryconfig.py However, I am getting error ImportError: No module named tasks File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/bin/base.py", line 311, in find_app sym = self.symbol_by_name(app) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/bin/base.py", line 322, in symbol_by_name return symbol_by_name(name, imp=import_from_cwd) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/kombu/utils/__init__.py", line 80, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/utils/imports.py", line 99, in import_from_cwd return imp(module, package=package) File "/opt/vso/software/py275/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named tasks -
Best practice working with python variables in javascript django
I am currently access my python data in javascript like this: <script> var x = {{x|safe}}; var l = {{ l|safe }}; var sf ={{ sf|safe }} </script> this works but does not seem like the most ideal to transfer data. What is the best practice for accessing and saving data between python and javascript using django? What I am trying to do is send data from the view, manipulate using the ui and javascript/vue.js and then save the data calculated in javascript.