Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
python django restful api - can't always catch a specific post request
I am using python Django restful api framework. I am trying to catch all the userPreference post requests in views.py. For some reason I can catch all the post request with my code. Here is my views.py class aUserViewSet(aAPIViewSet): def get_queryset(self): ''' This function limits the queryset to User's data ''' queryset = super(aUserViewSet, self).get_queryset() qs1 = queryset.filter(user=self.request.user) if qs1.exists(): if "userpreference" in qs1.model._meta.db_table: tp = self.ws_userPreference(qs1, self.request.user.username) else : print("no handle needed") else : print("qs1 not exist") return queryset.filter(user=self.request.user) def ws_userPreference(self, qs1, username): if self.request.method == 'POST': print("get userPreference post") else : print("get userPreference non post request") return 0 class UserPreferenceViewSet(aUserViewSet): queryset = UserPreference.objects.all() print "In userPreference viewset" serializer_class = UserPreferenceSerializer filter_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) filter_backends = (URLFilter, ) ordering_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) -
upstream prematurely closed while reading response header from upstream, reques: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:"
upstream prematurely closed connection while reading response header from upstream, client: xxx.xx.xx.xx, server: website.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:", host: "website.com" How to solve this? -
Error Setting Up Frontend Login in django marcador tutorial
I am a newbie using django 1.11.5 installed.This a tutorial from macador app project.I have already created the view in thhe project main template.my login and logout is not working.When i run the runserver command,I get the following error. terminal Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f087adf5aa0> Traceback (most recent call last): File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/root/Desktop/bookmarksmanager/myenv/src/mysite/urls.py", line 27, in <module> name='mysite_login'), File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view … -
save google autocomplete places data in a model which has foreign key
I have a form in django where there is a field called address where I am using https://github.com/ubilabs/geocomplete/ plugin so which when submitted should store address in fields like country, city, postal_code etc instead of giving user to fill all those fields in restaurant object along with other data. This one is working well class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) country = models.CharField(max_length=7) city = models.CharField(max_length=7) postal_code = models.CharField(max_length=7) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant widgets=({country: forms.HiddenInput(attrs={'id': country}), city: forms.HiddenInput(attrs={'id': locality}), postal_code: forms.HiddenInput(attrs={'id': postal_code})}) fields = ( "logo", "name", "cuisine", "country", "city", "postal_code", "address", "phone" ) def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() if request.user.is_authenticated(): if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) else: if request.method == "POST": user_form = MemberForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username=user_form.cleaned_data["username"], password=user_form.cleaned_data["password"] )) return redirect(restaurant_order) return render(request, "restaurant/sign_up.html", { "user_form": user_form, "restaurant_form": restaurant_form }) <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if user.is_anonymous %} {% bootstrap_form user_form %} {% bootstrap_form restaurant_form %} {% else %} Hello, {{ request.user.username }} <br>Please …