Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the usage of **Kwargs in django
What is the use of **kwargs in a class based view i.e get_success_url(self, **kwargs) in Django. All I understand is that it is a parameter of a function. -
Trying to have an anchor tag that renders to an edit.html using Django but having problem writing the parameters to link to the template
Urls.py from django.urls import path from . import views path('edit/int:user_id', views.edit), on views.py def edit(request, user_id): context = { 'edit':User.objects.get(id=user_id) } return render(request, 'edit.html', context) on the template a href="edit/{{ request.session.user.id }}">Edit</a (I know the a tag is not closed or open but need you to see the the parameters) -
Using Celery with Django: How do you save an object inside of a task?
I have a Django project and have set up a Celery worker. I have a test Task in which I attempt to create and save an object to the database: def get_genome(): return Genome(genome_name='test-genome2', genome_sequence='AAAAA', organism='phage') @shared_task def test(): sleep(10) g = get_genome() g.save() I call the task in a view using test.delay(). The sleep command and the get_genome commeand executes within the celery worker however calling .save() returns the following error: [2020-11-09 10:53:09,131: ERROR/ForkPoolWorker-8] Task genome.tasks.test[cdd748a9-f889-4dae-bec6-3f869f96daf9] raised unexpected: TypeError('connect() argument 3 must be str, not None') Traceback (most recent call last): File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/celery/app/trace.py", line 409, in trace_task R = retval = fun(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/celery/app/trace.py", line 701, in __protected_call__ return self.run(*args, **kwargs) File "/home/daemon/MAS/genome/tasks.py", line 14, in test g.save() File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base updated = self._save_table( File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert return manager._insert( File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1395, in execute_sql with self.connection.cursor() as cursor: File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in … -
Should I have React as a SPA and Django as a REST API or should I have the React inside Django?
So I have been researching this for a while and I honestly feel like I am going in a loop. I am creating a website for customers to view & unlock discounts. Originally, I wanted the React and Django to be completely separate. The reasoning for this is that in the future, I would like to create an Android & iOS application and it would be much easier to only create the front-end for them and connect it to the Django REST Api to fetch data from my PostgreSQL database. However, with further research it seems that it's recommended to have React inside Django due to making use of Django's user authentication? The argument is that it is too hard and also a bit of a security risk to handle the authentication yourself. (Django REST with SPA - what structure). Also I would have to worry about deploying 2 servers but I'm not sure what issues this could cause. So I found this library which helps with JWT authentication. If I was to use this library would my application be "safe"? I am not a security expert and I am the only developer working on this so I am a … -
python 2 for loop not working with list after using sorted()
I think I faced a weird behavior with python 2.7 for loop. Here is the code: events = Event.objects.filter(event_data__xpos=int(xpos), event_data__ref=ref, event_data__alt=alt, event_data__family_id=family_id) events = sorted(events, key=lambda e: get_date_from_event(e), reverse=True) for e in events: logger.info(e) def get_date_from_event(event): from_zone = tz.tzutc() to_zone = tz.gettz('America/New_York') date_saved = parser.parse(event.event_data['date_of_event']) date_saved = date_saved.replace(tzinfo=from_zone) date_saved = date_saved.astimezone(to_zone) return date_saved Event is a Django model with event_data JSONField where all the data is stored. I get a QuerySet with 2 results, then I use sorted and the following list is there: [<Event: Event object>, <Event: Event object>] I checked its type and it is list, and len and it is equal 2. But the for loop does not work, there is no iteration happens since logger prints nothing. -
How to have Django `manage.py test` recognize pytest test method that has no unittest base class?
I'm running parallel unittesting using Django 's manage.py test command. The issue is that this command only recognize the unittest-way test method - for those that has the pytest-way eg no test class and have fixture param, manage.py test will skip them. So my question is how to get manage.py test collect the pytest-way test methods? -
Did django compile views.py everytime a view is requested?
i'm working on a django project and in views.py i need to use an external class for doing some stuff. If i declare the reference of the class, like: class = MyClass() in the top of views.py. Did django need to instantiate the class everytime a view is requested? Or it uses the same instance for all the views(this is what i want)? What i want to achive is to have this external class that is very slow to initialize (4-5 seconds), and use it in one view for all the users... like: def myview(request): # ... some code ... output = class.doSomeStuff() # ................. -
Is it possible to connect a Django back-end to a SparkSql database? [closed]
I'm trying to connect a SparkSQL database to a Django back-end, which uses the Django Rest Framework. I've read Django documentation and learned that Django doesn't apparently support SparkSQL. The purpose of this connection os to access a database that aggregates information, which is then to be retrieved and displayed on dynamic tables on our front-end. So far, I've managed to do this with other databases (PostgreSQL and SQLite) and I've looked at the documentation for SparkSQL, PySpark, and even how to connect to Hive, but to no avail. Some years ago, I have implemented a solution that connected to this same database and then retrieved the information we needed. However, the back-end at the time was written in Java. Is it possible to connect a Django back-end to this sort of database? If so, what would you suggest? Thanks in advance! -
How to see the logs from docker? using django background_tasks
I'm running django background_tasks in the background with a docker container. The dummy tasks run smoothly @background(schedule=30) def dummy_backgrountask(**kwargs): print("running...") logger.debug('logger shows running 1.2..3....') print (kwargs) in docker: tasks_django: build: context: . dockerfile: docker/tasks_dj.dockerfile volumes: - .:/tasks_app command: python manage.py process_tasks depends_on: - db container_name: my_background_tasks While I can see in my my-sql that the job repeat itself, I'm unable to see the dummy logs with: $docker logs my_background_tasks it shows nothing -
Elastic Beanstalk - Django API calls getting 504 Gateway Timeout
Context I've setup a basic Django and React app with DRF. The app loads a single HTML page and lets React handle the frontend. React makes API calls to the Django backend. To be clear, Django and React live in the same domain. (I followed Option 1 here: https://www.valentinog.com/blog/drf/#django-rest-with-react-django-and-react-together). It's working well locally during development, and I wanted to deploy to production. I decided to go with aws elastic beanstalk, and I've been able to render the frontend assets successfully. The Problem I'm running into issues whenever I make any sort of API call to Django, for example logging in: I get a 504 gateway timeout error every time. What I've tried I've tried increasing the time limit but it still times out. I assumed that the backend API was not accessible, and so I needed to extend the nginx config for my Django and React setup - I followed this: https://stackoverflow.com/a/27230658/14603395, but I believe there is actually no support for doing this with Django. (And I realized the config file I wrote wasn't even being used). Where I'm at now Thinking about it more, I can't see why I would have to change the nginx config anyway, since I'm … -
Django create unique foreign key objects
I have a FK in my Django model, that needs to be unique for every existing model existing before migration: class PNotification(models.Model): notification_id = models.AutoField(primary_key=True, unique=True) # more fields to come def get_notifications(): noti = PNotification.objects.create() logger.info('Created notifiactions') logger.info(noti.notification_id) return noti.notification_id class Product(models.Model): notification_object = models.ForeignKey(PNotification, on_delete=models.CASCADE, default=get_notifications) When migrating, I get three PNotification objects saved into the database, however each existing Product is linked with notification_id=1, so each existing Product gets linked with the same PNotification object. I thought the method call in default would be executed for each existing Product? How can I give each existing Product a unique PNotification object? -
pytest and selenium usage to test a django view
I intend to test a simple CBV ListView with pytest and selenium. To avoid the repetition of getting in each method the call of reg_customer_browser and live_server fixtures, I thought of creating a fixture in the class like here: class TestAddressesListView: view_name = "dashboard_customer:addresses_list" @pytest.fixture def browser_as_regular_user(self, reg_customer_browser, live_server): return reg_customer_browser.get(live_server.url + reverse(self.view_name)) def test_regular_user_can_not_create_addresses(self, browser_as_regular_user, customer_regular): br = browser_as_regular_user create_url = reverse("dashboard_customer:create_address") with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{create_url}]"') def test_regular_user_can_not_update_address(self, browser_as_regular_user, customer_regular): br = browser_as_regular_user i = random.randint(0, customer_regular.company.addresses.count() - 1) address = customer_regular.company.addresses.all()[i] update_url = reverse("dashboard_customer:update_address", args=(address.pk,)) with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{update_url}]"') But adding this inner fixture makes the browser reopens few times and none of my tests passes. To pass, I need to write each time a method like this: def test_regular_can_not_update_address(self, reg_customer_browser, live_server, customer_regular): br = reg_customer_browser.get(live_server.url + reverse(self.view_name)) i = random.randint(0, customer_regular.company.addresses.count() - 1) address = customer_regular.company.addresses.all()[i] update_url = reverse("dashboard_customer:update_address", args=(address.pk,)) with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{update_url}]"' Isn't it a way to avoid initializing each method with reg_customer_browser and live_server? -
nginx, flower, Django, proxy_pass, and rejecting invalid HOSTs
I have a server on AWS running nginx/uWSGI/Django, with RabbitMQ, flower, and Celery. The problem: use nginx to proxy for flower without opening up a new port, and also reject badly-formed requests that would cause Invalid HTTP_HOST Header errors in Django. I can do either but not both because I am not super experienced with nginx. I'm running flower 0.9.4, as I'm aware of the bug in 0.9.5. In the following config files, if I comment out the "reject_hosts.conf" line, flower works, but I stop rejecting hosts like I should. If I leave it in, the web browser times out making the request for the /flower URL. Here's the relevant config files: nginx-app.conf # the upstream component nginx needs to connect to upstream django { server unix:/home/app.sock; # uwsgi socket } include redirect_ssl.conf; #301 SSL redirects # actual webserver. Note that https is handled by AWS so no listen on 443 server { # default_server indicates that this server block is the block to use if no others match server_name listen 8080 default_server; listen [::]:8080 default_server; charset utf-8; # max upload size client_max_body_size 3M; # adjust to taste include django_aliases.conf; # media and static directories include reject_hosts.conf; # return 444 … -
React Not Starting in DRF project
I am currently trying to create a react app in a django restframework project using "npm start" but i keep getting the following errors: $ npm start > ui@0.1.0 start C:\Users\Admin\Desktop\Projects\Workout & Api\reacter\ui > react-scripts start 'Api\reacter\ui\node_modules\.bin\' is not recognized as an internal or external command, operable program or batch file. internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module 'C:\Users\Admin\Desktop\Projects\react-scripts\bin\react-scripts.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! ui@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the ui@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-11-09T14_21_33_819Z-debug.log The thing is outside of the DRF project, "npm start" works just fine. I have tried force cleaning my npm cache, deleted my npm cache and npm folder, deleted my node_modules folder, uninstalled and reinstalled nodejs, added c:program/win32 to path but nothing has worked. Any help would be appreciated, thanks. -
Unit Testing django User Registration
I am trying to test the UserRegistrationForm forms.py:- class UserRegisterForm(UserCreationForm): email=forms.EmailField() first_name=forms.CharField(max_length=30) last_name=forms.CharField(max_length=150) phone_regex=RegexValidator(regex=r'^\ ?1?\d{9,15}$',message="Phone no must be entered in format: Up to 10 digits allowed.") phone=forms.CharField(validators=[phone_regex],max_length=10) class Meta: model=User fields=['username','first_name','last_name','email','phone','password1','password2'] def save(self,commit=True): user=super(UserRegisterForm,self).save(commit=False) user.save() user_profile=Profile(user=user,phone=self.cleaned_data.get('phone')) user_profile.save() def clean_email(self): email_passed=self.cleaned_data.get('email') is_valid=validate_email(email_passed,verify=True) if not is_valid: raise forms.ValidationError('Not a valid email') return email_passed test_forms.py:- class TestForms(TestCase): def test_UserRegisterForm(self): form= UserRegisterForm(data = { 'username':'Testing_User', 'first_name':'Test', 'last_name':'User', 'email':'testuser@gmail.com', 'phone':'1234567890', 'password1':'testing101', 'password2':'testing101' }) self.assertTrue(form.is_valid()) error:- Traceback (most recent call last): File "D:\Harshal's files\Harshal's wrk\Satvik\Sem 5\Company Project\cms\tests\test_forms.py", line 17, in test_UserRegisterForm self.assertTrue(form.is_valid()) AssertionError: False is not true I dont understand why the test fails? I think I am supplying enough data to the UserRegistration form yet it assert(form.is_valid()) returns False -
Django ValueError Datetime-Local Input does not match format '%A'
Getting a value error when trying to parse the day of the week from a datetime-local HTML input. Running python 3.8. Here is my code: Date: <input type="datetime-local" name="date"/><br /><br /> views.py: import datetime ___ def post(self, request): t = ticket(name = request.POST["name"], address = request.POST["address"], region = request.POST["region"], date = request.POST["date"], day = datetime.datetime.strptime(request.POST["date"], "%A")) t.save() models.py: class ticket(models.Model): name = models.CharField(max_length=40) address = models.TextField() region = models.ForeignKey(region, on_delete=models.CASCADE) date = models.DateTimeField() day = models.CharField(max_length=40) Help is appreciated. Thank you. -
How to temporary save database updates before approval from administrator in Django?
My problem is the following: I am developing a collaborative website in Django where every user can make changes in the database. Say I have a model MyModel as follows class MyModel(models.Model): name = models.CharField(max_length = 1000) description = models.TextField() and, I have an HTML form somewhere that displays the two fields and that every user can access to make changes. What I would like to do is that every time a user submits a change for an instance of MyModel, this update is saved somewhere temporary. Then, when the administrator logs in, he/she can see the submitted updates and can approve them or not. I have no ideas how to implement this in Django. If anyone has done that already or have an idea, that would be great :) Thanks ! -
images_data = validated_data.pop('images') KeyError: 'images'
I am tryiI am trying to upload multiple images to the article as ArrayField(ImageField()) is not working on Django right now. Here are my codes: Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True,) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True,related_name='images') Serializers.py class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True,allow_null=True) class Meta: model = Article fields = ('id','author','images') def create(self, validated_data): images_data = validated_data.pop('images') article = Article.objects.create(**validated_data) for image_data in images_data: ArticleImages.objects.create(article=article, **track_data) return article Views.py class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now i am facing with an issue that gives KeyError: images_data = validated_data.pop('images') … -
How to get n last elements from list in Django template
I have an image slider inside my website and I want it to display n (or in my case 3) preview_image of the latest posts. In models.py: preview_image = models.ImageField(default="img/news/default_preview.png", upload_to="img/news") In views.py: def home(request): context = { "posts": list(Post.objects.all()) } return render(request, "news/news_home.html", context) In news_home.html: ... <img src="{{ posts.1.preview_image.url }}" alt=""> ... This works for specific post, but I want to select the latest(last one) in the list, so far I tried: <img src="{{ posts|slice:'-1:'.preview_image.url }}" alt=""> <img src="{{ posts|slice:'-2:-1'.preview_image.url }}" alt=""> <img src="{{ posts|slice:'-3:-2'.preview_image.url }}" alt=""> But I get an error: Exception Value: Could not parse the remainder: '.preview_image.url' from 'posts|slice:'-1:'.preview_image.url' Anyone knows how to solve this? -
How to persist a session in sqlalchemy orm in order to simulate a cache
i'm using automap from sqlalchemy to automatically generates mapped classes and relationships from a database schema. So, in this way, it's not necessary create models. But, there's a problema with this to mapping classes and relationships, it's ver very slow. And, every singlw time i make a request, all the process is loading again. I wann know if there a way to keep the tables saved or persist them, like a cache. so that I don't have to pull them from the database with every request made. This is the original code: metadata = MetaData() metadata.reflect(engine) Base = automap_base(metadata=metadata) Base.prepare() table = getattr(Base.classes, <tablename>) I make a request: tablename = request.data[<tablename>] And, with this function, i take the table and they respective relations, if they exist: from django.conf import settings engine = settings.ENGINE['engine'] session = settings.SESSION['session'] def create_model(request_table): metadata = MetaData() metadata.reflect(engine, only=[request_table]) Base = automap_base(metadata=metadata) Base.prepare() return Base.classes But, like i said, every time a made a request, this function is loading again. I'm new to sqlalchemy orm and really need help. Also, i'm not using flask, i'm using django. -
How to update the User id in a related model's instance in Django
I am intending to populate the model's created by field with the user ID using a base model and to do that, I am updating the field in form valid method like this: form.instance.created_by = self.request.user # "created_by" : Field in the base model However, when I try to do this to update the created by field of the child model using: my_formset.instance.created_by = self.request.user the (created by) field is not updated (remain's blank) in the child model's record. As designed for the application logic, the child instances may be created during the create process as well as (at any point in time) at updates. So if a user different from the one who created the records, updates to add a new line item (child instance), it is intended that the user id should be saved in that particular (child) record (I hope I am able to convey the goal properly here). How should I approach this scenario? -
How to display formset with data generated by view
I can not figure out how to display data grid as a formset. They way my site works- user provides string in search field which later I use to display items that contain this string. The way I used to display it was: {% for item in found_items %} <form method="post" action="."> {% csrf_token %} <tr> <td> {{item.model}} </td> <td> {{item.symbol}} </td> <td> {{item.ean}} </td> <td><div class="form-group"> <input type="text" class="form-control" placeholder=0 name="qty" id="qty"> </div></td> <td> <button type="submit" name="add" class="btn btn-success" value="{{item.pk}}">Add</button> </td> </tr So I displayed a list of forms as a table. It worked very good but I want to change the behaviour by adding "ADD ALL" button (to an order). Basically I want to display all of my "found_items" with "quantity" input box and add all of items with quantity > 0 (user will provide quantity). Iterating through forms is difficult, I would have to send number of found items to template, give every form different name/id, iterate through all of them to check if quantity is > 0 and then add items to my order. I've read about formsets but I can't figure out how to use it in this example. The way it seems to work … -
blank page in pagination Django 3.1
I implemented the Django pagination to slice the results of the search on my site. # views.py def search(request): # Keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: title_list_control_valve = queryset_list.filter(title__icontains=keywords).order_by('title') description_list_control_valve = queryset_list.filter(description__icontains=keywords).order_by('description').distinct('description') result_list_control_valves = list(chain(title_list_control_valve, description_list_control_valve)) result_list_control_valves_2 = list(dict.fromkeys(result_list_control_valves)) paginator = Paginator(result_list_control_valves_2, 1) page = request.GET.get('page') paged_queries = paginator.get_page(page) context = { 'queries': paged_queries, } return render(request, 'pages/search.html', context) else: return render(request, 'pages/search.html') else: return render(request, 'pages/search.html') the URL of the site when showing search results is : http://localhost:8000/pages/search/?keywords=something It works perfectly fine on the first page only. From the second page on, it shows an empty page, and the URL of the site changes to: http://localhost:8000/pages/search/?page=2 I link to other pages in the HTML as following: <div class="col-md-12"> {% if queries.has_other_pages %} <ul class="pagination"> {% if queries.has_previous %} <li class="page-item"> <a href="?page={{queries.previous_page_number}} " class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in queries.paginator.page_range %} {% if queries.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}} " class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} {% if queries.has_next %} <li class="page-item"> <a href="?page={{queries.next_page_number}}" class="page-link">&raquo;</a> </li> {% else %} <li … -
Multi-part form in Django
I have this model class VehicleOption(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) option_name = models.CharField(max_length=60) I want to create a form in which I can add 0 or more instance of this model in the DB with a single form but I can't seem to make it work. I tried like this: class ExtraOptionForm(forms.ModelForm): option = forms.CharField(max_length=60) class Meta: model = VehicleOption fields = ('option', ) def vehicle_extra_option(request, vehicle_id): ExtraOptionFormSet = modelformset_factory(VehicleOption, form=ExtraOptionForm, min_num=0, max_num=10, validate_max=True, extra=10) if request.method == 'POST': formset = ExtraOptionFormSet(request.POST, queryset=VehicleOption.objects.none()) if formset.is_valid(): for form in formset.cleaned_data: if form: option = form['option'] option = VehicleOption(vehicle=vehicle_id, option_name=option) option.save() # use django messages framework messages.success(request, "Rregjistrim me sukses!") return HttpResponseRedirect("/") else: messages.error(request, "Error!") else: formset = ExtraOptionFormSet(queryset=VehicleOption.objects.none()) But I can ['ManagementForm data is missing or has been tampered with'] error. Thanks in advance! -
Django on Heroku - missing staticfiles manifest.json file
I am trying to start Django on Heroku. I looked around Stack Overflow, I tried different things, but I cannot figure it out. It looks similar to all the questions related to staticfiles problem on Django, unfortunately I don't know where the problem is. My project runs just fine with DEBUG = True, but when I change it to False, I get following traceback: 2020-11-09T13:13:42.801384+00:00 app[web.1]: Missing staticfiles manifest entry for 'order/css/open-iconic-bootstrap.min.css' It happens on all of my apps that require staticfiles. I tried to find manifest.json, but it does not exist. So I think this is the issue. Here are my relevant settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #more ... ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' django_heroku.settings(locals()) Thanks for looking into this!