Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying django websocket on apache
I have django-project (1.11, python 3.5) working with apache, but i can not make working websockets. This feature based on django-private-chat module. So, management command is running, but when i open web-page, in console i see: "WebSocket connection to 'ws://localhost:2842/m24f67swft8m1y9o4dif8igd42i4m7x9/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED". What's the problem? -
In django File upload option not show on page but other fields of form are shown
I want to create a form with image upload option.I created database with 4 fields: Artist Title geneder and 4th field is for image upload first 3 fields are showing on web page but the image upload field is missing but at the same time upload field is showing in admin area and display image on webpage which i uploaded from admin area. What can i do to show upload option in web page ? Here is my complete code: Models.py class album(models.Model): artist = models.CharField(max_length=250) title = models.CharField(max_length=500) gender = models.CharField(max_length=100) album_logo = models.FileField() Urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace='myapp')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Form template page where only text fields are shown {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2">{{ field.label_tag }}</label> <div class="col-sm-10">{{ field }}</div> </div> {% endfor %} -
Django cursor pagination
I'm looking for a solution to get a cursor pagination in Django. To be clear, cursor pagination is (I think) a system of pagination like Facebook. You just have to scroll down to load more contents. -
Append tag value and attributes to same tag in dexml model
Using dexml python I was wondering how could I append tag value as well as attributes to the same tag. eg. < Person name="Any name" >Value< /Person > Any help is appreciated -
Static content generation in Wagtail
I'm looking for a way of generating static content (SSG) in wagtail from pre-existing files. I know that there are 100% SSG blog engines (like the excellent pelican) but I'm am wondering if there is a way already exist which enables the import (and updating where appropriate) of content into a page model. I did not really want to reinvent the wheel if there is an elegant solution already in the wild. -
Django: Safely check for related objects before deletion
I have a Django app with two models: class Foo(models.Model): baz = models.CharField(max_length=100) class Bar(models.Model): foo = models.ForeignKey(Foo) In a view, I want to delete a Bar object. Currently it's done with: foo_to_delete = Foo.objects.get(pk=1) if not foo_to_delete.bar_set.exists(): # step 1 foo_to_delete.delete() # step 2 But now if at the time between the step 1 and the step 2, someone saves a new Bar object with the foo field pointing to foo_to_delete object, this new Bar object would be deleted by step 2. Is there any way to avoid this, maybe by doing a single SQL call ? Does the Django ORM provides something for doing this kind of check before deletion safely ? -
Django - Pre populate form with instance data
I have the following class based view, class FacetUpdate(TenantRootedMixin, UpdateView): model = Tenant context_object_name = 'facetten' form_class = FacetForm def get_success_url(self): kwargs = {'uuid': self.object.uuid} return reverse_lazy('productupdate', kwargs=kwargs) def get_success_url(self, **kwargs): return reverse('facet_list', args=[self.request.tenant.slug]) def get(self, request, *args, **kwargs): d = super(FacetUpdate, self).post(request, *args, **kwargs) self.object = self.get_object() return super(FacetUpdate, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): d = super(FacetUpdate, self).post(request, *args, **kwargs) self.object = self.get_object() #Create list of selected checkbox_ids hitlist = request.POST.getlist('facet_link') #Get current tenant currenttenant = Tenant.objects.get(name=self.request.tenant) #Get all facets that have been selected in the form selected_facets = Facetss.objects.filter(id__in=hitlist) #Update the currenttenant currenttenant.linked_facets = selected_facets currenttenant.save() return d That passes data to the following form. class FacetForm(forms.ModelForm): class Meta: model = Tenant fields = ['linked_facets'] This form is not using an autogenerated form, but a custom html page that contains a list of checkboxes. (Using a default widget meant that the layout was all wrong, as we wanted a nested layout) The form works, however, the one thing that is missing is having the checkboxes being prepopulated based on the instance that is being edited. All fields in the form show up empty, forcing the user to rewrite all of the data during the edit … -
What url structure should I use when retrieving users via a token?
I'm using Django Rest Framework to handle token authentication for a mobile application for a school. In particular, when a student logs in, the mobile application sends a token to my Django backend, which then combines data from its database and some external data from another source. I found it easiest to use a generic RetrieveAPIView to accomplish what I needed. My code is working, and my main question is around the url. For most retrievals, we usually have the primary key as well (e.g. /students/SOME-ID), but in this case, I'm using the token to retrieve the user rather than the primary key. In fact, if SOME-ID passed in was different from the Token, the user associated with the Token would be returned anyway (which seems kinda strange). I'm wondering whether it is better to have my url route be just (/students) instead though this seems to be a list rather than a retrieve operation. WHAT I HAVE NOW http://localhost:8000/api/v1/revision/students/1 IS THIS BETTER http://localhost:8000/api/v1/revision/students/ CODE class StudentView(generics.RetrieveAPIView): model = Student serializer_class = StudentSerializer # combines data from both current and legacy database def retrieve(self, request, pk=None): obj = get_object_or_404(Student, user=request.user) # KIV -> unsure if this is the best way … -
How to integrate a Django app with multiple forms in Django CMS as plugin?
I followed this tutorial to integrate my Django app into my Django CMS website. My app Sale has two models, OrderModel() and CustomerModel(), that both are used in forms.py to pass some fields to a form, like so: class CustomerForm(forms.ModelForm): class Meta: model = CustomerModel fields = ['firstname', 'surname', 'company', 'email',] class OrderForm(forms.ModelForm): class Meta: model = OrderModel fields = ['product', 'delivery_date',] As described in the tutorial, in models.py I generate the SalePluginModel and in cms_plugins.py, I specify the SalePluginPublisher plugin class, which is responsible for providing django CMS with the necessary information to render my app, like so in models.py: class SalePluginModel(CMSPlugin): title = models.CharField(u'title', blank=True, help_text=u'Optional. Title of the widget.', max_length=64, ) and so in cms_plugins.py: class SalePluginPublisher(CMSPluginBase): model = SalePluginModel # model where plugin data are saved module = _("Sale") name = _("Sale Plugin") # name of the plugin in the interface render_template = "sale/sale_plugin.html" form = '' # How to pass multiple model forms here? Now, the problem is, that only one form class can be passed to the CMSPluginBase as attribute. Is there a possibility to include both form classes in the SalePluginPublisher or in general, how can I integrate my app with two models … -
deployment Python Django applications to AWS Beanstalk
How long does it take to deploy Python Django applications to AWS-Beanstalk (for a simple social-platform) normally? Developers are giving me estimations 90 to 100 hours of work. It feels like a bit rip off. Are there responsible, experienced professionals here set up the deployment? -
'django runserver' working fine but 'django runserver ip:port' giving 404
I understand similar questions have been asked but none of the solutions are applicable here. When I run python manage.py runserver, everything works fine and I can access local server. But when I run python manage.py runserver 10.5.51.56:8000 (local IP address of my machine), on doing browser request I receive 404 error(and requests comes to server). After reading already asked questions on SO, I tried python manage.py runserver 0.0.0.0:8000 and now when I request localhost:8000 through my browser I get correct response but when I request 10.5.51.56:8000 I again receive 404 with request coming to server. I also tried with other ports (8001, 8002) in case port is being occupied but got same behaviour. I think it's some network permission issue but how can I pinpoint the problem? -
Django redirecting url with changed values
I have urls that take a parameter called board_slug. Before getting the template the view will replace the slug if its name is wrong and redirect it. I have already made the code for fixing the slug but do not know how insert the fixed board_slug into the new url. This code is run across multiple views so it has to work with all the following kinds urls: url(r'^boards/(?P<board_slug>[^/]+)/$', views.BoardView.as_view(), name='board'), url(r'^/front-thing/boards/(?P<board_slug>[^/]+)/new/$', views.BoardView.as_view(), name='new_board'), url(r'^boards/(?P<board_slug>[^/]+)/etc...$', views.BoardView.as_view(), name='anything_with_board'), class BoardView(View): template_name = 'forums/board.html' def get(self, request, board_slug): if wrong: url = get_django_url url.board_slug = 'new-slug' return redirect(url) else: return template -
Django dot fails to use dictionary key variable in dot notation
I need to create some code that will be integrated into a larger Django project, and I came across this problem. I am developing outside of a web environment, and I have reduced my problem to this test case: import django import sys from django.template import Template, Engine, Context nouns = {'jobs': {'Ugg': 'Programmer', 'Box': 'Storage' }} fmts = {'Ugg': 'standard', 'Box': 'bold'} report = {'these': nouns, 'formats': fmts} template_text = """ {% for thing, thing_function in report.these.jobs.items %} {{ thing }} | {{ thing_function }} | {{ report.formats.thing }} {% endfor %} Ugg name format: {{ report.formats.Ugg }} Box name format: {{ report.formats.Box }} """ t = Engine().from_string(template_text) c = Context({'report': report}) print(t.render(c)) print("Python version: " + str(sys.version)) print("Django version: " + str(django.VERSION)) The output is: Ugg | Programmer | Box | Storage | Ugg name format: standard Box name format: bold Python version: 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:14:59) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] Django version: (1, 11, 3, 'final', 0) My problem is that report.formats.thing is not picking up the loop variable thing. It looks like loop variables can't be used this way with dot notation. My question is, what is the … -
RequestError: TransportError(400, u'parsing_exception')
I am using django-haystack and elasticsearch for my app. I have loaded all the requirements and trying to search my indices using search.html But whenever i tried to retrieve the results using an API at http://localhost:8000/search, i am getting the below error and i have googled much about this but couldn't able to get any help: RequestError: TransportError(400, u'parsing_exception') The full error that I am getting is: Traceback (most recent call last): File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 530, in search doc_type, '_search'), params=params, body=body) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request self._raise_error(response.status, raw_data) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) RequestError: TransportError(400, u'parsing_exception') Failed to query Elasticsearch using '(sdf)': TransportError(400, u'parsing_exception') Traceback (most recent call last): File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 530, in search doc_type, '_search'), params=params, body=body) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request self._raise_error(response.status, … -
Django Restful Api of nest object
The "Brand" object is foreign key of "company",they are ManytoMany relationship,and Brand object exists the field "company_Group" the models are as follows: class Brand(models.Model): Company_Group = models.ManyToManyField(Company) Brand_Group = models.CharField(u'Brand Group',max_length=255, default="") Pref_Brand_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="") Pref_Brand_Name = models.CharField(u'Preferred Name',max_length=255, default="") PrimaryContact = models.ForeignKey(UserRole, null=True, blank=True) class Company(models.Model): Pref_Company_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="") Pref_Company_Name = models.CharField(u'Preferred Name',max_length=255, default="") Company_Type = models.CharField(u'Company Type',max_length=255, default="") class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' the Serializer as follows ,data_export_setting.Company_form_stand is the field as class CompanySerializer(serializers.HyperlinkedModelSerializer): Brand = BrandSerializer(source='brand', read_only=True) class Meta: model = Company Company_form_stand=['id', 'Brand', 'Company_Type','Company_Name','company_Name_SC'] fields = data_export_setting.Company_form_stand depth = 2 def create(self, validated_data): return Company.objects.create(**validated_data) def update(self, instance, validated_data): instance.__dict__.update(**validated_data) instance.save() return instance the viewset are as follows class BrandViewSet(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer model = Brand def get_serializer(self, *args, **kwargs): if 'data' in kwargs: data = kwargs['data'] if isinstance(data, list): kwargs['many'] = True return super(BrandViewSet, self).get_serializer(*args, **kwargs) class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer and I want to show the company objects with Brand objects ,however,it seems to ignore the brand object and its field appreciate any help ,thanks -
How to pass a dict of queryset results to $.json?
Currently I have the following queryset filters: def grab_city_landmark(request): State = State.objects.filter(state=state_name) City = list(State.valued_list('city', flat=True).distinct()) Landmark = list(State.valued_list('landmark', flat=True).distinct()) response = { 'state': State, 'city': City, 'landmark': Landmark, } return HttpResponse(response, content_type="application/javascript") The JQuery call is: $(document).ready(function() { $.getJSON('grab_city_landmark/', {state_name: state}, function(data) { ... GRAB DATA HERE ... iterate over i data['city'][i] My questions are: How do I make the response in json form? Is it in json form? How do I check? I can't see the object return to jquery. json.dumps(response) doesn't seem to work. How do you take a look in java console what is returned to the jquery? -
Sort nested serializer objects in Django
I have 2 serializers, one of them includes nested Serializer with many=True. I want to sort steps field by service_id. Including ordering=("service_id") into StepSerializer didn't help. How can I perform steps sort in nested Serializer? class StepSerializer(serializers.ModelSerializer): class Meta: model = TranslatedStep fields = ("pk", "service_id", "create_date", "update_date",) class LessonSerializer(serializers.ModelSerializer): steps = TranslatedStepSerializer(many=True) class Meta: model = TranslatedLesson fields = ("pk", "service_id", "create_date","steps_count", "steps") -
Why Redirect 127.0.0.1:8000 when logging in to the django application with twitter account?
I am about to make Django application available for production. However, login using twitter account does not work. I am using python-social-auth. There should be no problem in setting. But after being authenticated on twitter, it will be redirected to 127.0.0.1 instead of the domain I set up. The twitter application settings are as follows. Callback URL: http://example.com/ Callback URL Locked: No Sign in with Twitter: Yes the login button is as follows <button type="button" onclick="location.href='{% url 'social:begin' 'twitter' %}'">Login</button> urls.py of the django project is as follows from django.conf import settings from django.conf.urls import url, include from django.contrib import admin, auth import app.urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('social_django.urls', namespace = 'social')), url(r'', include(app.urls)), ] urls.py of app is as follows. from django.conf.urls import url from django.conf import settings from app import views from django.contrib.auth.views import logout urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^home/', views.home, name='home'), url(r'^logout/$', logout, {'template_name': 'logout.html'}, name='logout') ] I can log in without problems in the local environment. What is wrong? -
django rest framework serializer save() “got key error message”
sorry for the repost but I made a lot of mistakes in my first question I think it's better if I just asked it again with more details and less mistakes in explaining it. I'm trying to use the save method on my custom django rest framework serializer. I have a .create() method in the serializer and my views.py looks like this (simplified): def some_method(): validated_data = { 'id': some_integer_id, 'created_at': "some text"} context_data = { 'user': request.user.id} obj_serialized = MyCustomSerilizer(data=validated_data, context=context_data) if obj_serialized.is_valid(): try: obj_serialized.save() return Response(obj_serialized.data) except BaseException as e: raise APIException(detail=e.message) else: raise ValidationError(obj_serialized.errors) this returns an exception: Got KeyError when attempting to get a value for field `created_at` on serializer `MyCustomSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `dict` instance. Original exception text was: u'created_at'. here is my serilizer: class MyCustomSerializer(serializers.Serializer): id = serializers.IntegerField() created_at = serializers.CharField() def create(self, validated_data): print validated_data['created_at'] user = self.context.get('user') return {'id': validated_data['id'], 'message': validated_data['message']} the first line of create method prints the value of created_at field correctly. the data I send with the dict is unicode and so the keys for the dict turn unicode too but I doubt that's the … -
settings.DATABASES is improperly configured (Elasticsearch)
I am using elasticsearch as database for my Django app. But whenever I run python manage.py rebuild_index I come up with the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/management/commands/rebuild_index.py", line 37, in handle call_command('update_index', **options) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 214, in handle self.update_backend(label, using) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 240, in update_backend total = qs.count() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/query.py", line 369, in count return self.query.get_count(using=self.db) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 476, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 457, in get_aggregation result = compiler.execute_sql(SINGLE) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 824, in execute_sql sql, params = self.as_sql() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 374, in as_sql from_, f_params = self.get_from_clause() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 612, in get_from_clause clause_sql, clause_params = self.compile(from_clause) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 353, in compile sql, params = node.as_sql(self, self.connection) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/datastructures.py", line 146, in as_sql base_sql = compiler.quote_name_unless_alias(self.table_name) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 344, in quote_name_unless_alias r = self.connection.ops.quote_name(name) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/db/backends/dummy/base.py", … -
Django solution for cursor pagination
I would like to setup a cursor pagination. I mean a dynamic pagination like Facebook which is based on your position in the page. I look for a way to do it and I found this : https://github.com/photocrowd/django-cursor-pagination Is anyone already tried it ?Is there a beter solution ? Thanks -
Setting up django jenkins build on stash to accept MySQL Raw query syntax
My project depends on a Raw mysql query and hence the Jenkins build is failing since it does not know about the CONCAT function of MySQL. How can I setup a jenkins job to accept the MySQL query syntax? -
Default value of read_only_fields
There is a Django Rest API project. There is a FooSerializer which extends serializers.ModelSerializer: class FooSerializer(serializers.ModelSerializer): foo = serializers.CharField() class Meta: model = Foo fields = DEFAULT_FOO_FIELDS + ['foo'] read_only_fields = [] Does the read_only_fields has to be set empty list every time or the empty list is the default value and the expression can be just ignored? -
How Django links to item detail page at admin site?
I met a problem when learning Django Tutorial. I design a detail method in views.py to show detailed information for each item I added in pdf-format and a admin page. The problem is, when I'm on the admin web page editing a particular item, how to add a hyperlink pointing to its corresponding detail web page? I construct my urls in this way: urlpatterns = [..., url(r'^(?P<item_id>[0-9]+)/$', views.detail, name='detail')] To do that, I need to get that item id at the corresponding template. It seems that change_form.html is the template and the overwritten function render_change_form inside MyModelAdmin class is the function who renders the template. So, is it possible to get the item id in render_change_form? I noticed that there is a question asking this, yet there is no accepted answer. So is getting item id the correct way solving it? What's the proper solution to do that? -
django.db.utils.DatabaseError: permission denied for sequence
After assigning the data to my database, and run command: python manage.py syncdb I'm facing this error: django.db.utils.DatabaseError: permission denied for sequence log_action_id_seq I tried pretty all of the ways suggested for solving sequence errors, none of them works! Can anyone help to solve this issue please?