Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-parler IntegrityError when add new object in admin
I have this error when try to save new object. Trying to ask google, nothing helpful. I think my problem is different id for Product and translation table, but i don't know how to fix this. Sorry for my english. django==1.10.7 django-parler==1.8 Exception Type: IntegrityError Exception Value: insert or update on table "pcart_catalog_product_translation" violates foreign key constraint "pcart_catalog_pr_master_id_571a2ec0_fk_pcart_catalog_product_id" DETAIL: Key (master_id)=(a74f5571-512d-4bd5-9164-0388dd22bcd8) is not present in table "pcart_catalog_product". This is part of my object: class Product(TranslatableModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(_('Slug'), max_length=255, unique=True) external_id = models.CharField( _('External ID'), default='', blank=True, max_length=255, db_index=True) translations = TranslatedFields( title=models.CharField(_('Title'), max_length=255), description=HTMLField(_('Description'), blank=True), page_title=models.CharField(_('Page title'), max_length=255, blank=True), meta_description=models.TextField(_('Meta description'), blank=True), meta_keywords=models.TextField(_('Meta keywords'), blank=True), meta_text=models.TextField(_('Meta text'), blank=True), ) This is language and parler settings: LANGUAGE_CODE = os.environ.get('LANGUAGE_CODE', 'uk') LANGUAGES = [ ('uk', 'Українська'), ] USE_I18N = True USE_L10N = True USE_TZ = True PARLER_LANGUAGES = { SITE_ID: ( {'code': 'uk',}, ), 'default': { 'fallbacks': ['uk'], 'hide_untranslated': False, } } -
billiard.pool map function getting a hang
I need to run my logic parallelly using all available CPUs, for that I am using billiard package for pooling, PFB my technology stack - -Python 3 -Django==2.0.5 -Django rest from work -celery==4.2.0 My problem is, when I am hitting my rest-API and triggering my celery task it executes till pooling line but after that, its getting hang, I am not getting any error message but It is not moving further. PFB my project structure: -cdm |cmdapp | | | |helper | | |aaa.py | |tasks | | |bbb.py | |api | |ccc.py |cdm | |settings.py |manage.py PFB my code example: #cmdapp.helper.aaa.py from billiard.pool import Pool class A(): def squre(self,number): return number*number def calculate(self,number_list): pool = Pool() result = pool.map(self.squre, number_list) return result #cmdapp.tasks.bbb.py from celery import task from cmdapp.helper.aaa import A @task def calculation_task(number_list): a_obj=A() result=a_obj.calculate(number_list) #cmdapp.api.ccc.py from rest_framework.views import APIView from rest_framework import status, permissions from rest_framework.response import Response from cmdapp.tasks.bbb import calculation_task class C(APIView): def get(self, request): range_list=range(1000) calculation_task.delay(range_list) return Response({ "result": "success", }, status=status.HTTP_200_OK) I went through some articles where they have mentioned unpickable function cannot be called by pool.map function. Here I am not getting my function is pickable or unpickable and why It is … -
how to fix error - No module named 'cryptography'
when I run command python manage.py runserver I got an error also I try to install cryptography on virtual environment by command pip install cryptography. It says successfully installed the cryptography with following message. But still I am not able to avoid the message No module named 'cryptography' when I run the server on AWS instance. Please help me to fix this issue. -
I cannot use mysql at Mezzanine
I'm almost new with mezzanine. Earlier, I was trying to create Datebase with this code. $ python manage.py createdb Then, happpened an error. Here is each versions and environments. Environments pc: mac os 10.13.1 Versions python: 3.6.2 mezzanine: 4.3.1 django: 1.11.16 mysqlclient: 1.3.13 And, here is the error. Traceback (most recent call last): File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 26, in <module> import MySQLdb as Database File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib Referenced from: /Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/{ThisIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in … -
Django is installed but python3 does not find it
I'm having problems running Django. I installed it with pip3 and then it says: The script django-admin is installed in '/Library/Frameworks/Python.framework/Versions/3.5/bin' which is not on PATH. So I tried to modify my PATH in the bash.profile like this: export DJANGO=/Library/Frameworks/Python.framework/Versions/3.5/bin This did not help so as I ran in terminal: django-admin.py startproject firstdjango it just says: -bash: django-admin.py: command not found I don't know what to do to make it work. Any ideas? -
Django Model Save() method with related instance update
I am probably a medium Django user with quite a lot of RTFM under my belt. I have a workflow that is roughly this: Retrieve an account (model) object. Perform actions on the account object (update fields, etc.) Create a related usage (model) object using account as foreign key. Update the account object as part of a custom save() on the usage object. (Save any changes to account made in step 2). Models: class Account(models.Model): ... credit_balance = models.IntegerField(...) ... class Usage(models.Model): ... account = models.ForeignKey(Account, ...) credit_balance = models.IntegerField(...) ... def save( self, *args, **kwargs ): """Custom usage save to update account stats.""" if self.account: self.account.credit_balance = self.credit_balance self.account.save() Code in various functions / methods: account = Account.objects.get(pk=pk) [do something to account] usage = Usage.objects.create(account = account, tariff_short_name = account.tariff.short_name, **customer_data['usage']) What I am really struggling to work out is if I need to do: account.save() At this point, and what the implications are? It seems that the changes I have made to account (e.g. in step 2) are saved when I save the related account object in the usage object custom save method. Why? How does the usage object "know" what the current state of the instantiated account … -
I am not able to load image on my html on django
I am not able to load my image on my template html. Here is my code on models.py class Userimgmodel(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_img = models.ImageField(upload_to='profile_img',blank=True) def __str__(self): return self.user.username I have added the following in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'mynotes/media') Also in my urls.py urlpatterns = [ ....................//my paths//............ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And then in my template html <img src= "{{ user.userimgmodel.profile_img.url }}" width="250" height="250"> I added the image from admin panel and saved it. I got the folder media created on my project and within it there was the folder profile_img where the image which was uploaded was also present.It was all good till now, but when I try to display it on m webpage using above code, all I get is a rectangle with no image. -
selector in Javascript
I'm beginner in Javascript. I have a list of links and I want to select links end with .zip and add class zip from css; add select links end with not .zip and add class notzip from css. I use $("a[href $='.zip']").addClass("zip") to do the first task but cannot do the task 2 by add ! or not(). It is recommended by $this and location, filter function. How can I do that? <ul> <li><a href="a.html">a</a></li> <li><a href="b.pdf">b</a></li> <li><a href="c.zip">c</a></li> </ul> -
Django - Having trouble using foreign key model
TL;DR Accessing an objects foreign key, invoice must have one customer, how can I print an invoice and it's customer data? I'm making an invoicing system, so I have these models. class Customer(models.Model): name = models.CharField(max_length=100, default='') email = models.EmailField(max_length=100, default='') phone_num = models.CharField(max_length=10, default='') address = models.CharField(max_length=200, default='') def __str__(self): return str(self.id) class Invoice(models.Model): amount = models.FloatField(max_length=10, default=0) job_description = models.CharField(max_length=100, default="") date_of_issue = models.DateField(default='') customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name='cus') def __str__(self): return str(self.job_description + "\t$" + str(self.amount)) An Invoice has ONE and ONLY ONE Customer. I can easily print customers and invoices separately using templates. How can I access the customer which an invoice was sent to? If I want to look up an invoice, how can I get the customers name and contact details to print in a template? Currently I have displayed all of my invoices (looping through) and would like to show the customer name and ID number with the invoice information. How can I then do it backwards and search for all invoices belonging to customer 'x'? -
Django group permission activate
If you have django.contrib.auth in your INSTALLED_APPS django will automatically create add, change, delete and view permissions to every model in your system (or any one you add later). These are stored in auth_permission. In django doc, here is what we can read under Groups section: django.contrib.auth.models.Group models are a generic way of categorizing users so you can apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has the permissions granted to that group. For example, if the group 'Site editors' has the permission can_edit_home_page, any user in that group will have that permission. I've a group with no permission at all (call it NADA) and I've assign that group to a specific user (let's call him Pierre). Pierre can still connect and create, update, delete or view anything on my web interface. How can I make it working? There's few or no doc on the web for native Django Permission. I've read this nice publication django-permission-apps-comparison. I know I could install django-guardian, django-role-permissions or django-rules... I know we can manage access via middleware or decorator But since django IS creating these tables for us … -
How do i create a new form in inline formset by clicking a link
I created an inline relation between Reader and Book models. I imported the formset in my template successfully but I can not create a new Book form by clicking a link related to my addtext attribute in the below script. In otherwords , for one Reader I want to be able to create more than one Book form by clicking a link. <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'jquery.formset.js' %}"></script> <script type="text/javascript"> $('table.book tr.formset_row').formset({ addText: 'Add new Book', deleteText: 'Delete', prefix: 'reader_book_set', animateForms: true }); </script> The whole template is this: {% extends 'base.html' %} {% load bootstrap3 %} {% load static %} <!-- Latest compiled and minified JavaScript --> {% block content %} <div class="col-md-12 text-center"> <h2>Create / Edit Reader </h2> </div> <hr> <form class="well" method="post" action=""> {% csrf_token %} {% bootstrap_form form %} <table class="table book"> {{ formset.management_form }} {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in … -
django channels won't disconnect
I'm using channels to long-poll a database so I'm using the AsyncConsumer. I can't get the disconnect method to run when the webpage closes or is manually refreshed. I've tried creating def disconnect(self, close_code), def ws_disconnect(self, close_code), def websocket_disconnect(self, close_code), and I've tried them with and without async in front. I've also tried replacing the parameters with 'event'. When I first wrote the methods I included channels.exceptions.StopConsumer() but when that didn't work I placed a print statement inside my disconnect method just for testing and it appears that the disconnect method is never firing. Apologies if this is a stupid question but I've spent 3 days trying everything that I could find on the internet. When I close or refresh the page the terminal shows 'WebSocket DISCONNECT /page_name/ [127.0.0.1:35748] and then a few seconds later there's a message which states 'Application instance call() running at /home/ecl/.local/lib/python3.5/site-packages/channels/sessions.py:179> wait_for=> for connection took too long to shut down and was killed.' If anyone can give me any suggestions as to where to look for a solution to this I'd really appreciate it. -
How can I access the object User (django admin) using Group By and Join?
How can I access the object user (from django administration) when I use group by and join? That my query: Idea.objects.values("author_id").annotate( total=Count('author_id')) Running this query, I got this result: <QuerySet [{'author_id': 1, 'total': 6}, {'author_id': 2, 'total': 8}]> However, I can't access the values from User (default User model from django admin). In this case, I can access only author_id e total on my template: {% for d in ideas %} {{d.total}} - {{d.author_id}} {% endfor %} I can't do something like this: d.author.user.email My model: class UserProfile(models.Model): user = models.OneToOneField('auth.User', on_delete=models.PROTECT) use_term_accept = models.NullBooleanField(default=False) manager = models.NullBooleanField(default=False) def __str__(self): return self.user.username class Idea(models.Model): title = models.CharField(max_length=200) creation_date = models.DateTimeField('data criação') author = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, related_name='old_author') authors = models.ManyToManyField('users.UserProfile', related_name='authors') deleted = models.BooleanField(default=False) I did my best to be clear. If u have any question, I'm gonna answer it asap. -
Searching with Elasticsearch filters
I am using elasticsearch to do my search queries. An example would be to search for "graduates" and filter it by topics e.g. "Planit Training". Here is what the logic looks like now in views.py: responses = ResponseDocument20.search().filter(Q_ES("match", Response=cleanQ.lower())&Q_ES("match", Topic__Name=queryT)).extra(size=10000) However the topic filter, "Q_ES("match", Topic__Name=queryT)" is matching anything that has "Planit" in it, such as "Previous Planit Assignments" or "Planit Bootcamp", so it is returning extra results that i do not want. How would i query it so it only returns results that are linked to "Planit Training" only? -
django-shortcuts command prompt error 'C:\Program' is not recognized as an internal or external command, operable program or batch file
Trying to run "django r" command from a django shortcuts https://github.com/jgorset/django-shortcuts Getting the error 'C:\Program' is not recognized as an internal or external command, operable program or batch file Any ideas how to fix this? Found some questions with the same error 'C:\Program' error. Not sure how it could help in my case. Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file -
How to access node_modules with django compressor?
I'm using the Django compressor package. However I don't know the best way to access files from node_modules. For example I installed the following modules vie npm: "clipboard": "^2.0.1", "flatpickr": "^4.5.0", "highlightjs": "^9.12.0", "jquery": "^3.3.1", I don't think it's a good idea to put my node_modules folder in the static directory. How should I access the files from the node modules? -
Allow superuser to monitor CRUD (add/change/delete) history of staff user in Django admin
I know there is a history for model objects when auth users perform some kind of CRUD operation on them in the Django Admin. If this object still exists for the model, another user can see that same related history. However, if an auth user deletes an object, that object and its history are completely removed, and as far as I've been able to discern, there's no way to keep record of who made that delete/destroy request on the object as it is removed from the model database. That said, is there a way for an auth user, whether granted superuser access or not, to see the history of delete/destroy requests on a particular object from another user, after it is gone? Thank you. -
django redis with django showing ulimit error
Im trying to use redis on my django project and when i try to run thr server using 'redis-server' on the terminal i get the following errors 2280:C 23 Nov 15:19:57.938 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo 2280:C 23 Nov 15:19:57.938 # Redis version=4.0.9, bits=64, commit=00000000, modified=0, pid=2280, just started 2280:C 23 Nov 15:19:57.938 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf 2280:M 23 Nov 15:19:57.939 # You requested maxclients of 10000 requiring at least 10032 max file descriptors. 2280:M 23 Nov 15:19:57.939 # Server can't set maximum open files to 10032 because of OS error: Operation not permitted. 2280:M 23 Nov 15:19:57.939 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'. 2280:M 23 Nov 15:19:57.939 # Creating Server TCP listening socket *:6379: bind: Address already in use I have tried all solutions including setting the file max size etc ,still error persists.Any other solutions? -
Change the way image upload field renders from a form in django?
I have the following code in template: {{ form.profile_picture }} The Profile picture field in the form is derived from a model as Meta. The Model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) bio = models.TextField(max_length=100, blank=True) location = models.TextField(max_length=50, blank=True) date_of_birth = models.DateField(null=True, blank=True) profile_picture = models.FileField(default='default_pic.png') When the field is rendered on the webpage, it looks like this: I want to change this button to look somewhat different like an edit button. -
How to generate swagger for django rest api where my views are fucntion based view
I have search so many sites,even document but cannot find a complete steps to create swagger for function based views in django. Thanks in advance -
JSONField reference a model like One to One within the JSON
Stupid question time! :) I don't think this is possible but I need to ask in case I'm wrong. Is it possible to create a one to one relationship to a normal Django model in the JSON of a JSONField? Example: Django Model (Example): class TheModel(models.Model): example = models.CharField(max_length=255) something = models.CharField(max_length=255) dt = models.DateTimeField() Django model in separate app (Example): class JsonModel(models.Model): json_stuff = JSONField(default=list) The JSON itself will be a list of dictionaries of will have multiple layers but some need to hold a reference to the "TheModel" to be presented in a template (the same way a One to One relationship would). JSON (Example): [{"title": "A Title", "body": [{"line": "Some text", "reference": TheModel}, {"line": "More Text", "reference": None }]} It's looking like I'll have to loop through the JSON and insert the reference manually in the view. -
Django UpdateView without form to update object
I am using class based views with django 1.9 and I am trying to figure out how to update an object(After clicking a button) without using the form. I do not need any user input to update the object but I am still getting an error message that the template is missing. Can you help me? -
HTML doesn't see django form (django form doesn't render/display)
I created simple form in django. I tried do it in many different ways check all posibilities but still my HTML code doesn't see this form. Code looks like : forms.py from django import forms class TimeTable(forms.Form): title = forms.CharField(max_length=100, required=True) time_start = forms.DateTimeField() time_end = forms.DateTimeField() views.py from home.forms import TimeTable from django.shortcuts import render def schedule(request): if request.method == 'POST': form = TimeTable(request.POST) if form.is_valid(): pass else: form = TimeTable() return render(request, "registration/schedule.html", {'schedule_form': form}) urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), path('accounts/login/', TemplateView.as_view(template_name='registration/login.html'), name='login'), path('schedule/', TemplateView.as_view(template_name='registration/schedule.html'), name='schedule'), ] schedule.html {% block calendar %} <div class="calendar_create"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} </div> HTML only see this <button> mark rest is missing. I tried do it with many tutorials, django documentation and all this stuff doesn't work for me. What I'm doing wrong ? -
Can ForeignKey.limit_choices_to work for grandparent choices in Django 1.11?
I am using Django v1.11 I have the following relations: SubProject has many Quotation Quotation has many QuotationLineItem SubProject is many to many with Scope through ScopeInSubProject QuotationLineItem belongs to Scope via ForeignKey where the scope_id is default null So I like to ensure that when the user does assign a scope value, it's limited to the list of Scope records associated with its grandparent model (SubProject). For e.g. SubProject ABC is associated with Scope A1 and A2. A QuotationLineItem is associated with SubProject ABC indirectly via a Quotation record. Then when I try to save Scope for this very QuotationLineItem, I cannot save anything other than A1 and A2. I came across this concept called limit_choices_to, so I was wondering how do I use it in my specific case? If I don't use this concept, how do I ensure this restriction somehow? Do I write extra validation logic? -
How to use prismjs in django?
can someone tell exact how to use prismjs in django blog app. I tried but not working. I just want step by step guidence from very start to end. Thanks in advance !