Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku not migrating with new fields
I have been working on my local machine and I recently added some field to an existant model. I tried to push it this morning on Heroku and make the migrations and this is the message I get : My models.py Class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) complete = models.BooleanField(default=False) recurrence = models.BooleanField(default=False) urgence = models.BooleanField(default=False,verbose_name="Tâche urgente") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') Todo.reccurence is the new field. What I usually do is deleting database on my local machine and run migrate again but I really can't do that with real data. Thanks -
Django: RecursionError: maximum recursion depth exceeded
I am getting a runtime error in django while saving a certain model. I want to save the model with two instances So I have done the following: class Journal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') counter = models.IntegerField(blank=True,null=True) urlhash = models.CharField(max_length=100, null=True, blank=True, unique=True) date = models.DateField(default=datetime.date.today) voucher_id = models.PositiveIntegerField(blank=True,null=True) voucher_type = models.CharField(max_length=100,blank=True) by = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) narration = models.TextField(blank=True) My signal: @receiver(pre_save, sender=Journal) def pl_journal(sender,instance,*args,**kwargs): if instance.debit != None or instance.credit != None or instance.by.group1_Name.group_Name == 'Indirect Expense': Journal.objects.update_or_create(user=instance.user,company=instance.company,date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,to=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first(),debit=instance.debit,dredit=instance.credit) The problem is in the following line of code in my signal: to=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first() Anyone have any idea why this error is happening? Thank you -
DRF how to add to serializer field validation errors?
In the example below all fields are required. A post request with an empty phone and non matching passwords would result in only the not matching error - presumably because phone comes later when alphabetically sorted. How do you add to the serializer field errors instead of overriding them? IN: curl -X POST http://localhost:8000/register/ -d "password=not&password1=matching" OUT: {"password1":["Passwords do not match."]} class UserRegistrationSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) class Meta: model = User fields = ('password', 'password1', 'phone') extra_kwargs = { 'password': {'write_only': True}, 'password1': {'write_only': True}, } def create(self, validated_data): del validated_data['password1'] password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password: instance.set_password(password) instance.save() return instance def validate(self, attrs): if attrs.get('password') != attrs.get('password1'): raise serializers.ValidationError({'password1': ['Passwords do not match.']}) return attrs -
Implementing two factor in django
I'm trying to add two factor authentication to my django app. I'm following this library. As the doc says, i added the library to my Django settings and i added url(r'', include(tf_urls)), to my urls. I'm kind of stuck here, though, i don't really know how to go forward from here. Can anyone help me? -
Swagger UI API calls DRF and fails with status 406
There is an app which consists of 2 API layers. Django Rest Framework (DRF) There is a ViewSet which return the PDF content: class PDFReportViewSet(APIView): ... renderer_classes = (BinaryFileRenderer, ) ... response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s' % filename response.write(pdf) return response And it works perfectly fine. If I navigate to the link http://myserver/api/get-pdf it would download the PDF file. REST (based on Swagger) For the reasons I would not get into, there is another public API which is supposed to simply call the core API. There is a View: class PDFReportView(SwaggerView): def get(self, account, monitor_id): """ produces: ... - application/pdf responses: 200: description: Downloading a Monitor PDF report schema: type: file ... """ headers={ 'Accept': 'application/pdf', 'Content-Type': 'application/pdf' } return requests().get('http://myserver/api/get-pdf', headers=headrs) So basically swagger-rest thing simply calls the core (DRF) url and is supposed to return a PDF FILE to the user. Getting: { "detail": "Not Acceptable", "status_code": 406 } Response headers content-length: 56 content-type: application/json date: Wed, 06 Mar 2019 11:57:54 GMT rest-version: 2.28 server: Werkzeug/0.10.4 Python/2.7.12 Why it would return application/json if I set Content-Type and Accept to application/pdf everywhere and the http://myserver/api/get-pdf return a file as well? -
Django KeyError in ModelForm
I have a modelform in Django which is used in Django Admin site. It worked perfectly fine until some time ago I wanted to customise some fields and added a couple of lines in the model form init: if something_is_true: self.fields['myfield'].required = True Outcome of these few lines were unsuspected. I started getting KeyError('myfield') pointing to the line of code that I added every time I entered the edit form view in Django (of course, only in situation when something_is_true was in fact true). And here's the point where everything goes strange. Error doesn't occur on all envs. Some env are free from it, in others it shows. Also, some testers state that this error show randomly, but I don't want to make such assumptions. I was looking for a solution in web and found information that I shouldn't add such code to modelform init method. I've created a bugfix, but I need justification in order to push it. The error doesn't occur on local envs and testing envs - only on production and production-like envs. Even if my fix is correct, I'm not able to reproduce the bug and check if it really helps. Help me, Obi-Wan Kenobi. I … -
str' object has no attribute
when i want to create a new user i got this error Exception Value: 'str' object has no attribute 'get' Exception Location: D:\Dev\ecommerce\src\ecommerce\views.py in register_page, line 40 here is a code def register_page(request): signup_form = RegisterForm(request.POST or None) context = {"signup_form": signup_form} if signup_form.is_valid(): print(signup_form.cleaned_data) username = signup_form.cleaned_data.get("username") email = signup_form.cleaned_data.get("email") password = signup_form.cleaned_data.get("password") new_user = user.objects.create_user(username, email, password) print(new_user) return render(request, "auth/signup.html", context) -
Django DRF | Modify parent model field while creating a Child model
I have a User model and another Admin model which has a OneToOne relationship with User model. I am trying to modify a field in User model while an Admin model is being created. Here is my Serializer for admin model: class AdminSerializer(serializers.ModelSerializer): """A Serizlier class for vendor """ user = UserSerializer() class Meta: model = models.Admin fields = ('user', 'first_name', 'last_name', 'dob', 'gender') # This didn't work, also user_type is a field in User model and not Admin model read_only_fields = ('user_type',) def create(self, validated_data): # override this method <<< """ Since the "user" is a read_only field, the validated data doesn't contain it. """ # Line that causes the error. Trying to modify User model field validated_data['user_type'] = constants.Constants.ADMIN return super().create(validated_data) but I get an error: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer letzbargain_api.serializers.AdminSerializer, or set read_only=True on nested serializer fields How can I fix this? -
Bad email format with django
I am new in web development with django. And am testing a website for deployment but when I receive email from my contact page to my gmail account, I will see 'From me to me' instead of 'from sender to me'. Please see screenshot below: From me to me and when I open the email it looks like this when I open the email. Please someone should help me to fix this. Here is my django code: def contact(request): title = 'Contact us' form = ContactForm(request.POST or None) confirm_message = None if form.is_valid(): instance = form.save() subject = instance.subject name = instance.name email = instance.email comment = instance.comment message = ' From : %s\n\ Email : %s \n\ Message: %s ' %(name, email, comment) emailFrom = email emailTo = settings.EMAIL_HOST_USER send_mail(subject, message, emailFrom, recipient_list=[emailTo], fail_silently=True) title = 'Thanks!!' confirm_message = "Thanks for the message we will get right back to you" form = None context = { 'title':title, 'form': form, 'confirm_message': confirm_message, } return render(request, 'website/contact.html', context) -
URLSearchParams not working in internet explorer
I am trying to use URlSearchParams but it won't work on internet explorer, but it does with every other browser. Working version of code: if (location.search) { var params = new URLSearchParams(window.location.search); var entries = params.entries(); for (index of entries) { if (index[0] == 'q') { document.querySelector('input#searchBarMain').value = index[1] document.querySelector('input#filterSearch').value = index[1] } if (index[0] == 'min_cook_time') { document.querySelector('#cooking>input.minSlider').value = index[1] console.log('min_cook_time', index[0]) } if (index[0] == 'max_cook_time') { document.querySelector('#cooking>input.maxSlider').value = index[1] console.log('max_cook_time', index[0]) } if (index[0] == 'min_prep_time') { document.querySelector('#preperation>input.minSlider').value = index[1] console.log('min_prep_time', index[0]) } if (index[0] == 'max_prep_time') { document.querySelector('#preperation>input.maxSlider').value = index[1] console.log('max_prep_time', index[0]) } if (index[0] == 'min_servings') { document.querySelector('#servings>input.minSlider').value = index[1] console.log('min_servings', index[0]) } if (index[0] == 'max_servings') { document.querySelector('#servings>input.maxSlider').value = index[1] console.log('max_servings', index[0]) } } } I tried using a different for loop but this version did not work as I need to use the URLSearchParams. if (location.search) { var params = (window.location.search); for (let index = 0; index < params.length; index++) { if (index[0] == 'q') { document.querySelector('input#searchBarMain').value = index[1] document.querySelector('input#filterSearch').value = index[1] } if (index[0] == 'min_cook_time') { document.querySelector('#cooking>input.minSlider').value = index[1] console.log('min_cook_time', index[0]) } if (index[0] == 'max_cook_time') { document.querySelector('#cooking>input.maxSlider').value = index[1] console.log('max_cook_time', index[0]) } if (index[0] == 'min_prep_time') { document.querySelector('#preperation>input.minSlider').value = index[1] … -
Password Reset link redirecting to Explain Domain page
Reset password is redirecting me to this page But I also I am using .org domain. So if that problem is with this domain so what should I do? -
Get button name when clicked in Django
How can I get the name of a button when clicked ? Note that, the button is not in a form so I it does not work with `request.POST.get('button_name)'. My button is more of the form: <button onclick="location.href='{% url 'assigntask' %}'" type="button" name="Assign_Task">Assign Task</button> I tried: if request.POST.get('Assign_Task'): print "User Clicked Assign Task" -
Deploying a Django App on GAE with a custom Dockerfile
I am trying to use a custom image of Dockerfile to deploy my Django App on GAE. I am following the example provides by Google. However I have an issue on the last step : CMD gunicorn -b :$PORT main:app I have tried several things but it keeps saying my module is not found. What I have tried: CMD gunicorn -b :$PORT wsgi:app CMD gunicorn -b :$PORT myproject/wsgi:app CMD gunicorn -b :$PORT myproject.wsgi Thank you in advance for your help ! -
Celery restart causes redelivery of scheduled tasks in RabbitMQ
I have a celery worker which consumes tasks from a RabbitMQ broker. This works great until a restart of the worker. celery multi restart -A proj causes all the scheduled(Unacked) messages to become ready again which then immediately starts getting redelivered causing a delay in consumption of new incoming tasks depending on the number of the scheduled tasks. The speed of redelivery depends on the concurrency of the workers. -
Supplying StreamField with default value in Wagtail admin interface
By default, wagtail's StreamField looks something like this in the admin for empty fields, showing the different blocks available for the user: I would however prefer it to contain a block of my choosing by default. For example: How would I accomplish this? Setting a default keyword argument for the field didn't seem to work. -
Where is the celery default logs are stored?
Where is celery default logs get stored? I am starting celery worker with screen with no -f arguments. -
How to make a reply function for a comment django
I am making a blog but I am stuck on a comment replies function. I don't know how to make a Reply function from which users can reply to the comments. I tried a lot but it's still displaying those comments like other comments not as replies to that specific comment. Here,s the models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) pub_date = models.DateTimeField(auto_now_add = True) parent = models.ForeignKey('self',null = True,blank = True) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name @property def get_replies(self): return Reply.objects.all() def get_absolute_url(self): return reverse('blog',kwargs = { 'pk':self.pk }) class Reply(models.Model): comment = models.ForeignKey(Comment,on_delete = models.CASCADE,related_name = "replies") body = models.TextField() Here,s the views.py def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm(request.POST or None) subscribe = Subscribe() reply = ReplyForm(request.POST or None) if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) reply = ReplyForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return redirect('index') elif reply.is_valid(): reply.instance.comment = comment reply.save() return render(request,'app/blog.html',{'blog_object':post,'comment':comment, 'subscribe':subscribe,'reply':reply }) Here,s the blog.html <h3 style = "color: #ff714a; font-weight:300;" > Leave a comment </h3> <div class="comments"> <div class="row"> <div class="container"> </div> <form … -
Giving Base64 response through API for the images stored in AWS S3
I am storing images in AWS S3. My models stores the directory of where the image is stored. So in normal scenario the API response is that of the directory of where the image file is stored. I want to return Base64 string of that image and not the directory while as a response of an API. How can we achieve this? -
how to select table tag from ajax data
I am working on a django application. In the application a user can upload a csv file. That csv file is then processed with pandas and a html table is generated with the pandas to_html function. This html table is then displayed on the webpage. To submit the form I use ajax to avoid page refresh. The problem I am facing is in displaying the table when ajax is used. This is my code views.py def on_csv_upload(request): path = './csv/' if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) df = pd.read_csv(os.path.join(path, str(request.FILES['file']))) table_heading = list(df.columns.values) table_content = df.to_html(classes='table table-bordered table-hover thead-dark', index=False) context = {'table_heading': table_heading, 'table_content': table_content} return render(request, 'index.html', context) html template <form action="{% url 'csv_upload' %}" method="POST" enctype="multipart/form-data" class="mt-2 mb-2 csv_upload_form"> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile"/> <label for="file" class="btn btn-outline-dark btn-lg btn-block select">Choose .csv file</label> <input class='btn btn-warning btn-lg btn-block upload_csv_button' type="submit" value="Upload file" disabled/> </form> <div class="scroll_it"> {{ table_content|safe }} </div> index.js $(document).on('submit', '.csv_upload_form', function(event) { event.preventDefault(); csvUploadAjax(); }); function csvUploadAjax() { let $form = $(".csv_upload_form"); let form_data = new FormData($form[0]); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: form_data, dataType: 'html', processData: false, contentType: false, success: function (data) { displayTable(data); }, error: … -
python manage.py runserver not respoding
python manage.py runserver not working - image screenshot python manage.py runserver / python manage.py runserver 8080 does not work if i type in the code : python manage.py runserver , it just keeps on loading and doesnt show anything and server doesnt run even after so many hours. i dont know why this is happening. so after waiting for long time and press ctrl+c to stop running the server, the following codes(PLEASE CHECK THE IMAGE ABOVE) appear on my bash screen. PLEASE HELP I REALLY DONT KNOW WHY THIS IS HAPPENING, MY PYTHON VERSION IS 3.7.0 AND DJANGO VERSION IS 2.1.7 PLS HELP -
i can't see title of objects in django admin site .just see this : modelName object (2)
i have app call "web". and in models.py i write Income model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Income(models.Model): text = models.CharField(max_length=255) date = models.DateTimeField() amount = models.BigIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) and add this object to models: text = wage , date = now , amount = 1500 , user = 'already users' but i see this: Income object (1) !! image of problem i want to see wage! -
Django Crispy Forms
I am fairly new to Django and I have installed and am trying to use crispy forms in my web app.I have added crispy_forms to my installed apps with a comma after it. When I run the server I get this error: Watching for file changes with StatReloader Performing system checks... Exception in thread Thread-3: Traceback (most recent call last): File "c:\users\amart\django\django\template\utils.py", line 66, in getitem return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\amart\django\django\template\backends\django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "C:\Users\amart\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\amart\AppData\Local\Programs\Python\Python36-32\lib\site-packages\crispy_forms\templatetags\crispy_forms_field.py", line 10, in <module> from crispy_forms.utils import TEMPLATE_PACK, get_template_pack File "C:\Users\amart\AppData\Local\Programs\Python\Python36-32\lib\site-packages\crispy_forms\utils.py", line 11, in <module> from django.utils.lru_cache import lru_cache ModuleNotFoundError: No module named 'django.utils.lru_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\amart\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\amart\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) … -
Problems with collectstatic disabling during heroku deploy in Django
I was experiencing a ! [Remote rejected] master -> master (pre-receive hook declined) problem while deploying heroku project in Django. I know that heroku deploy succeeded by running the command heroku config: set DISABLE_COLLECTSTATIC = 1 according to the log, but this command disables collectstatic during deployment. But my static files will work normally. What happens to me when I use the heroku config: set DISABLE_COLLECTSTATIC = 1 command? -
How to fill and access a Django ArrayField?
To solve my (kinda specific) problem, I found that I have to use Django ArrayField: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/fields/#arrayfield I have defined it in my models.py file as Bla = ArrayField( models.IntegerField(), size=4 null=True ) But how do I actually put information inside? Ideally both a whole python list, as also at a single place. And once it is in there, how can I retrieve it? Both on python side, as also in the .html file? PS: I don't think that the whole background of the problem is relevant, so I omitted it for now, but I will of course provide all necessary details if anyone is interested. -
how to add dropdown list to the form in django?
i have a form that allow user to insert new record to the database using django. the form is working as it should. and i have dropdown list country that is pre-populated with data from the database and it works as it should. now i want to enter the dropdown list into the form to allow the user to select from it. how can i do it ? models.py class Country(models.Model): name = models.CharField(max_length=50) def __str__(self): return str(self.name) class Person(models.Model): boolChoice = ( ("M","Male"),("F","Female") ) name = models.CharField(max_length=50) date = models.DateField() description = models.TextField() gender = models.CharField(max_length = 1,choices=boolChoice) country = models.ForeignKey("Country", on_delete = models.CASCADE) addPerson.html {% extends 'base.html' %} {% block content %} <div class="hero__content"> <form method="POST" class="form-style-9">{% csrf_token %} {{ form.as_p }} <ul> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <li> {# <input type="number" name="field1" class="field-style field-split align-right" placeholder="اﻟﺴﻨﺔ" id="year"/> #} {# <input type="date" name="field2" class="field-style field-split align-left" placeholder="اﻟﺘﺎﺭﻳﺦ" id="date" /> #} <h2>Add Member</h2> </li> <li> <input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/> </li> <li> <input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" /> </li> <li> <input type="radio" name="gender" value="M"> Male<br> <input type="radio" name="gender" value="F"> Female<br> </li> <li> <textarea name="description" class="field-style" placeholder= "introduce yourself …