Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When deploying Heroku app I get DisallowedHost at / - But I have added the URL to ALLOWED_HOSTS
DisallowedHost at / Invalid HTTP_HOST header: '#.herokuapp.com'. You may need to add '#.herokuapp.com' to ALLOWED_HOSTS. But I have added both '#.herokuapp.com' and 'www.#.herokuapp.com' into ALLOWED_HOSTS in settings.py Everything is up to date on GitHub and when I change anything in settings.py locally and git add, commit and then run '$ git push heroku master' it detects the insertion/deletion. Builds and deploys the Heroku app successfully. So it should be reading the ALLOWED_HOSTS also, but it's the same annoying error every time! DisallowedHost at / (Error) Really pulling my hair out with this one! -
Mock.assert_has_calls() not working as expected
I have this unit test where I want to ensure my Django custom management job is writing specific messages to its log. @override_settings(HR_SYNC_DATA_DIR=f"{settings.BASE_DIR}/core/management/tests/HR_SYNC_DATA_DIR") @patch('core.management.commands.process_hr_changes.log') @patch('core.management.commands.process_hr_changes.requests.get') def test_sync_users2(self, mock_get, mock_log): # # Load our Mock data # test_data_dir = f"{settings.BASE_DIR}/core/management/tests/TEST_DATA_DIR" get_mocks = [] for filename in glob.glob(path.join(test_data_dir, 'test-data-hrdata_underrun_page_*.json')): with open(filename, "r") as infile: mock_response = Mock(ok=True) mock_response.json.return_value = json.load(infile) mock_response.status_code = status.HTTP_200_OK get_mocks.append(mock_response) mock_get.side_effect = get_mocks with self.assertRaises(CommandError) as context: call_command('process_hr_changes') print(context.exception) self.assertEqual('percent change is -0.125 and delta_pct is 0.1. Lifecycle is dev.', context.exception.args[0]) mock = Mock(return_value=None) info_calls = [ mock.call('rehires = 0 new hires = 0 terminations = 5.'), mock.call('process_hr_changes args are: delta_pct 0.1 how_many_hours_back 24 dry_run False debug is False verbose is False'), mock.call('test: startup'), mock.call('Removing directory /apps/core/management/tests/HR_SYNC_DATA_DIR.'), mock.call('Creating directory /apps/core/management/tests/HR_SYNC_DATA_DIR.'), mock.call('percent change is -0.125 and delta_pct is 0.1.'), ] for mock_call in mock_log.info.mock_calls: print(mock_call) mock_log.info.assert_has_calls(info_calls, any_order=True) When I run this test it fails on the mock_log.info.assert_has_calls(info_calls, any_order=True) statement with this message: AssertionError: (<MagicMock name='log.call()' id='140711932625744'>, <MagicMock name='log.call()' id='140711932625744'>, <MagicMock name='log.call()' id='140711932625744'>, <MagicMock name='log.call()' id='140711932625744'>, <MagicMock name='log.call()' id='140711932625744'>, <MagicMock name='log.call()' id='140711932625744'>) not all found in call list I also see this output from my print statement: call('process_hr_changes args are: delta_pct 0.1 how_many_hours_back 24 dry_run False debug is False verbose … -
how can I refresh image in Django HTML
I'm trying to refresh the image after pressing the button I include the image in static files.. im using Django with HTML -
How to put parameters as kwargs in Postman
I will use kwargs in django in python but I do not how to put parameters as kwargs? -
Use F value as dict key for ordering django
I am developing a Django website and I have the following models (simplified): class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) opinions = JSONField(default=default_opinions) class Author(models.Model): name = models.CharField(max_length=50, unique=True) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, default='0') with the opinions field being the opinion that a specific user has of the different authors: Exemple: { Shakespeare: 0.5, Voltaire: 0.6 } Then I have a listView BookListView, in which I want to query the Book database, and order them by the opinion the currently logged in user has of their author. In the previous example it would be all the Voltaire's books first, then the Shakespeare's ones. So I came up with this in my listView: def get_queryset(self): user_opinions = self.request.user.profile.opinions queryset = Book.objects.order_by(user_opinions[F("author__name")]) return queryset The problem is the F value is computed after the get_queryset(), so I get a F("author__name") key does not exist error. I thought about iterating through the dict keys and values but I don't see how that could work since opinions are floats (and thus can take any values). Thanks in advance ^^ -
Django decorator - Check user password to continue
I'm trying to create a decorator that redirects the user to a view that accepts the logged-in user's password and then continues to the requested view if the password is entered correctly. The purpose of this is to add a confirmation step on something like a Delete View. This is what I have so far: decorators.py def confirm_password(view_function): @wraps(view_function) def wrapper(request, *args, **kwargs): # some inner function/logic to call ConfirmPassword view?? # if something: # from .views import ConfirmPassword # return ConfirmPassword.as_view()(request, *args, **kwargs) return view_function(request, *args, **kwargs) return wrapper views.py class ConfirmPassword(UpdateView): form_class = ConfirmPasswordForm template_name = 'myapp/confirm-password.html' def get_object(self): return self.request.user def get_success_url(self): return self.request.get_full_path() forms.py class ConfirmPasswordForm(forms.ModelForm): confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('confirm_password', ) def clean(self): cleaned_data = super(ConfirmPasswordForm, self).clean() confirm_password = cleaned_data.get('confirm_password') if not check_password(confirm_password, self.instance.password): self.add_error('confirm_password', 'Incorrect password.') How do I structure the above decorator to correctly call the ConfirmPassword view? Thank you! -
django upload image using gridfs
I want to add two field for image upload in my model , I run python manage.py makemigrations xxx_app and I've got an error no module named 'gridfsuploads' model-class error-no-module-named -
(Django) Database design theory -- choosing between two design options
Let's say I'm designing a database with books (using Django's ORM, but I'm interested in the general theory of database design here as well as Django-specific advice). This is how I've designed my database so far so that there aren't any useless fields in each model: class Book(models.Model): author = models.ManyToManyField() class PictureBook(Book): illustrator = models.ManyToManyField() class MusicBook(Book): composer = models.ManyToManyField() With this database design, I have an abstract model that has all universal fields stored in it, then sub-classes that have fields specific to them. The problem is that as my project grows, I'm having to duplicate a lot of effort to handle each of the sub types rather than developing around one universal model. What I'm considering is reverting to something more like this: class Book(models.Model): types = (("g", "General"), ("p", "Picture"), ("m", "Music")) type = models.CharField(max_length=10, choices=types) author = models.ManyToManyField() illustrator = models.ManyToManyField(blank=True) composer = models.ManyToManyField(blank=True) Here I would just have one Book model, which has a limited-option field that has the user choose the sub-type of the book they are adding. The problem is that then picture books have composer fields and music books have illustrator fields, and even though I can leave them blank, it … -
I can't validate a file field in my Django form
Form from django import forms class XLSForm(forms.Form): xlsx_file = forms.FileField(help_text="The XLSX file") column_1 = forms.ChoiceField(help_text="Column 1 from XLSX") column_2 = forms.ChoiceField(help_text="Column 2 from XLSX") kaka = forms.CharField(help_text="Column 2 from XLSX") View: def IndexView(request): if request.method == 'POST': form = XLSForm(request.POST, request.FILES) else: form = XLSForm() context = { 'form': form } return render(request, 'xlsplot.html', context) And template: <form method="post" novalidate> {% csrf_token %} {{form}} <button type="submit" class="btn btn-primary">Submit</button> </form> Whenever I submit with file chosen from computer, the file field is reset to "No file chosen" and error is shown "This field is required". Other inputs seem to work fine, if they are filled no errors. I don't get it. -
How do I return Message error for PROTECT Field on DJANGO
I don't no how return a simple message for a error on django, for example, I neeed return PROTECT Error on delete this OBJECT: MY VIEW: def delete_notafiscal(request, notafiscal_id): notafiscal = NotaFiscal.objects.get(id=notafiscal_id) context={'object':notafiscal,'forms':''} try: if request.method =="POST": notafiscal.delete() return HttpResponseRedirect(reverse("controles:notasfiscais")) except ProtectedError as e: print("erro",e) return render(request,'controles/notafiscal_confirm_delete.html',context) MY TEMPLATE <form method="post">{% csrf_token %} <p>Você irá deletar "{{ object }}"?</p> <input type="submit" value="Confirm"> </form> THANKS! -
Gitlab-CI runner is having issues finding my venv and activating it
I am trying to set up CI/CD for the first time. I was following this youtube video: https://www.youtube.com/watch?v=Jav4vbUrqII and I set up my django application using this digitalocean tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04. When I log in with putty to the staging server and run the source command it can find and activate the virtual environment without issue. But when it's run with the script below it tells me no such file exists. I had an idea to see what working directory the script is running from: $ echo $PWD /builds/my username/dir When I am on user home I cannot find /builds/my username/dir: cron.log cron.sh dir1 data file.sql Question: So is it failing to find and activate my environment because it is in a weird directory? What I want to achieve with the script below is: grab the code in the dev branch run collectstatic/migrate restart gunicorn so changes take effect test (but in this case print string - I will have to learn how to do tests at a later time). Gitlab-ci.yml: stages: - build - test staging: build: stage: build script: - echo "Building" - echo $PWD - source dir1/env/bin/activate - cd dir1/my project name/ - git fetch origin dev - … -
Glyphicons can't apply the website in bootstrap 4.5.0
bootstrap 4.5.0 can't use Glyphicons in the old version way '''html this is the line 1 ''' the glyphicons doesn't show on my website ,is there anyone knows the new method to apply the glyphicon in 4.5.0 version??? -
Serializer in patch method does not check fields
I am trying to partially update a model and overwriting the patch method. It works fine when I send correct data, but my problem is, that when I send incorrect data the serializer stays True and I still get a 200 status code and nothing gets updated. With incorrect data I mean wrong field names. I could basically send any field name and get a 200 status code. So I think the fields are not checked by the serializer... class BuildingUpdateAPI(UpdateAPIView): serializer_class = BuildingSerializer def patch(self, request, *args, **kwargs): """Patches building.""" building = buildings.get(name=self.kwargs['name_building']) serializer = BuildingSerializer(building, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(status=200, data=serializer.data) return JsonResponse(status=400, data="Wrong data provided") serializer: class BuildingSerializer(serializers.ModelSerializer): """Serializer for Buildings.""" class Meta: model = Building fields = ( "id", "name", "...", ..... Now I am wondering if this is like this by design or if I am doing something wrong in my view. I thought I could overwrite the validate-method in the serializer but my model has quite a lot of fields... So I would have to check every field single field wich is not optimal I think. Or is there a way to do this somehow elegantly? I am patching like this: result … -
Wagtail embbed youtube video json decode error
Im currenly using wagtail version 2.9.3 , and im having the following errors when trying to upload a youtube URL to wagtail. JSONDecodeError at /admin/pages/3/edit/ Expecting value: line 1 column 1 (char 0) Here is the full error traceback: Internal Server Error: /admin/pages/3/edit/ Traceback (most recent call last): File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\admin\urls\__init__.py", line 109, in wrapper return view_func(request, *args, **kwargs) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\admin\auth.py", line 188, in decorated_view return view_func(request, *args, **kwargs) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\admin\views\pages.py", line 380, in edit if form.is_valid() and not page_perms.page_locked(): File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\modelcluster\forms.py", line 315, in is_valid form_is_valid = super(ClusterForm, self).is_valid() File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\forms\forms.py", line 180, in is_valid return self.is_bound and not self.errors File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\forms\forms.py", line 376, in full_clean self._clean_fields() File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\django\forms\forms.py", line 394, in _clean_fields value = field.clean(value) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\core\blocks\base.py", line 543, in clean return self.block.clean(value) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\core\blocks\stream_block.py", line 198, in clean (child.block.name, child.block.clean(child.value), child.id) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\core\blocks\struct_block.py", line 129, in clean result.append((name, self.child_blocks[name].clean(val))) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\core\blocks\struct_block.py", line 129, in clean result.append((name, self.child_blocks[name].clean(val))) File "C:\Users\dream\Desktop\NoboCMS\backend\cms_env\lib\site-packages\wagtail\embeds\blocks.py", line … -
django projects(saleor) python manage.py migrate error message
Hello Guys I tried to migrate using the command python manage.py migrate and I got this error am done with the set of my environment and I also cloned the saleor reporsitory on github but am still getting these errors. what can I do to fix it? C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\saleor\saleor\urls.py:35: UserWarning: The debug toolbar was not installed. Ignore the error. settings.py should already have warned the user about it. warnings.warn( Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\saleor\saleor\plugins\checks.py", line 20, in check_plugins check_single_plugin(plugin_path, errors) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\saleor\saleor\plugins\checks.py", line 43, in check_single_plugin plugin_class = import_string(plugin_path) File "C:\Users\Timothy Dawadakpoye\Desktop\pyprojs\apron\denv\lib\site- packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "c:\users\timothy dawadakpoye\appdata\local\programs\python\python38- 32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, … -
Problems Running Chatterbot Django example-app
I installed the chatterbot django example_app and I get the ChatterBot page with a text box that says "Type something to begin...". I only have pip installed django, chatterbot, chatterbot-corpus. Is chatterbot out of the box unable to hold a conversation? All it does is parrot back my questions. Is it in training mode? I am not sure what to expect from the dango-example in chatterbot. I looked at the tutorial (https://www.tutorialdocs.com/tutorial/chatterbot/quickstart.html) and it says under training that training is not required. I thought it might be able to handle some simple questions ("how are you?", "what is your name?", etc.) out of the box, but maybe not? I thought chatterbot-corpus gave the chatterbot the ability to hold a simple conversation. If not, what is its purpose? I got one error when running chatterbot: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details. return yaml.load(data_file) Does this mean it cannot load the necessary datafiles to hold a conversation? Thanks for any help you can provide! Mark -
How to to get a list from a model based on function applied on a field without changing values in table
I am using Django and developing a Webapp, I have a model named People with different fields like, first_name,last_name, Familyid. Values in column Familyid looks like this: example familyids: 1 1.1 1.1.1 1.1.1.1 when i am creating view and get data in query set and displaying via template, i want to add one more column in query result set, with information FamilyID Dot Count i.e. Family ID contains how many docts "." , values like Dot Count = 1 or 2 or 3 and so on. please help either should i do it in template(HTMl) or inside view and return it as queryset, and how. Thanks -
how to Run Django and React server together?
I wanna know is it possible Running two server Django and React.js together? every time I should to run Backend with python manage.py runserver and then I should go to Frontend and Run npm Start actually I have One Fullstack project with Subfolders Backend And Frontend my question is we have any code to rune both servers together or Not? -
After login redirect to where the user was
Django==3.0.8 django-allauth==0.42.0 A post with comments below. To leave a comment a user have to be logged in. But when they have logged in, they should be redirected back to that very post and to the comments section. I try like this: <a href="{% url 'account_login' %}?next={{ object.get_absolute_url }}#comments">Log in</a> But after logging the user is redirected to /accounts/profile/ The only thing in the documentation about 'next' seems to be here: https://django-allauth.readthedocs.io/en/latest/release-notes.html?highlight=next#id156 That is in the year 2012 they did something about next param: Added template tags for pointing to social login URLs. These tags automatically pass along any ?next= parameter. Could you help me with this problem? -
I want to add "favourite books or basket" in django models
I'm trying to understand relationships on django and create a little project but I'm stuck.So basically I want to add a field (sort of basket) so that people can add their favourite items among many of them. But I can't implement it. What should I do inside my models? Thanks. Bye the way I want to turn this into RESTFUL.I'll appreciate if you give me any advice. models.py from django.db import models from django.contrib.auth.models import User class Products(models.Model): name = models.CharField(max_length=20) price = models.IntegerField() fav_product = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name -
Django: How to do 2 different model data field sum ? Here 2 model i need A model wh_price * B Model qty= B Model Total
class A (models.Model):name =models.CharField(max_length=50)language = models.CharField(max_length=50, choices=Language)wh_price =models.DecimalField(max_digits=6,decimal_places=2)sa_price=models.DecimalField(max_digits=6,decimal_places=2)class B(models.Model):added_date=models.DateField(max_length=32,auto_now_add=True)newspaper =models.ForeignKey(Newspaper, on_delete=models.CASCADE)qty=models.IntegerField(default=0)qty_return =models.enter codehereIntegerField(default=0)total = models.enter codehereDecimalField(max_digits=6,decimal_places=2) -
How to mock Queryset slice operator
I have the following chained usage I'd like to mock Example.objects.order_by(order_by).filter(filters).all()[:page + 1] It's quite easy to mock all methods involved, but I got no idea how to the slicing, given that it's not an "actual" python slice, it translates into LIMIT/OFFSET. How can this be mocked? -
Django: null value in column "shipping_address_owner_id" violates not-null constraint
I'm trying to add new record to my invoice model table but i keep getting the error message IntegrityError null value in column "shipping_address_owner_id" violates not-null constraint My guess is the column shipping_address_owner which is using ForeignKey that links it to a second table called ShippingAddress. I'm trying to add the following entry to my paymentInvoice model table but i'm getting the above stated error { "shipping_address_owner": "Becky", "product": [ "Sepit" ], "quantity": 1, "payment_made": "2600.00" } Below is my paymentInvoice model table class paymentInvoice(models.Model): shipping_address_owner = models.ForeignKey(ShippingAddress, on_delete=models.CASCADE, related_name="customer_invoice") product = models.ManyToManyField(Product, related_name='product_invoice') date = models.DateField(default=datetime.now) invoice_id = models.CharField(max_length=50, unique=True, default=increment_invoice_number) quantity = models.PositiveSmallIntegerField() payment_made = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.shipping_address_owner.customer.name My ShippingAddress model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_ship_address") address = models.CharField(max_length=50, blank=True) zip_code = models.CharField(max_length=12, blank=True) def __str__(self): return self.customer.name My serializer file class paymentInvoiceSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() shipping_address_owner = serializers.SerializerMethodField() class Meta: model = paymentInvoice fields = '__all__' def get_shipping_address_owner(self, instance): return instance.shipping_address_owner.customer.name def get_product(self, instance): names = [] for product in instance.product.all(): # get all products field names.append(product.name) # append the product name return names -
Generic question about handling data migration with non-nullable foreign keys in Django
I wanted to get an insight on handling data migration in multiple environments for production level data. The use case is where a django application runs in multiple environments across multiple regions, and a new business requirement pops up, asking for a new reference to an existing model. How do we go by handling such scenarios? RunPython is one option, however the deployment process is automated. The python code to handle it per environment becomes un-manageable, and was wondering if there's a non-trivial solution that's been tried and tested. Please advice. Appreciate your time and consideration. Regards, NM. -
Removed abstract Meta from a Django model class and now child class needs a <model>_ptr field?
So originally I had the models structured similarly to this: class Base(models.Model): name= models.CharField(max_length=30) class Meta: abstract = True class Child(Base): other_field = models.CharField(max_length=120) But now, I would like to have both models to have database tables, so I removed the abstract field from the Meta class of Base Now when I run python manage.py makemigrations from cmd, I'm prompted to enter a default value for base_ptr so it can be added to child What is this field? I'm guessing it's something that links the child class to the parent, but I don't know what value it should take as a default.