Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to bypass manage.py in django? [duplicate]
This question already has an answer here: How to do database migration using python script? 1 answer I am following django tutorial at: https://docs.djangoproject.com/en/1.10/intro/tutorial02/ The page says: Bypassing manage.py If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable to mysite.settings, start a plain Python shell, and set up Django: >>> import django >>> django.setup() If this raises an AttributeError, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version. You must run python from the same directory manage.py is in, or ensure that directory is on the Python path, so that import mysite works. For more information on all of this, see the django-admin documentation. the resulting django-admin documentation is also silent how you can bypass the python admin.py My question is How to bypass the shell commands and do the python manage.py from python file itself. related question: How to do database migration using python script? -
Django ForeignKey to textfiled
I have one foreign key class Task(models.Model): task_relates = models.ForeignKey('Task',on_delete=models.SET_NULL) I am getting choice filed when I paint this on form but I want input from the user as in textfield and then manually I will check it to the id. how to print the same filed as textfield in form? I tried this task_relates = forms.CharField(max_length=30, required=False) -
M2M relationships to self with attribute.
I want to create cross selling product: class Product(models.Model): name = models.CharField(max_length=150, blank=True, default='') ... class CrossSellingProduct(models.Model) parent_product = models.ForeignKey(Product, related_name='cross_sellings') associate_product = models.ForeingKey(Product) double_sided = models.BooleanField(default=1) I want to call function cross_selling_products on product instance and see all products which are associated. If double_sided is True I can see associated product in bouth way, if False only parent -> associated_products. Is some smart way to implement this? Thank you. -
Django Error for property
We are to trying to run the below code however we are getting an error Exception Type: NoSectionError Exception Value: No section: 'credentials' can someone help me out please import configparser def populate_skillgroup(request): print("djangoo app") config = configparser.RawConfigParser() config.read('Supervisor.properties') user_name = config.get('credentials', 'db_credentials.user_name') password = config.get('credentials', 'db_credentials.password') db_name = config.get('credentials', 'db_credentials.database_name') -
Session api on django
I need to implement using api such behavior: App opening without registration If it's new user, then send signup request, and get new session If there is a session, then check it. So I think I need /signup method which creates session and returns a session token. And /check method which gets a token and returns check result. Could you please help me with implementing that? I'm new at Django. And I want to use Tastypie for api. -
pymssql INSERT won't auto increment ID
I am using pymssql in my django project to connect to a database. I'm trying to use execute() method to do an insert. However I get this error: Cannot insert the value NULL into column 'ID', table ITEMS the ID column is primary key and so it should be filled by the sql itself as I understand. here is my insert command: bill_id = execute(""" INSERT INTO ITEMS(COlUMN1,COlUMN2, COlUMN3,COlUMN4,COlUMN5) VALUES (%d, %d, %d, %d, %d); """, (1713, 6, 929, 1184, 25)) and none of these COLUMNs are ID. can anyone tell me what am doing wrong? -
Can not parse the remainder: '==0' from 'data.tab_nid==0'
I my template, I want to give a class active: <li>{% if data.tab_nid==0 %} class="active" {% endif %} </li> But when I run the page I get the bellow error: TemplateSyntaxError: Could not parse the remainder: '==0' from 'data.tab_nid==0' -
Chrome does not stream content from Django's StreamingHttpResponse
A year ago, I used Django's StreamingHttpResponse to stream a text file and Chrome immediately displayed every trunk of text that it received. Now, with the same code, Chrome only displays the text when it completely loads the text file, thus risks server timeout. This does not happen with Firefox. I created a simple test: # views.py import time from django.views import generic class TestEditView(generic.TemplateView): def generator(self): for _ in range(15): time.sleep(1) yield 'THIS IS {}\n'.format(_) print('LOG: THIS IS {}\n'.format(_)) def get(self, request, *args, **kwargs): return StreamingHttpResponse(self.generator(), content_type="text/plain; charset=utf-8") If I access that view in Firefox, that browser will print out 'THIS IS ....' each second for 15 seconds. But in Chrome, the browser will wait 15 seconds, then print out all of the 'THIS IS...', even though the development server log 'LOG: THIS IS...' once a second. I wonder if there is any subtlety in this problem that I missed. Thank you. Python: 3.6.2, django: 1.10.5 -
duplicate key value violates unique constraint itemstaticlabel_item_id_f9405967_uniq
I know, this problem happens because the code is trying to add an entry to the database with a combination of unique keys that already exist. But my question is: why and how can I prevent this? It doesn't make sense to me that this is happening, given my logic. I have this piece of code that basically stores some static label for an invoice. The idea is to create the label on the fly if it doesn't exist, instead of manually inserting it in a lot of places in the code. Whenever an Item is generated, an ItemInv is also created, and by saving the latter, I check if a static label exists. If it doesn't, a new one is created. The code to get (or create) the static label is also called when displaying an Invoice / Draft. The error seems to happen right there. The label doesn't exist, a new one is created, but somehow this happens twice? I mean, I really don't get why that code would try to add the same item two times. Could it be a thread issue? I am not using get_or_create because some attributes on ItemStaticInv (static_account_label, static_agreement_label...) can be updated … -
Create sql schema from django models or migrations
I created different models with django 1.8. Now, to enable other people to have a quickly comprehension, I would create a sql schema from the models or from the migration files (even only from the initial migration file). Someone knows how does it? -
Return Python Django model as a json object
I am trying to return an object created from a Django model as JSON to the rest framework after being created. I have tried many ways but they all don't seem to work. Here is my code; router.register(r'amazon/products/import/(?P<id>[-\w\d]+)', amazon_views.AmazonImportProductViewSet, base_name='import-amazon-product') ...routing to... class AmazonImportProductViewSet(viewsets.ViewSet): def list(self, request, id=None): product = simple_amazon.lookup(ItemId=id, ResponseGroup='ItemAttributes,Offers,Images,EditorialReview,Reviews') brand = get_object_or_404(AmazonBrand, name="microsoft") createdProduct = AmazonProduct.objects.create(title=product.title, brand=brand) #json_p = serializers.serialize("json", createdProduct) serializer = AmazonProductSerializer(createdProduct) return Response({'success': "true", 'message':'Imported successfully!', 'product':serializer.data}) I am trying to return just 1 object with it's OneToMany relationships. For example I would like brand returned as well. -
Angular 2 with Django
I am struggling to find a good tutorial or documentation that covers the integration of Django and Angular 2+. It is easy to find documentation for each individually but cannot find something suitable which takes you through both at the same time. For other languages such as C# there are many books on ASP.Net and Angular 2+ together. I find it strange as to why there is no documentation for Django (in Python). Does anyone know where I can learn how to connect these two popular technologies? -
Django - write model contents to new file
I have a Django model, and I want, when the user clicks on submit, the model not only saves the data in the database, but also writes them in a new file in this format: (structid,name,pos,long,type). I am new to Django and I am doing my internship in it. -
Django: HTTP status 400 response rolls back model save?
I have an API endpoint to trigger a payment request to a third party. The endpoint is called with some data in a POST request and goes something like the code below. Somehow when the payment request failed (payment.is_successful = False), no data was ever saved to the database, although the debug log showed SQL INSERTs being made, and no error was thrown. The data was just dropped silently. I figured that if I changed HTTP_400_BAD_REQUEST to HTTP_200_OK then my data is saved. Why is this happening (and where is the code responsible for it)? Is there a way to prevent it from happening (I want my data in the db for this view, no matter what) with some setting in Django/DRF? I've temporarily set the return code to 200, but it feels wrong as the request actually failed. What code would make more sense, that doesn't cause the data to disappear? view code ser = MySerializer(data=request.data) if ser.is_valid(): payment = ser.save() else: # do some non database stuff return Response(result, status=status.HTTP_400_BAD_REQUEST) if payment.is_successful: # some more processing return Response({'success': True}, status=status.HTTP_201_CREATED) else: return Response({'success': False}, status=status.HTTP_400_BAD_REQUEST) ## THIS LINE ## serializer code class MySerializer(serializers.ModelSerializer): def create(...): # call payment … -
Django <object> is not JSON serializable
I am using https://github.com/coderholic/django-cities and i wanted to add city and country to my serializer. This is my model: from cities.models import Country, City class Location(models.Model): name = models.CharField(max_length=200, blank=True, null=True, default=None) city = models.ForeignKey(City, blank=True, null=True, default=None, related_name='city_of_location') geolocation = map_fields.GeoLocationField(max_length=100, blank=True, default='') My views: class LocationsView(generics.ListAPIView): queryset = Location.objects.order_by('-id') serializer_class = LocationsSerializer serializers.py class LocationsSerializer(serializers.ModelSerializer): number_of_rooms = serializers.SerializerMethodField() country = serializers.ReadOnlyField(source='city.country') class Meta: model = Location fields = ['id', 'name', 'geolocation', 'city', 'country'] When i'm trying to see if it works i'm getting: <Country: Austria> is not JSON serializable -
my django can't generate models from oracle database
I am building django project upon oracle database, after i set my database in django settings, i use command python manage.py inspectdb to generate oracle tables, but there is an error: > Unicode DecodeError: 'utf-8 codec can't decode bytes in position > 82-83:invalid continuation byte what can i do ? the oracle is not install in my local pc. i tried to set local env path:NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK, it doesn't work. Thank you for your help! -
How to use request.META.HTTP_HOST inside Django models?
I'm trying to improve my app's SEO by having absolute URLs to my links (link for each world city). I managed to do so in the template by doing this: <a title="{{city.name}}" href="http://{{ request.META.HTTP_HOST }}/{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> However I'm trying to implement the same from the model in a way that I can simply do this: <a title="{{city.name}}" href="{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> This is my attempt: def get_absolute_url(self): return "http://" + self.request.META.HTTP_HOST + '/city/%s/' % self.slug But I get this: name 'request' is not defined How can I import the user request to use in a model? -
ajax is not working with django
i am creating a form that add a comment to a post, it is working without ajax, because ajax send the form data as None. the ajax: <script> $(function() { $("#myform").on("submit", function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: 'POST', data: $(this).serialize(), beforeSend: function() { $("#message").html("sending..."); }, success: function(data) { confirm('worked') } }); }); }); </script> the form: <form action="{% url 'newcom' Post.id%}" id="myform"> <div class="input-group"> <input type="text" name="comment_body" class="form-control" placeholder="Leave a comment"> <div class="input-group-btn"> <button class="btn btn-success" id="message" type="submit"> <i class="glyphicon glyphicon-send"></i> </button> </div> </div> <br> </form> the view: def new_comment(request, post_id): body = request.GET.get('comment_body') post = Post.objects.get(id=post_id) Nat.objects.create(fromUser=request.user.username, toUser=post.created_by, content="commented on your post") Comment.objects.create(post=post, created_by=request.user, created_at=timezone.localtime(timezone.now()), comment=body) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Shall I rename user uploaded files?
Django==1.11.6 There are file upload attacks. But modern Django seems well guarded against them. Django security guide is here: https://docs.djangoproject.com/en/1.11/topics/security/#user-uploaded-content Concerning user uploaded files it is much shorter than other security guides. In the Internet we can find this kind of advice: The application should not use the file name supplied by the user. Instead, the uploaded file should be renamed according to a predetermined convention. Well, I think that renaming is a good idea. Shall I rename user uploaded files or it is not dangerous in case of modern Django? -
Push to heroku: no module named 'channels'
I am facing this error when I add 'channels' into INSTALLED_APPS Writing objects: 100% (4/4), 351 bytes | 0 bytes/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with latest Pipenv… remote: Installing dependencies from Pipfile.lock (36121f)… remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/__init__.py", line 27, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 978, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 961, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'channels' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. … -
mod_wsgi-express: error: no such option: --url-alias
I'm deploying an application with mod_wsgi-express, and I've a new error when launching the service : oct. 12 09:15:29 Angara mod_wsgi-express[12284]: Usage: mod_wsgi-express start-server script [options] oct. 12 09:15:29 Angara mod_wsgi-express[12284]: mod_wsgi-express: error: no such option: --url-alias /static /var/www/agenda-v3.example.tld/static --url-alias /media /var/www/agenda-v3.example.tld/media The mod_wsgi-express application fails to launch... I've added the --log-directory directive to route logs to the ${SERVER_PATH}/log, which works great (I can read the log files now), I've checked the /var/www/agenda-v3.example.tld/media and /var/www/agenda-v3.example.tld/static directories, they exist for now. Service file: https://gist.github.com/frague59/a7701073d50e77e4b5492c72157ebfab Service environment file: https://gist.github.com/frague59/2992e3b02e5d40a1b5a6f0a508a73f4a Have you any idea ? It worked before... Thanks for your help ! -
Django test: how to compare result of resolve() with view function when login_required is specified for that view
In urls.py i have my view detail annotated with login_required to forward unauthorised users to login page: url(r'^(?P<id>[0-9]+)/$', login_required(views.detail), name = 'detail') And i'm trying to write a test to check which view are selected on querying target url. I've a class to log in before tests start off: class LoggedInTestCase(TestCase): def setUp(self): user = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') class ProductDetailTest(LoggedInTestCase): def setUp(self): super(ProductDetailTest, self).setUp() def test_product_detail_url_resolves_product_detail_view(self): view = resolve('/products/1/') self.assertEquals(view.func, detail) and when i run tests i got: FAIL: test_product_detail_url_resolves_product_detail_view (products.tests.ProductDetailTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\heroku\django\products\tests.py", line 46, in test_product_detail_url_resolves_product_detail_view self.assertEquals(view.func, detail) AssertionError: <function detail at 0x05CC3780> != <function detail at 0x053B38A0> ---------------------------------------------------------------------- When i remove login_required all tests pass well. -
Use the template of another django app in an another app
I have two django apps. One which belongs to core code and one contrib app. What I need to do is to display a template in my contrib app, which actually exists already in the core app. This is more or less the folder structure: django project core app templates ... contrib app templates -template_from_core_app The template renders data from views and forms which exist in the core app. I am wondering what is the best way to do something like this. -
Connect to remote ElasticSearch Server using Haystack
I am using to django-Haystack to connect to remote elasticsearch, but the haystack is looking for local installation of the elastic-server. How to use haystack with remote elastic server These are my config HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://xx.xx.xx.xx:9200', 'INDEX_NAME': 'my-index', } } -
how to pass {% csrf_token %} in javascript which is returning a html form
function GetDynamicTextBox(value){ return '<form id="addtextbox" name="addtextbox" method="post">'+ '<div class="col-xs-4">'+ '<label for="ex3">Enter Alertname</label>'+ '<input class="form-control" id="userInput" type="text" name="alertname1" placeholder="Enter the alerts..">'+ '<br>'+ '<i class="fa fa-cloud" aria-hidden= "true"></i>'+ ' <input type="submit" class="btn btn-success" value="Save">'+ '</div>'+ '</form>' } It is throwing an error csrf token missing but even I include ''+'{% csrf_token %}' it is throwning an error.Please guide me in this