Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField'
Installing project from GitHub repo and receive following error after all File "/Users/TheKotik/closer/blog/models.py", line 5, in <module> from rest_framework import serializers File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/rest_framework/serializers.py", line 1534, in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField' Have no idea, what it's related to. Please help.. The whole traceback: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/TheKotik/closer/blog/models.py", line 5, in <module> from rest_framework import serializers File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/rest_framework/serializers.py", line 1534, in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField' -
reverse() got an unexpected keyword argument 'pk_url_kwarg' - UpdateView
I am trying use Django built-in class UpdateView to update an image model The model is: def get_image_path(instance, filename): return '/'.join(['studyoffer_images', instance.study_offer.slug, filename]) class UploadStudyOffer(models.Model): study_offer = models.ForeignKey(StudiesOffert, related_name='uploadsstudyoffer') image = models.ImageField(upload_to=get_image_path, verbose_name='Seleccionar imagen') # images folder per object featured = models.BooleanField(default=False, verbose_name='Destacada', help_text='Indica si la imagen aparecera en el carrusel') thumbnail = models.BooleanField(default=False) active = models.BooleanField(default=True, verbose_name='Activa', help_text='Indica si una imagen de oferta esta habilitada o disponible') objects = UploadStudyOfferManager() def __str__(self): return self.study_offer.ad_title The form of this model is: class StudyOfferImagesUploadForm(forms.ModelForm): class Meta: model = UploadStudyOffer fields = ('image', 'active', 'featured') What I want now is to allow the user to edit an image and can change it and change the status image (featured, active, thumbnail) Then I build my StudyOfferImageUpdateView to update the image attributes: class StudyOfferImageUpdateView(SuccessMessageMixin, UserProfileDataMixin, LoginRequiredMixin, UpdateView): model = UploadStudyOffer form_class = StudyOfferImagesUploadForm success_url = reverse_lazy("host:edit-study-offer-image", pk_url_kwarg='pk') success_message = "Imagen actualizada" def get_context_data(self, **kwargs): context = super(StudyOfferImageUpdateView, self).get_context_data(**kwargs) user = self.request.user return context def get_object(self): return get_object_or_404(UploadStudyOffer, pk=self.kwargs.get('pk')) The URL to access this view is: url(r"^study-offer/edit/images/(?P<pk>\d+)/$", StudyOfferImageUpdateView.as_view(), name='edit-study-offer-image' ), When I want edit my image the template is this: {% block body_content %} <h2>Editar imágen</h2> <form role="form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ … -
How to extract values from queryset objects in python?
I'm trying to compare values to each other for a quiz in django. I'm using POST data for object data and trying to compare each other. Current code: answerList = [] answerList2 = [] for i in Question.objects.filter(related_quiz = examid): answerList.append(i.answer) form = EditQuizForm() form = EditQuizForm(request.POST) if request.method == "POST": form = EditQuizForm(request.POST) submittedObject = request.POST.copy() newList = (dict(submittedObject.lists())) values = newList.values() for i in values: answerList2.append(i) print(answerList) print(answerList2) This returns the values: ['A', 'D'] [['A'], ['D']] However, I cannot iterate over these to compare them as they are not the same. I do not how get answerList2 to appear like answerList1 so i can compare the values. Any help would be appreciated as i am fairly new to python/django. -
Django foreign key default
I'm using CreateView to add a Section with a foreign key to Course. If I have a default value for the foreign key, it always saves as the default value. If I don't have a default value, it always saves as null or blank. class Course(models.Model): course_name = models.CharField(max_length=50) course_code = models.CharField(max_length=8, unique=True) atype = models.CharField(max_length=10, default='Course') def get_absolute_url(self): return reverse('calculate:course_detail', kwargs={'pk': self.pk}) def __str__(self): return self.course_name class Section(models.Model): section_name = models.CharField(max_length=50) percentage = models.IntegerField(default=100, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) atype = models.CharField(max_length=10, default='Section') section_section = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) section_course = models.ForeignKey('Course', blank=True, null=True, on_delete=models.CASCADE) def get_absolute_url(self): if self.section_course is None: pk = self.section_section.pk else: pk = self.section_course.pk return reverse('calculate:course_detail', kwargs={'pk': pk}) def __str__(self): return self.section_name Here's the CreateView: class SectionCreate(CreateView): model = Section fields = ['section_name', 'percentage', 'section_section', 'section_course'] def get_initial(self): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) return {'section_course': course} def get_form(self, form_class=None): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) form = super(SectionCreate, self).get_form(form_class) form.fields['section_section'].queryset = Section.objects.filter(section_course=course) return form def get_context_data(self, **kwargs): pk = self.kwargs['pk'] s_type = self.kwargs['s_type'] context = super(SectionCreate, self).get_context_data(**kwargs) if s_type == 'Course': course = Course.objects.get(pk=pk) self.model.section_course = course if s_type == 'Section': s = Section.objects.get(pk=pk) section.section_section = s context['course'] = course context['pk'] = pk context['s_type'] = … -
The best way to hash password with Django & custom user in all the possible create/save cases?
I have a custom user which is inherited from Django's AbstractBaseUser and PermissionsMixin. From that custom user I'm going to inherit two other user types. I'm also using Django Rest Framework. For the custom user I've made a custom user manager which hashes the password. I already overrode the create method for serializer linked to that custom user model and models inherited from it. I need to hash the password no matter through which functionality/method the user is created (also in the cases when a object of model inherited from the custom user is created). I also need to hash the password in case the user wants to reset his/her password (this goes for those inherited models too). How do I ensure that? In other words, how many and what create/save methods I have to override? To the architecture itself, could it be possible to use Django's default user model so that the email is a username and that username and email fields are always synced together? -
How do I pass an array to a custom Django database function?
I'm trying to write a Django wrapper for PostgreSQL's width_bucket like this: from django.db.models import Func from django.db import models class Log2Bucket(Func): template = "width_bucket(%(expressions)s::double precision[])" def __init__(self, expression, a, b, **extra): buckets = [] while a <= b: buckets.append(str(a)) a *= 2 buckets = Value(buckets, output_field=ArrayField(models.FloatField())) super().__init__(expression, buckets, output_field=models.PositiveSmallIntegerField(), **extra) This works for queries like Foo.objects.annotate(b=Log2Bucket('bar', 125, 100000)).values('b') But for from django.db.models import Count (Foo.objects.annotate(b=Log2Bucket('bar', 125, 100000)) .values('b').annotate(count=Count('pk'))) I get a TypeError: unhashable type: 'list' from inside Django. How do I fix this? Is there an approach that makes this function less hacky? I've tried using function = 'width_bucket' instead of template = ..., but then I get a PostgreSQL error function width_bucket(double precision, numeric[]) does not exist. -
Django class based view form_class choice
I've a single View, that can be called with or without the label_rif attribute, based on this I can switch the form_class and template? class LabelCreateView(CreateView): model = models.Label if self.kwargs['label_rif'] > 0: form_class = LabelForm template_name = 'AUTO_form.html' else: form_class = LabelManForm template_name = 'MAN_form.html' I've tried to insert the form_class without succes in the method def get_form_kwargs(self): kwargs = super(LabelCreateView, self).get_form_kwargs() if self.kwargs['label_rif']: form_class = LabelForm Or should I define another separate view? I want to keep it DRY, is it possible? -
Python and PG Copy
I have the code below which downloads a CSV to memory using sqlalchemy inside of a Django application. engine = create_engine('postgres://.....') response = requests.get(STOCK_DATA_URL) zip_file = ZipFile(BytesIO(response.content)) data_file_name = zip_file.namelist()[0] new_prices = zip_file.open(data_file_name) df = pd.read_csv(new_prices, names=['ticker', 'name']) Instead of loading it into a dataframe, how would I save it to the database using pg_copy which works manually. \copy stock_tickers (ticker, name) FROM '<FILE NAME>' DELIMITER ',' CSV; -
Django (Ubuntu): What is the best way to use npm for front-end dependency management
How I used to create my Django projects mkvirtualenv env1 - creates virtual environment env1 pip install -r requirements.txt - install some python modules pip install nodeenv - for isolated node environments nodeenv -p - This commands installs nodejs and adds new shell functions to our virtualenvwrapper shell functions. Directory node_modules was put inside env1 directory npm install -g bower - Bower directory was put in node_modules inside env1. pip install django-bower - I set BOWER_COMPONENTS_ROOT = '/PROJECT_ROOT/components/' I set BOWER_INSTALLED_APPS and run ./manage.py bower install. Packages listed in BOWER_INSTALLED_APPS were installed into '/PROJECT_ROOT/components/bower_components' at the end I used django-compressor However Bower is now apparently no longer a thing, so i need a new setup. For now I decided, that I'm gonna use only npm for front-end dependency management. So my question is, if the following setup is good enough. NOTE - I am a complete rookie regarding npm and javascript environments Create nodeenv environment inside virtualenv env1. Then in django project root I run npm init which creates package.json, and then from the same directory I run npm install foundation-sites --save for example. This creates node_modules in project root. Then I could use django-compressor with precompilers that work on … -
Python coding assignment
Design an algorithm to calculate Score for the UNIT. An UNIT contains many SECTIONS. SECTION contains many QUESTION. Question has multiple choices with selected values (each choice has weight associated with it). The score for UNIT is calculated as average score for all SECTIONS in the UNIT. The score for SECTION is calculated as sum of score of all QUESTIONS in that SECTION. The score for QUESTION is calculated as weight of selected choice divided by sum of all choices for that QUESTION. the sample UNIT is like (json): -
How to get objects using a ForeignKey field through another ForeignKey in Django?
My models.py is something like this: class Department(models.Model): name = models.CharField(max_length=255) class Category(models.Model): name = models.CharField(max_length=255) department = models.ForeignKey(Department, related_name="categories") class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name="products") As you can see, the product model does not have a direct connection to the department, it only has one through the category model. However, in my department details for < Department X >, I want to get all the products that have a category that has the department < Department X >. Is there any way to do it with one query? I don't want to use a for loop for this. Thanks! -
How to use nginx-rtmp module to create a Django REST API and hls live stream
https://benwilber.github.io/streamboat.tv/nginx/rtmp/streaming/2016/10/22/implementing-stream-keys-with-nginx-rtmp-and-django.html This article helped me with most of my problems but how to use rest API view with this, and return Json response -
How to neaten a long built in template tag in django?
How do you neaten a long template tag like this: <td>{{ membership.is_project_manager|yesno:"<span class='glyphicon glyphicon-ok'></span>,<span class='glyphicon glyphicon-remove'></span>"|safe }}</td> -
Django celery beat not working
I am trying to get started with celery, but I can't get my task up and running. I have installed django-celery-beat and celery4. My settings file. Installed apps (with celery packages) ... 'django_celery_beat', 'django_celery_results' the celery configuration CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sandbox.settings') app = Celery('sandbox') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and my simple task, which i configured to run through the admin panel of django celery beat. from __future__ import absolute_import, unicode_literals from sandbox.celery import app @app.task() def try_celery(): print "Trying out Celery" I am trying to run this task as a periodic task (beat) with cron tab as */2 * * * * The log I am getting is, $ celery -A sandbox worker --loglevel=debug [2017-10-24 14:28:02,999: DEBUG/MainProcess] … -
Testing a utility method that doesn't belong to a class in django
I have a file I created called utils.py In that I have a few little methods that don't really belong on a model, they don't really belong in the view. They don't do a lot of work and are just used once or twice in my application so I felt they best fit into a 'utility' kind of role. My question is - how do I test them? I currently test my models and forms - but I wanted to put together some tests to go against this utils file, too. I just don't know how to do that without a class to call in the test_utils.py file -
Can't authenticate Django user in shell
For some reason I can't authenticate a newly created user in the Django shell and I really don't know what's wrong. Must be something very stupid... Start Django shell: (venv) xxx:xxx xxx$ python ../manage.py shell Python 3.6.0 (v3.6.0, ...) [GCC 4.2.1 (...) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Create a new user: >>> from django.contrib.auth import get_user_model >>> email = "testemail@gmail.com" >>> password = "testpassword" >>> user = get_user_model().objects.create_user("TestUser", email, password) The new user seems to have been added to the database correctly: >>> get_user_model().objects.all() <QuerySet [<MyUser: testemail@gmail.com>]> >>> u = get_user_model().objects.first() >>> u.username 'TestUser' >>> u.email 'testemail@gmail.com' >>> u.password 'pbkdf2_sha256$36000$Onrvxuy09b6r$sCuz/2/bIbeg5j7cfO934kCIvzVdxqo1s1v6x6nwYLY=' But authentication fails: >>> from django.contrib.auth import authenticate >>> user = authenticate(email = email, password = password) >>> user.email Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'email' >>> I have a custom User model hence the use of get_user_model(). models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = … -
Conflicting models when overriding
It seems like oscar is not picking up my pointed local folder. INSTALLED_APP = [] + get_core_apps(['myoscar.partner']) My error is Conflicting 'partner' models in application 'partner': <class "oscar.app.partner.models.Partner"> and <class "myoscar.partner.models.Partner"> This also leads me to another related question - there's two settings.py. I've tried adding in both. When I remove myapp.partner in my main app, I obviously dont get the error but it gives me oscar's default model - which makes sense but then I run into the above error when I add it in. I don't know of anywhere else I'm registering the partner model before this override - at least not that I know of. My question is 1) which settings.py is the right one? I want to make sure. 2) why do I get this error when I pointed to the forked folder? Is it not picking up my folder? App/myoscar/partner/models.py from django.contrib.auth import get_user_model from django.db import models from oscar.apps.partner.abstract_models import AbstractPartner User = get_user_model() class Partner(AbstractPartner): users = models.OneToOneField(User,related_name='partner_user') from oscar.apps.partner.models import * #per some answers on stackoverflow, I've also tried removing this but the docs say this should be added here to keep the other models. my folder structure: App |--app |----__init.py__ |----settings.py … -
How to pass function result to a templage?
i'm working on django projects and i have a problem : I would like to pass the results of function to a dynamic template. def liste_ebauche(request): if not request.is_ajax() and not request.method == 'GET': raise Http404 try: param_json = None param = request.GET for json_liste_eb in param: param_json= json.loads(json_liste_eb) of_select= param_json['numof'] reponse= {} reponse_json= {} reb={} c=connection.cursor() c.execute("BEGIN") c.callproc("p_web_get_ebauche",[of_select]) ebauches=c.fetchall() c.execute("COMMIT") c.close() html = render_to_string("paquet/ss_ebauche.html", locals()) except Exception as e: logger.warning("error :" + e.message) return HttpResponse(html) In my templates i' m doing : {% for ebauche in ebauches %} <tr style="text-align:center"> <td class="id_ss_ebauche" style="display:none;">{{forloop.counter}}</td> <td class="case">{{ebauche.ebauche}}</td> <td class="case">{{ebauche.type}}</td> <td class="case">{{ebauche.longueur}}</td> <td class="case">{{ebauche.ligne}}</td> </tr> {% endfor %} It's ok if i transmit a queryset but not with results function. How can i adapt result function to transmit to my template? Please help me. -
GAE Stackdriver: SOURCE_LOCATION_ERROR (No code found at...)
I'm debugging a custom django command by using GAE Stackdriver Debug. It's used the GAE source code: I published a new version and I see the updated files in GAE, but executing the command via python manage_gae.py gives a SOURCE_LOCATION_ERROR: No code found at line ... in /base/data/home/apps/e~my_project/.../my_command.py. Try lines ... -
u' admin' is not a registered namespace in django
I am writing an application for django admin and everything seems to be going well till I used admin: in url on my templates and I got error u' admin' is not a registered namespace I am using the latest django version as at october 2017 html {% extends "admin/base_site.html" %} {% load staticfiles %} {% block extrastyle %} <link rel="stylesheet" type="text/css" href="{% static " css/admin.css " %}" /> {% endblock %} {% block title %} Order {{ order.id }} {{ block.super }} {% endblock %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url " admin:index " %}">Home</a> &rsaquo; <a href="{% url " admin:orders_order_changelist " %}">Orders</a>&rsaquo; <a href="{% url " admin:orders_order_change " order.id %}">Order {{ order.id }}</a> &rsaquo; Detail </div> {% endblock %} admin.py def order_detail(obj): return '<a href="{}">View</a>'.format( reverse('orders:admin_order_detail', args=[obj.id])) order_detail.allow_tags = True urls.py url(r'^admin/', admin.site.urls), app urls.py url(r'^admin/order/(?P<order_id>\d+)/$', views.admin_order_detail, name='admin_order_detail'), further codes would be provided on request -
djando ManyToMany models views and templates
I have the Gammer model that is User extension and the Competition model. many users can play a competition and a competition can have many users (ManyToMany) class Gammer(User): competition=models.ManyToManyField(Competition) puntaje_global = models.IntegerField(default=0) ranking = models.IntegerField(default=0) class Competition(models.Model): name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) finish_date=models.DateTimeField(blank=True, null=True) duration = models.DurationField(blank=True,null=True) def finish(self): self.finish_date = timezone.now() self.save() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name Add in admin.py: admin.site.register(Gammer) The admin can view player competitions (users) or assign them competencies Now I want the players (users) can register the competitions(choose competitions). How do I continue? -
django.db.utils.IntegrityError: (1048, "Column 'category_id' cannot be null")?
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') import_goods_data.py from apps.goods.models import Goods, GoodsCategory, GoodsImage from db_tools.data.product_data import row_data for goods_detail in row_data: goods = Goods() goods.name = goods_detail['name'] goods.market_price = float(int(goods_detail['market_price'].replace('¥', '').replace('&', ''))) goods.shop_price = float(int(goods_detail['sale_price'].replace('&', '').replace('元', ''))) goods.goods_brief = goods_detail['desc'] if goods_detail['desc'] is not None else '' goods_goods_desc = goods_detail['goods_desc'] if goods_detail['goods_desc'] is not None else '' goods.goods_front_image = goods_detail['images'][0] if goods_detail['images'] is not None else '' category_name = goods_detail['categorys'][-1] category = GoodsCategory.objects.filter(name=category_name) if category: goods.category = category[0] goods.save() in the goods.py, not 'category_id', why running 'import_goods_data.py' get the error: _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1048, "Column 'category_id' cannot be null") and must be add 'category_id'? -
Retrieving by a different parameter using DRFs ModelViewSet
How can I retrieve a user by username rather than the primary key while using the rest frameworks ModelViewSet? Here is my current view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Is there a way to refer to only some fields in a Django ForgeinKey?
I believe this is best explained by an example. So, I am making a program for saving weightlifting results for international and national competitions. Below is a (weight)lifter model: class Lifter(Person): # Changed from dateTime, as we don't need time of birth birth_date = models.DateField(null=True) gender = models.CharField(max_length=10, choices=Gender.choices(), null=True) club = models.ForeignKey('Club', null=True) I would like to connect the lifter model to the InterntionalResult model: class InternationalResult(models.Model): lifter = models.ForeignKey(Lifter, null=True) body_weight = models.FloatField(verbose_name='Kroppsvekt', null=True) # International group can be (for example) "A" or "B" group = models.CharField(max_length=5, verbose_name='kategori') snatch = models.IntegerField() clean_and_jerk = models.IntegerField() total = models.IntegerField() However, lifter has a ForeginKey to group (club = models.ForeignKey('Club', null=True)). When I connect Lifter to InternationalResult, I would like to exclude this ForgeinKey, but still connect Result to the rest of Lifter. This is because international competitions don't have clubs in the same way. Is there a way to do this, or should I just create a new InternationalLifter-model? Thank you for your time! -
Paho MQTT and Django - Working, but Many Errors
I have a Django application. This application is meant to get data and display it to the user. I have chosen (for the moment) to use MQTT as my method of passing information between my Django application and a separate server that collects data. When a user loads a page, an AJAX request is made (seen below) to request data. My goal is to make the AJAX request, subscribe to a topic, and have my other server publish a message to that topic. When the message is received, I return it as JSON to the template. Now, this may be a little backwards, as I am turning MQTT into a request/response architecture, which is not what it was designed for - but MQTT solves some other problems for me. I any case, the solution you see below works - but it has some errors. Load a page works perfectly fine. The request is made, it is blocked until a response is received, and then the response is returned as a JsonResponse and is displayed to the user. But, if the page is refreshed while the first request is being made (so a number of refreshes in a row) then a …