Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template render is taking more time
my website is veryslow when i want to check the reason i used the django toolbar to check it out and found that the template is taking more than 80% of the time to consume. [Image for reference][1] also attached the timing Templates Name Average Times Total time Min Max Queries Query Duration rest_framework/api.html 822.4 ms 1 822.4 ms 0 ms 822.4 ms 0 0 ms rest_framework/raw_data_form.html 465.1 ms 1 465.1 ms 0 ms 465.1 ms 0 0 ms rest_framework/horizontal/form.html 326.2 ms 1 326.2 ms 0 ms 326.2 ms 0 0 ms django/forms/widgets/select.html 161.1 ms 3 483.2 ms 0 ms 187.1 ms 0 0 ms django/forms/widgets/select_option.html 40.1 ms 9 361.1 ms 0 ms 52.0 ms 0 0 ms django/forms/widgets/textarea.html 39.0 ms 3 117.0 ms 0 ms 52.0 ms 0 0 ms django/forms/widgets/attrs.html 19.1 ms 15 286.0 ms 0 ms 26.0 ms 0 0 ms rest_framework/horizontal/input.html 13.8 ms 18 248.2 ms 0 ms 26.0 ms 0 0 ms rest_framework/horizontal/textarea.html 13.0 ms 3 39.0 ms 0 ms 13.0 ms 0 0 m this is the time rendered by each template how can improve the performace. -
CheckboxSelectMultiple Django extract if checked or not
I'm learning the django framework and i'm stuck on the "CheckboxSelectMultiple", i dont know how to extract what the user selected and what not. for example, my forms.py: from django import forms FAVORITE_COLORS_CHOICES = ( ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ) class MyForm(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) my views.py: from accounts.forms import MyForm def my_view(request): form = MyForm(request.POST or None) if request.method == "POST": if form.is_valid(): try: if request.POST["favorite_colors"]: print(request.POST["favorite_colors"]) except: print(request.POST["favorite_colors"]) return render(request, 'accounts/form.html', {'form': form}) currently, it print me the last selected checkbox, how can i check if specific checkbox was selected? (for example 'if request.POST["favorite_colors.blue"]: print('blue')' or something like that). thanks! -
Access related manager method from another manager
I am trying to access a manager method from a manager of a related model but I'm having no success. Let's say these are my models: class ModelA(models.Model): description = models.TextField(blank=True) objects = ModelAQuerySet.as_manager() class ModelB (models.Model): a = models.ForeignKey(ModelA, related_name='a_objs') objects = ModelBQuerySet.as_manager() And I am defining the managers as QuerySets, that is: class ModelAQuerySet(models.QuerySet): def description_starts_with(self, desc): return self.filter(description__startswith=desc) class ModelBQuerySet(models.QuerySet): pass What I would to do is to create a ModelBQuerySet method that prefetch modelA objects starting with a certain description. Here's a WRONG example of what I am trying to do: class ModelBQuerySet(models.QuerySet): def prefetch_a_objs_starts_with(self, desc): return self.prefetch_related( Prefetch('a_objs', queryset=ModelAQuerySet.description_starts_with(desc), to_attr='a_objs_with_desc')) This of course doesn't work because description_starts_with is an instance method, and here I am invoking it from the class. Even this is completely wrong I hope it gets the idea of what I'm trying to do. Question is: how to create a models.QuerySet method with a prefetch that can access its related models.QuerySet instance methods? -
docker tmpfs seems to have no effect on postgresql
I have a Postgres database inside a docker container against which I run django tests. I want to improve the speed of the tests. The easiest way to do this (it seems to me) is to move postgres data into tmpfs volume. Here's what I did: docker run --name my_tfmps_test -d -p 5432:5432 \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=my_database \ -e PGDATA=/var/lib/postgresql/data \ --tmpfs /var/lib/postgresql/data \ library/postgres Because I specified --tmpfs I expect the tests run significantly faster. Unfortunately this is not the case. The speed of the tests remains exactly on the same level (give or take 5%). My questions is: why did the speed of the tests did not change? And what can I do about it ? Extra info: MacOS 10.13.6 reference https://docs.docker.com/storage/tmpfs/ -
django.db.utils.OperationalError: no such table
I'm upgrading a Django project from 1.8 to 1.9, I deleted the database file and all cache files, then I tried to run python manage.py makemigrations or python manage.py makemigration --run-syncdb but always raise this error django.db.utils.OperationalError: no such table: it works fine on django1.8 without any error! Are there any edits or updates should I make in Settings.py? -
Django model formset - filter foreign key field
I have a ModelFormSet which has a foreign key field. I would like to filter this, so it does not displays ALL foreign key attributes: models: class ClinicallyReportedVariant(models.Model): vasr_id = models.ForeignKey(VariantAnnotationSampleRun, on_delete=models.CASCADE, db_column='vasr_id', related_name='vasr_id', null=True, blank=True) reported = models.BooleanField(default=False) date_reported = models.DateTimeField(auto_now=False, null=True, blank=True) views: CRVFormSet = modelformset_factory( ClinicallyReportedVariant, exclude=('clinically_reported_sample_id',), ) formset = CRVFormSet() I want to filter the CRVFormSet based on the VariantAnnotationSampleRun model. How can I do this? The ClinicallyReportedVariant table is empty - so I do not want to filter based on the formset queryset -
Group By in django 1.8
I have the next structure in my django app: class A(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) time = models.DateTimeField(auto_now_add=True) I want select the earliest time of each name, in database like: id name time 1 a 2018-09-10 2 a 2018-09-11 3 b 2018-09-10 4 b 2018-09-11 Then the result should be: id name time 1 a 2018-09-10 3 b 2018-09-10 I know raw-sql is a solution, but is it possible to use django query expressions? I'm using django 1.8. Any help please. -
Django token : download server files with token authentification
I'm looking for set token authentification in order to download server files with secure way and add after an expiration time. Requirements : Django 1.11 Ubuntu 18.04 Database PostgreSQL Process : User fills a form with some informations CustomerForm(email, firstname, lastname and country) and he has to choose one or several document(s) with checkboxes. When form is submitted, I create an object with user informations + document choosen + token generated from email + document_id + datetime in sha1 format. User gets an email with download link according to previous document(s) (1 email per document). Expected : In this part I will explain what I would like to do, but I don't know how it's possible and this part is still fuzzy in my head. It's the first time I'm trying to do that. User receives an email with url link based on token generated previously. When he clicks into the link, there is an authentification process which let to confirm user and open a window in order to download document file. But, after few time (maybe 10 minutes) the token is expired and user have to submit the form a new time in order to get document file link. … -
Problem with Django UpdateView and inline_formsets
I'm new with Django and run into trouble with Django UpdateView and Formsets. I don't understand, why to set fs.instance.be = company in my post-method, but this leads to a new entry in db not an update. Wthout this line, no saving. What's wrong here? Thanks in advance. My Code: #models.py from django.db import models # A base class for Client and Company for joining Address and Telephone etc. here class BusinessEntity(models.Model): name = models.CharField(max_length=30) class Address(models.Model): be=models.ForeignKey(BusinessEntity,on_delete=models.CASCADE) street = models.CharField(max_length=256) #some more here class Telephone(models.Model): be=models.ForeignKey(BusinessEntity,on_delete=models.CASCADE) number = models.CharField(max_length=30,null=True,blank = True) class Client(BusinessEntity): title = models.CharField(max_length=30) firstname = models.CharField(max_length=30) class Company(BusinessEntity): customer_no=models.CharField(max_length=20) #----------------------------------------------------------------------- #forms.py from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import Address,Telephone,Client,Company class CompanyForm(forms.ModelForm): class Meta: model = Company CompanyAddressFormset = inlineformset_factory(Company, Address ) CompanyTelephoneFormset = inlineformset_factory(Company, Telephone ) #----------------------------------------------------------------------- #views.py from django.views.generic import CreateView, UpdateView class CompanyEditView(UpdateView): template_name = 'imsApp/company_edit_form.html' model= Company form_class = CompanyForm success_url = '/imsApp/manage/company/info' def get_object(self, queryset=None): return Company.objects.get(id=self.kwargs['company_id']) def get(self,request,**kwargs): self.object = self.get_object() form_class = self.get_form_class() company_form = self.get_form(form_class) address_form = CompanyAddressFormset(instance = self.object) telephone_form = CompanyTelephoneFormset(instance = self.object) return self.render_to_response(self.get_context_data(company_form=company_form,address_form=address_form,telephone_form=telephone_form)) def post(self,request,**kwargs): self.object = self.get_object() form_class = self.get_form_class() company_form = self.get_form(form_class) qsAddress = Address.objects.filter(be = self.object) qsTelephone = … -
when I use get method I get matching query doesn't exist, but there should be a matching query
When I use filter method instead I get index out of range, which I also don't understand. Did I set the whole view, model and url wrong? in my models.py class Drama(models.Model): class Season(models.Model): drama = models.ForeignKey('Drama', on_delete=models.CASCADE) class Content(models.Model): season = models.ForeignKey('Season', on_delete=models.CASCADE) now in my urls.py as you can see they have foreignkey relationship, I want my url to have domain/kdrama/s1e1 so I have set the url in the following manner path('<slug:slug1>/<slug:slug2>', views.contents, name='contents'), The problem I have is in views.py which is suppose to retrieve data seasons method works fine def seasons(request, slug): seasons = Season.objects.filter(drama__name=slug) return render(request, 'seasons.html', { 'seasons':seasons, }) problem is this one, I want the contents to be filtered based on the seasons. So for instance, I have season1 under kdrama then the contents related to that filed to show up. I tried this way but I'm not sure why I'm getting matching query doesn't exist error....I am filtering contents based on the season name just like I did for the seasons method. Is this a database problem?or my logic is just terribly wrong? def contents(request, slug1, slug2): contents = Content.objects.get(season__name=slug1) return render(request, 'contents.html',{ 'contents':contents, }) -
Authenticate not working with right credentials
I can't authenticate a user I just made. This post is alike but there are no answers. try: User.objects.get(username=USERNAME) user = authenticate(username=USERNAME, password=PASSWORD) print(user) except User.DoesNotExist: User.objects.create_superuser(USERNAME, EMAIL, PASSWORD) user = authenticate(username=USERNAME, password=PASSWORD) print(user) But when I set a breakpoint on any of the prints the user object is none. I also tried AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) but there was no difference -
what django process saves processed values from one model to another model ?
class ledger1(models.Model): Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) group_Name = models.ForeignKey(group1,on_delete=models.CASCADE) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2) class journal(models.Model): Date = models.DateField() To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,) Credit = models.DecimalField(max_digits=10,decimal_places=2) i have these two models that take data from the user. I want to process data from journals using django query => select those journal names which matches some ledger1.name for any particular date range, also filter all transactions in which the ledger name exists in By field, and aggregate their 'To' side debit total and save it to another class closing balance. -
Django-Channels 2 Apache CentOS 7 deploy
I can't make Apache serve websockets through Daphne. The requirements.txt Django==2.0.7 channels==2.1.3 asgiref==2.3.2 redis==2.10.6 settings.py CHANNEL_LAYERS = { "default":{ "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost"), 6379], }, "ROUTING": "myapp.routing.channel_routing", }, } ASGI_APPLICATION = "myapp.routing.application" routing.py #..imports websocket_urlpatterns = [ url(r"", MyConsumer), ] application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ) ) }) asgi.py #.. imports os.environment.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") django.setup() application = get_default_application() MyConsumer.py #..imports class MyConsumer(WebsocketConsumer): def websocket_connect(self, event): Logger.log("Connected " + json.dumps(event)) self.send({ "type": "websocket.accept" }) def websocket_receive(self, event): Logger.log("Receive " + json.dumps(event)) def websocket_disconnect(self, event): Logger.log("Disconnected " + json.dumps(event)) httpd.conf #... RewriteEngine on RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC, OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* ws://127.0.0.1:9001%{REQUEST_URI} [P, QSA, L] supervisord.conf ;... [fcgi-program:asgi] socket=tcp://127.0.0.1:9001 command=/var/www/venv/bin/daphne -u /run/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myapp.asgi.application numprocs=2 process_name=asgi%(process_num)d directory=/var/www/venv/myapp/ autostart=true autorestart=true stdout_logfile=/tmp/asgi.log redirect_stderr=true In javascript, I just try to connect: var location = window.location var socket = new WebSocket('ws://' + location.host + ':9001' + location.pathname) socket.onopen = function(e){ console.log('open', e) } socket.onerror = function(e){ console.log('error', e) } socket.onclose = function(e){ console.log('close', e) } Each time the page is accessed it gives WebSocket connection to 'ws://127.0.0.1:9001/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET after a while and prints the error and close messages in … -
Django - Taking of object model by select tag and passing this object to another view
I'm struggling with the following problem. In my project I have the following model: models.py class InputSignal(models.Model): name = models.CharField(max_length=512) author = models.ForeignKey(User, on_delete=models.CASCADE) adnotations = models.TextField(blank=True, null=True) input_file = models.FileField(upload_to='signals/', null=False, validators=[validate_file_extension]) add_date = models.DateTimeField(default=datetime.now()) last_edit_date = models.DateTimeField(default=datetime.now()) last_json_results = models.FileField(upload_to='resuts/') objects = models.Manager() def delete(self): self.input_file.delete() super().delete() def __str__(self): return self.name def add_date_pretty(self): return self.add_date.strftime('%b %e %Y') Two url addresses: urls.py path('display/list', displayviews.display_list, name='display-list'), path('display/details/<int:signal_id>', displayviews.display_details, name='display-details'), And two view functions: views.py def display_list(request): signals = InputSignal.objects.filter(author=request.user) return render(request, 'display_list.html', {'signals': signals}) def display_details(request, signal_id): signal = get_object_or_404(InputSignal, pk=signal_id) The template of the first function of the view at this moment looks like this: display_list.html <div class="row mt-2"> <div class="col-lg-1"></div> <div class="col-lg-10"> <select class="form-control mt-2 text-center"> {% for signal in signals %} <option> <h2>{{ signal.name }}</h2> </option> {% endfor %} </select> </div> <div class="col-lg-1"></div> </div> <div class="row mt-3 mb-2"> <div class="col-lg-4"></div> <div class="col-lg-4"> <a href="{% url 'storage-main' %}" class="btn btn-outline-success btn-block">Perform Analysis</a> </div> <div class="col-lg-4"></div> </div> I would like based on the structure of this template to design a solution that after selecting the signal name from the select tag and clicking the 'perform analysis' button, go to the next view - display_details (request, signal_id). Where I will … -
django-telegrambot doesn't catch all forwarded messages using WEBHOOK mode
I use django-telegrambot package to make anti-spam telegram bot. The mode for the bot is WEBHOOK I have some functionality to remove all forwarded messages from chat. My code looks like: if update.message.forward_from or update.message.forward_from_chat: bot.delete_message(chat_id=update.message.chat_id, message_id=update.message.message_id) return the code above doesn't work very well, for example when I select a few messages and send them to channel, it deletes only one(sometimes two) messages from forwarded set, sometimes it even doesn't delete if I forward one message, I checked if we always have forward_from and forward_from_chat when forwarding, yes -- we always have it, also I thought I just have some amount of pending_update_count, but it's 0 I know django-telegrambot based on python-telegram-bot package when I have the same code using only python-telegram-bot and run it locally like python main.py it works perfect(catch and delete all forwarded messages) Did someone face with such error here? Any thinks/suggestions? Thanks! -
django - I don't see anything from database when i want to display the contents on cards/index page
django - I don't see anything from database when i want to display the contents on cards/index page. in the admin section it's working but here not working. BTW sorry my bad communication urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_id_cards), ] views.py from django.shortcuts import render from .models import IdCard def all_id_cards(request): cards = IdCard.objects.all() return render(request, 'cards/cards_index.html', { 'cards': cards }) models.py from django.db import models # Create your models here. class IdCard(models.Model): emp_id = models.CharField(max_length=12) emp_name = models.CharField(max_length=40) emp_title = models.CharField(max_length=30) emp_telephone = models.CharField(max_length=12) emp_email = models.CharField(max_length=30) emp_generation = models.CharField(max_length=20) emp_status = models.CharField(max_length=20) def __str__(self): return self.emp_name cards_index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Homepage</title> </head> <body> <h1>Identity Cards</h1> <div class="identitycards"> {% for cards in cards %} <div class="identitycard"> <p>{{ IdCard.emp_name }}</p> </div> {% endfor %} </div> </body> </html> -
Django; How can I refer to image's width and height?
I'm trying to test a validator. I need to get the image's width and height but I cannot refer. How can I do it? models.py is like this. class CustomUser(AbstractUser): objects = CustomUserManager() photo = models.ImageField( upload_to='users/photo', blank=True, null=True, validators=[validate_profile_image], ) and I create model using factory boy. class CustomUserFactory(factory.django.DjangoModelFactory): class Meta: model = CustomUser and then I want to set image's width and height when I test the model and validator. class TestValidators(TestCase): def test_valid_profile_image(self): user0 = CustomUserFactory() #I want to set user's photo here with width and height. def test_invalid_profile_image(self): user1 = CustomUserFactory() Anyone who could give me tips? -
Django - Use Primary Key as a Foreign for another table when adding data into the database
I have an html file which has two text areas. Each of the text area is linked to two different tables in a database. Textarea one is linked to 'Question' table, and Textarea two is linked to 'Response' table. Right now, both the tables are linked to the database. However, the response table have a foreign key(Question_id) which is the primary key of the question table, therefore if I add the question and the response, the foreign key in response table should automatically take in the new question_id as its foreign key, therefore linking the question and the response together. Is there anyway I can do this? I am using Django framework. Views.py def adddata(request): addmoreData = Response.objects.all() if request.method == 'POST': if request.POST.get('addquestion'): question=Question() question.Statement=request.POST.get('addquestion') question.save() if request.POST.get('addresponse'): response=Response() response.Response=request.POST.get('addresponse') response.save() return render(request, 'app/adddata.html') else: return render(request, 'app/adddata.html', {}) Models.py class Question(models.Model): Statement = models.TextField(default='Question') def __str__(self): return self.Statement class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Response = models.TextField(default='Response') def __str__(self): return self.Response HTML <td> <div class="form-group"> <label for="addQuestion"><b>Please enter the question here:</b></label> <textarea class="form-control" required id="addQuestion" rows="3" placeholder="Question..." name="addquestion"></textarea> </div> </td> <td> <div class="form-group"> <label for="addResponse"><b>Please enter the response here:</b></label> <textarea class="form-control" required id="addResponse" rows="3" placeholder="Response..." name="addresponse"></textarea> </div> </td> … -
How do i send email to user to reset password without explicitly filling PasswordResetForm?
I am making a Django web app using 1.11.2 version in which admin is registering users using default django authentication views and customized html templates.I want that when admin clicks on 'Register' and submits the details (like username,email,password and confirmed password) an email is simultaneously sent to user's email-id in which there is a link to reset password so that user can reset his/her password.I don't want to explicitly use password_reset_view and password_reset_done view unless i am using forgot password option. Here what i have coded. views.py from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import Permission, User from django.contrib.auth.views import RegisterView class RegisterView(SuccessMessageMixin, CreateView): form_class = RegisterForm template_name = 'registration/register.html' success_message = "Your account was created successfully." def dispatch(self, *args, **kwargs): return super(RegisterView, self).dispatch(*args, **kwargs) register.html {% extends "base.html" %} {% block nav_people %} class="active" {% endblock %} {% block content %} {% load static %} <!DOCTYPE html> <html lang=en> <head> <link rel="stylesheet" href="{% static "dashboard/css/login.css" %}"/> </head> <body> <title>Register</title> <div class="reg"> <div class="regbox"> <h1>Register</h1> <br> <form class='text-left' method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Register" /> <input type="hidden" name="next" value="{{ next }}" /> </form> </div> </div> </body> </html> {% endblock … -
Django - how to restrict DeleteView to object owner
I'm trying to implement a DeleteView and prevent the model from being deleted if the user is not the owner. I'm sure it's a pretty trivial task but i can't manage to find a clear answer. So far I can see my view but currently everyone can delete the object. Here is my code : views.py : @method_decorator(login_required, name='dispatch') class RestaurantDeleteView(DeleteView): model = Restaurant template_name = 'restaurant/delete_form.html' success_url = '/' models.py : class Restaurant(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) category = models.CharField(max_length=200) description = models.TextField() capacity = models.IntegerField(default=0) def get_absolute_url(self): return reverse('detail', kwargs={'pk': self.pk}) Thanks in advance ! -
Django: How do I pass a for variable into a querystring?
I'm attempting to fix some pagination issues in a Django app. Using the Previous and Next buttons work fine, since I'm using existing variables like previous_page_number, but I'm unsure how to get the Page 1, Page 2, Page N buttons to work. Here's the Previous Page code, which works just fine: {% if table.page and table.paginator.num_pages > 1 %} {% block pagination %} <nav class="pagination is-centered" role="navigation" aria-label="pagination"> {% block pagination.previous %} {% if table.page.has_previous %} <a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}" class="pagination-previous">Previous</a> {% else %} <a href="#" class="pagination-previous" disabled>Previous</a> {% endif %} {% endblock pagination.previous %} And here's my current Pagination Range code, which doesn't. Specifically, the else segment is what I'm unable to get working. {% block pagination.range %} {% if table.page.has_previous or table.page.has_next %} <ul class="pagination-list"> {% for p in table.page|table_page_range:table.paginator %} {% if table.page.number == p %} <li> <a class="pagination-link is-current is-dark" aria-label="Page {{ table.page.number }}" aria-current="page">{{ table.page.number }}</a> </li> {% else %} <li> <a href="{% querystring table.prefixed_page_field=table.page.p %}" class="pagination-link" aria-label="Page {{ p }}">{{ p }}</a> </li> {% endif %} {% endfor %} </ul> {% endif %} {% endblock pagination.range %} Currently, the pagination doesn't work, and the URL that gets passed ends at page= instead of … -
Type error at admin/articles/article/add Tuple does not support the buffer interface in django
I am encountering an error in django. i created a Imagefield in django for uploading images and also downloaded pillow package. Now when i upload the image in django admin it gives the error: Type error at admin/article/article/add Tuple does not support the buffer interface . please help me out i had also done all the required settings in settings.py -
Django formset - how to give a different queryset for each form within the modelformset
I have a form for a Model - ClinicallyReportedSample, which links to a Sample model. I am trying to create a formset for ClinicallyReportedSample where, based on a queryset of Sample, a specific amount of forms are displayed so that the user can add data. Currently, the Sample model has entries, but the ClinicallyReportedSample model is completely empty: models: class Sample(models.Model): request_number = models.PositiveIntegerField() year = models.PositiveIntegerField() class Meta: db_table = "sample" unique_together = (('request_number', 'year'),) def __str__(self): return("%s/%s" %(self.request_number, self.year)) class ClinicallyReportedSample(models.Model): sample_id = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample_id') reported = models.BooleanField(default=False) evidence = models.TextField(null=True, blank=True) ... other fields ... class Meta: db_table = "clinically_reported_sample" unique_together = (('sample_id'),) def __str__(self): clinically_reported_sample = str(self.sample_id) return(clinically_reported_sample) I want ClinicallyReportedSample model forms, within a formset, that relate to a queryset of Sample model. For example, Sample objects with pk 1, 2 and 3: forms.py: class BaseCRSFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.queryset = ClinicallyReportedVariant.objects.none() class CRSForm(forms.ModelForm): class Meta: model = ClinicallyReportedSample fields = ('sample_id', 'evidence',) def __init__(self, *args, **kwargs): super(CRSForm, self).__init__(*args, **kwargs) So I try to do this using queryset in my formset views.py: def get(self, request, *args, **kwargs): sample_obj = Sample.objects.filter(id__in=[1, 2, 3]) formset = modelformset_factory( ClinicallyReportedSample, form=self.crsform, formset=BaseCRSFormSet, extra=3, ) … -
Celery - Django - 'null value in column "result" violates not-null constraint'
I'm working on a django project using celery to queue differents tasks. Mostly we use it for mail sending, and we have plenty of tasks that are currently working under the same method. The things is that I'm having an error on production because suddenly celery doesn't save any values on the result field of the Task model. Hope this info is enough, if not, please ask. This is the traceback: Task users.tasks.send_reset_password_task with id cf6ddab4-4407-477e-80e5-a5e50fbe4a90 raised exception: 'IntegrityError(\'null value in column "result" violates not-null constraint\\nDETAIL: Failing row contains (524, 2018-09-10 13:26:13.528034+00, {"errors": [{"error_code": 0, "error_data": {"user_id": 3298, "e..., 3298, 59, null, null).\\n\',)' Task was called with args: [272, [3298]] kwargs: {u'_schema_name': u'tgs'}. The contents of the full traceback was: Traceback (most recent call last): File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/app/users/tasks.py", line 618, in send_reset_password_task log_event(user=user, event_type=EventLogTypes.RESET_PASSWORD_EMAIL_SENT, success=success, extra={'errors': errors}) File "/app/lmsplatform/services_eventlog.py", line 937, in log_event campaign_id=campaign_id, File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 399, in create obj.save(force_insert=True, using=self.db) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, … -
TinyMCE deletes new line symbols from text
I'm trying to figure out what is wrong with my code. I have a textarea on a page that's being filled with text automatically and tinymce formats it by changing '\n' on '<p></p>'. I checked backend code it sends text with new lines. But once it gets to .js scipt new lines are suddenly vanished, and it only changes the first one. // Set title $('#title').val('').val(post.title).trigger('change'); // Set description $('#description').val('').val(post.description).trigger('change'); // Set text tinyMCE.get('text').setContent(''); tinyMCE.get('text').setContent(post.text.replace('\n', '</p><p>').replace('<p></p>', '')); Can someone please tell me what might be wrong. Cause if I make a breakpoint while .js is running I see that text has new lines and if I paste it mce parses new lines.