Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to recursively group products by its category in django
I have Category model related to itself and products model related to Category model. Category(models.Model): name = ... subcategory = models.ForeignKey(self, related_name="SubCategory", null=True, blank=True) Product(models.Model): name = .... category = models.ForeignKey('Category', related_name='ProductCategory') I need to list products in template by recursive category groups, for instance: 1st Main Category: Products linked to only 1st Main Category 1st Level Sub Category of 1st Main Category: Products linked to only 1st Level Sub Category 2nd Level Sub Category of 1st Level Sub Category: Products linked to only 2nd Level Sub Category 2nd Level Sub Category of 1st Main Category: Products linked to only 1st Level Sub Category 2nd Main Category: Products linked to only 2nd Main Category 1st Level Sub Category of 2nd Main Category: Products linked to only 1st Level Sub Category 2nd Level Sub Category of 1st Level Sub Category: Products linked to only 2nd Level Sub Category ... Should I make this grouping in view and how can I do this? -
csv.writerow writing to the next row
I apologize if this has been asked before, I have been searching all over and can't seem to figure this out. I have a large dataset coming in as column headers for a csv file. Each header is something like START_DATE END_DATE etc, but there are just under 100 entries. It seems to be acting like I have 'wordwrap' on in a text editor and bringing my entries down into the next row. I say wordwrap, because one of my entries is OPT_OUT_SURVEY_END_DATE and it is being split at OPT_OUT_SURVEY_END_ and then putting DATE directly on the next row, and continuing with the rest of my entries. a sample of my code is as follows: # Write the results csv_file = StringIO() writer = csv.writer(csv_file) key_mapper = KeyMapper() # Get column name columns = [field.name for field in entries[0]._meta.fields if include_field(field)] column_name_fields = [key_mapper[k] for k in columns if k in key_mapper] writer.writerow(column_name_fields) Where columns is the lowercase model definition, and column_name_fields is simply a mapping to my uppercase column names. The key mapper is what maps the lowercase to the uppercase, and I have confirmed this is working correctly. The entries are coming from my djangodb via entries.objects.all() Any β¦ -
Django REST Framework, PUT/POST serializer data disappearing
I am having trouble with part of my data disappearing when I try to update or post a new instance. With data like this data = { 'item': 'Product', 'station': 'Workbench', 'ingredients':[ {'item': 'ing1', 'amount': 2}, {'item': 'ing2', 'amount':1} ] } I have a serializer with a nested serializer that get_or_creates ingredients as needed. class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ('item', 'amount') class WriteableRecipeSerializer(serializers.ModelSerializer): item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all()) ingredients = IngredientSerializer(many=True) station = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all()) def create(self, validated_data): logger.info(validated_data) ingredient_data = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) for ingredient in ingredient_data: ingredient_item = Item.objects.get(name=ingredient['item']) amount = ingredient['amount'] ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount ) recipe.ingredients.add(ingredient) return recipe def update(self, instance, validated_data): logger.info(validated_data) ingredient_data = validated_data.pop('ingredients') instance.item = validated_data.get('item', instance.item) instance.station = validated_data.get('station', instance.station) for ingredient in ingredient_data: ingredient_item = Item.objects.get(name=ingredient['item']) amount = ingredient['amount'] ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount) logger.info('Itering') instance.ingredients.add(ingredient) return instance class Meta: model = Recipe fields = ('item', 'amount', 'ingredients', 'station') The data validates and I get a response code 200, but both the response data and the validated_data a shown by my logger in the create and update methods return something like this: data = { 'item': 'Product', 'station': 'Workbench', 'ingredients':[] } The Ingredients data going AWOL somewhere. I β¦ -
Django (mezzanine) urls catching everything
I'm writing some custom views in the admin of a django project, should be simple. I have an "events" page and i want to create a "event" page (exactly the same as the django polls tutorial but in the admin, the event page would be the same as the detail view.) No i cannot use the built in functionality as normal using foreignkeys etc and need to build from scratch. urls.py: admin.autodiscover() def get_admin_urls(urls): def get_urls(): my_urls = [ url(r'^my_cms/events', views.events, name="events"), url(r'^my_cms/events/(?P<event_id>[0-9]+)/$', views.detail, name='detail'), ] return my_urls + urls return get_urls admin_urls = get_admin_urls(admin.site.get_urls()) admin.site.get_urls = admin_urls urlpatterns = i18n_patterns("", ("^admin/", include(admin.site.urls)), ) So.. visiting .../admin/my_cms/events/ works but .../admin/my_cms/events/xxxxxx just displays the same events page, rather than the detail view if i change the url pattern to anything other than "events" eg: url(r'^my_cms/events', views.events, name="events"), url(r'^my_cms/[anything]/(?P<event_id>[0-9]+)/$', then it will display the event view correctly... So my question is why is the first url catching everything? i can put anything (.../admin/my_cms/events/anythingilike) and it will display the events page? Joe -
object has no attribute 'get_answers_list'
I am getting an error: 'Question' object has no attribute get_answers_list @python_2_unicode_compatible class Question(models.Model): """ Base class for all question types. Shared properties placed here. """ quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Figure")) content = models.CharField(max_length=1000, blank=False, help_text=_("Enter the question text that " "you want displayed"), verbose_name=_('Question')) explanation = models.TextField(max_length=2000, blank=True, help_text=_("Explanation to be shown " "after the question has " "been answered."), verbose_name=_('Explanation')) objects = InheritanceManager() class Meta: verbose_name = _("Question") verbose_name_plural = _("Questions") ordering = ['category'] def __str__(self): return self.content django_quiz -
<User: root> is not JSON serializable
i am trying to display a chart that shows the number of books that are related to each user , and i am getting the right result in the shell, but i am getting an error( is not JSON serializable ) when i render my template . my template_tag @register.simple_tag() def chart_data(): users = User.objects.annotate(num_books=Count('books')) return json.dumps({ 'labels':[user for user in users], 'series':[[user.num_books for user in users]] }) -
Save object from template
#from template <button onclick="{{favorite}}">Favourite</button></td> So when the user clicks the button it sets the model_obj_name.is_favorite boolean field as True but it does not save model_obj_name. How can I solve this? Your help is very much appreciated! -
Django rest OAuth token on redis
we are planning for the new chat server for our ecommerce django based system. from the chat server we need to authenticate the user before he make a connection. We can have some private http api for validate user auth. but we feel http is slow. We need to store the user token on redis and chat server directly validates with redis. we are using https://django-oauth-toolkit.readthedocs.io/en/latest/ for the token generation. it is by default store the token on the database. How can I make authentication happens on redis server ? Is this the best approach to do so ? -
Build RESTful API with Python
I need to build a RESTful API. I like the Python programming language, and I usually build websites using Django. This API will be build from ZERO. What I donΒ«t like in Django is the fixed database structure. I prefer the freedom on designing the database. There are other options in the Python world, I came across this one: https://github.com/flask-restful/flask-restful There is a good option as framework? This will be my first RESTful API, what free online materials should I read before start? Best Regards, -
Constraints when writing Python class
I`m using Python 3.5.2 and Django 1.11 using SQLite I faced situation where i want to name my model Class with certain name, but with different names I get different results in manage.py migration regarding ForeignKeys Example from shell: modules.py from django.db import models class Place(models.Model): question_text = models.CharField(max_length=200) class Choice(models.Model): question = models.ForeignKey(Place, on_delete=models.CASCADE) Running python3 manage.py makemigrations post Migrations for 'post': post/migrations/0001_initial.py - Create model Choice - Create model Place - Add field question to choice' When renaming class Choice into in example "Rating": from django.db import models class Place(models.Model): question_text = models.CharField(max_length=200) class Rating(models.Model): question = models.ForeignKey(Place, on_delete=models.CASCADE) Output of migration attempt: Migrations for 'post': post/migrations/0001_initial.py - Create model Place - Create model Rating You might notice that foreign key implementation disappeared. I`ve triple checked it everywhere. Tried with new projects. Stuck with this for a few days. Is there any class naming restrictions or some sort of a bug? Have a nice holidays, thanks. -
Django csrf token missing or incorrect error 403
When i submit the form i get following error: CSRF verification failed Reason given for failure: CSRF token missing or incorrect. my views.py is: def name(request): if request.method == 'POST': form=NameForm(request.POST) if form.is_valid(): name=form.cleandata['your_name'] return HttpResponseRedirect('/thanks/',RequestContext(request)) else: form=NameForm() return render_to_response('contact.html') my setting.py file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] my forms.py file is: class NameForm(forms.Form): your_name=forms.CharField(initial='your name',max_length=100) my contact.html is: <form action="/your-name/" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Submit" /> </form> urls.py is: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^search/$', search),url(r'^contact/$',contact), url(r'^name/$',name),url(r'^your-name',name),url(r'^thanks/$',thank) ] -
Django form AttributeError: 'tuple' object has no attribute '_meta'
I have a django model like this - class Transaction(models.Model): date = models.DateField() type = models.IntegerField(choices=TRANSACTION_TYPE) distributor = models.ForeignKey(Distributor) second_party = models.CharField(max_length=100) route = models.ForeignKey(DistributionRoute) total_price = models.FloatField() def __str__(self): return self.date + " " + " " +self.total_price I have tried to create a form from the model like this - class transactionForm(forms.ModelForm): class Meta: model = Transaction fields = ['date', 'type', 'distributor', 'second_party', 'route', 'total_price'] But i am constantly getting following error -- File "/home/itsd/sts/transaction/forms.py", line 5, in <module> class transactionForm(forms.ModelForm): File "/home/itsd/venv/lib/python3.5/site-packages/django/forms/models.py", line 247, in __new__ opts.field_classes) File "/home/itsd/venv/lib/python3.5/site-packages/django/forms/models.py", line 133, in fields_for_model opts = model._meta AttributeError: 'tuple' object has no attribute '_meta' I am stuck here for hours. What are the reasons for such issue ? -
Return objects with boolean value=True
This is my models.py : class Song(models.Model): is_favorite = models.BooleanField(default=False) I created some songs with the model Song. So let the song names be x,y,z. Now I made the value of x.is_favorite = True . But when I typed Song.object.filter(is_favorite) to get all the songs whose is_favorite = True, it returned []. Whats the error? How can I set the is_favorite value of a song to True?How can I get all the songs with is_favorite field = True? Thank you -
Django: translation in templates not working
Django 1.11 I can't make Django translate templates in my project. Messages were compiled and recompiled. Could you give me a kick here? settings.py INSTALLED_APPS = [ ... 'frame', ... ] LANGUAGE_CODE = 'ru-RU' USE_I18N = True frame/templates/frame/frame_form.html {% extends 'general/cbv/general_form.html' %} {% load i18n %} {% block title %} <h1>{% trans "Create frame" %}</h1> {% endblock %} frame/locale/ru_RU/LC_MESSAGES/django.po #: templates/frame/frame_form.html:5 msgid "Create frame" msgstr "Π‘ΠΎΠ·Π΄Π°ΡΡ ΡΡΠΆΠ΅Ρ" tree βββ frame ... β βββ locale β β βββ ru_RU β β βββ LC_MESSAGES β β βββ django.mo β β βββ django.po ... β βββ templates β β βββ frame β β βββ frame_form.html -
How to remove celery beat task in django
I followed the doc (http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html) and write a Periodic Task , add CELERYBEAT_SCHEDULE in django settings.py, and run it in supervisor: celery -A proj worker -B But now I do not want the Periodic Task anymore. I delete the schedule in settings.py, and change command in superviosor to: celery -A proj worker without celery beat, and reload it. but once I run celery, there are still Periodic Tasks running. I event delete all data in djcelery and celery beat pid file. But it does not help. How can I remove the Periodic Task ? -
Docker-compose with Django: 'ascii' codec can't decode byte 0xcd in position 7: ordinal not in range(128)
I'm just starting with Docker and Django. I try to create example Django prodject as here: https://docs.docker.com/compose/django I made Dockerfile, requirements.txt and docker-compose.yml. But when I try to create the Django project using the docker-compose command, I have an error: docker-compose run web django-admin.py startproject MyProject . Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 64, in main File "compose\cli\main.py", line 116, in perform_command File "compose\cli\main.py", line 712, in run File "compose\cli\main.py", line 1020, in run_one_off_container File "compose\cli\main.py", line 1100, in call_docker File "distutils\spawn.py", line 220, in find_executable File "ntpath.py", line 85, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xcd in position 7: ordinal not in range(128) Failed to execute script docker-compose I try to search the same problems, but nothing helps. Windows 10 Pro (English is not system language, if it's important). My Docker: docker --version Docker version 17.03.1-ce, build c6d412e docker-compose --version docker-compose version 1.11.2, build f963d76f Dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ requirements.txt: Django psycopg2 docker-compose.yml: version: '2' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: β¦ -
Implementing Django-oscar COD
Its been 1 week now and I cannot figure out the way to implement COD in django-oscar. I will be really thankful if someone at least give me a head start to accomplish this task. I've tried to use few Github repositories but either they are outdated or not clear enough to be used with the project. A head start will be good enough for me to get started from scratch. Thanks -
Django Crispy Forms with custom field template is not adding the value of the field to request
I am using Django 1.10 and django-crispy-forms 1.6.1 in my project. I added a custom datetimepicker dropdown template that seems to be functioning correctly. The problem I am now encountering, is that every time I attempt to submit a form, I am flashed with the error on the field that it is required. It seems that after submitting the form, the field is cleared out, and the error class is added to the field. After submit, form shows errors When I checked the console, I receive no errors, but when I check Chrome DevTools, I looked at the request payload sent server-side and I see that the field is not added at all to the request. Here is a picture of the request payload from the dev tools. DevTools request payload without "time_stamp" I am able to get the datetimepicker to dropdown when the input receives focus, and that seems to work just fine. Here is the relevant code for my forms/views, and the custom template.html: models.py class Call(models.Model): history = AuditlogHistoryField() analyst = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True, limit_choices_to={'is_staff': True}, related_name='call_analyst') contact = models.CharField(max_length=50) time_stamp = models.DateTimeField(default=datetime.now) description = models.CharField(max_length=512) ticket = models.PositiveIntegerField(blank=True, null=True) CALL_TYPE = ( ('M', 'Made'), ('R', β¦ -
OAuth2 POST Data : Error 403 Forbidden for URL
I'm using OAuth2 and Django-Rest_Framework in my applications. When i try GET and in my applications it works.But i got an error as mentioned when i try to POST it. I try both method in Postman and it works well.. Did i missing something in OAuth2 settings? This is my code to POST using Angular2 PostLevelling(test: Test) { return this.http.post('http://localhost:8000/api/v1/test/', {headers: this.getHeaders()}) .map((res:Response) => res.json()); } -
Posting user-defined non-fatal error to Sentry from Django project
I have successfully configured Sentry for my Django project. But now I am experiencing a problem trying to figure out how to correctly pass a user-defined error to Sentry and continue the code execution. My code: def some_view: if my_serializer.is_valid(): my_serializer.save() else: post_exception(my_serializer._errors, request.user) post_exception definition: def post_exception(error_msg, user): str = '' if isinstance(error_msg,dict): for elem in error_msg: if isinstance(elem,dict): for key in elem: str = str + elem[key][0] else: str = str + error_msg[elem][0] else: str = str + error_msg # posting str to Sentry and continue code execution What I can't figure out is whether it's possible to send the str to Sentry so that code execution can be continued. -
QuerySet return column name along with latest time in django python but want only time
I have written code to get latest time from 'start_time' column in my Django model in following way def index(request): start=Location.objects.values('start_time').latest('start_time') end=Location.objects.values('end_time').latest('end_time') print (start) print (end) Location is my model name.The output of above program is {'start_time': datetime.time(11, 0)} {'end_time': datetime.time(19, 0)} I want my output as '11:00:00' and '19:00:00' Please help me in this case -
Django translation and model inheritance
Django 1.11 settings.py INSTALLED_APPS = [ ... 'general', 'general_frame', ... ] LANGUAGE_CODE = 'ru-RU' USE_I18N = True USE_L10N = True general/models.py class GeneralModel(models.Model): """Sharing common features of models.""" title = models.CharField(max_length=200, null=False, blank=False, default="", verbose_name=_("title")) general_frame/models.py class GeneralFrame(GeneralModel): DOCUMENT = 'D' PHOTO = 'P' PHOTO_DOCUMENT_CHOICES = ((None, '----'), (DOCUMENT, _('document')), (PHOTO, _('photo')),) type = models.CharField(max_length=1, choices=PHOTO_DOCUMENT_CHOICES, blank=False, null=False, default="---", verbose_name=_('type')) I have executed makemessages and compilemessages. The structure is as follows: Project structure: βββ general β βββ locale β β βββ ru_RU β β βββ LC_MESSAGES β β βββ django.mo β β βββ django.po βββ general_frame β βββ locale β β βββ ru_RU β β βββ LC_MESSAGES β β βββ django.mo β β βββ django.po The problem is: everything in GeneralFrame is translated, bot GeneralModel is not translated. I mean that document, photo and type are translated. But title is not translated. I made messages, checked .po files and recompiled messages again several times. Could you give me a kick here? -
Django 1.10 - Ajax - order of operations?
I am using Ajax with Django 1.10 to implement a like functionality ( a user likes an image posted by another user) on my website. I have the following code : In the views.py file : @ajax_required @login_required @require_POST def image_like(request): image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Image.objects.get(id=image_id) if action == 'like': image.users_like.add(request.user) else: image.users_like.remove(request.user) return JsonResponse({'status':'ok'}) except: pass return JsonResponse({'status':'ko'}) In base.html : <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script> <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ {% block domready %} {% endblock %} }); </script> And finnaly in the detail.html : {% extends "base.html" %} {% block title %}{{ image.title }}{% endblock %} {% block content %} ... {% with total_likes=image.users_like.count users_like=image.users_like.all %} <div class="image-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> </div> {{ image.description|linebreaks }} </div> <p> β¦ -
Issue with Webpack using React
Sorry if this is a duplicate question. I can't seem to solve this or find an answer. I have a basic Webpack setup i'm working with in conjunction with React and Django. Basically I'm getting compilation error's when using webpack. These two webpack files aren't loading properly, both below, and neither is this App module (I think it's the provider component from redux). I think it may be something to do with a driver - or something very simple that I've missed. I would really appreciate the help as I've been trying to fix this for a long time now haha! Thanks!!! webpack.config.local.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var ip = 'localhost' var config = require('./webpack.base.config.js') config.devtool = "#eval-source-map" config.entry = { App1: [ 'webpack-dev-server/client?http://' + ip + ':3000', 'webpack/hot/only-dev-server', './reactjs/App1', ], } config.output.publicPath = 'http://' + ip + ':3000' + '/assets/bundles/' config.plugins = config.plugins.concat([ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BundleTracker({filename: './webpack-stats-local.json'}), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('development'), 'BASE_API_URL': JSON.stringify('https://'+ ip +':3000/api/v1/'), }}), ]) config.module.loaders.push( { test: /\.js?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] } ) module.exports = config webpack.base.config.js var path = require("path") var webpack = require('webpack') module.exports = { context: __dirname, entry: β¦ -
NoReverseMatch at / myplaylist
Error: NoReverseMatch at /myplaylists/ Reverse for 'create_playlist' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] My urls.py: url(r'^create_playlist/$', views.create_playlist, name='create_playlist'), On my index page, im trying to reference that url using : <a href="{% url 'create_playlist' %}">Create playlist</a>