Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error "collectstatic --noinput" in heroku with Github
I have created and worked on a Django application (Simple website with user registration and login) and now i want to try deploying it into heroku. I have already uploaded my full code to GitHub and I'm using the deployment method through GitHub on Heroku. I connected my GitHub directory to heroku and started the deployment, but an error came up. I've searched everywhere but i can't find a solution anywhere. here's the error -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 125, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 313, in listdir for entry in os.listdir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_e6d59abe7139c45ae94e60de651b660c/sitoassociazione/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may … -
django inspectdb ORA-00904 "IDENTITY_COLUMN"
I'm currently trying to get Django (version 2.1.5) models from existing Oracle 11 database by python manage.py inspectdb, but this error still occurs: # Unable to inspect table table_name # The error was: ORA-00904: "IDENTITY_COLUMN": invalid identifier I've tried to use different Djangos. E.g. with 2.0, error didn't occur, but no text for models was created. Another questions from this topic here on SO were not helpful. Based on this link, I think error occurs because I have no primary key in the table, but since I'm not sure, I don't want to make any changes to existings database. Does anybody solved this problem? -
Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 41624: character maps to
I'm trying to import a CSV file with Django-MySQL, using django-import-export module. My data looks like below; laptops_name laptops_url laptops_price laptops_image brand_name "Acer Predator Helios 300 PH315 144Hz (i7-8750H, 8GB, 1TB, 128GB, NV GTX1060, W10)" https://computermania.com.bd/product/acer-predator-helios-300-bd-price/ 132900 https://computermania.com.bd/wp-content/uploads/2017/08/acer_predator_helios_evl1L-240x240.jpg Computer Mania "Acer Predator Helios 300 PH315 144Hz (i7-8750H, 16GB, 1TB, 128GB, NV GTX1060, W10)" https://computermania.com.bd/product/acer-predator-helios-300-ph315144hz-refresh-rate-i7-8750h-16gb-1tb-128gb-nv-gtx1060-w10h/ 138900 https://computermania.com.bd/wp-content/uploads/2017/08/acer_predator_helios_evl1L-240x240.jpg Computer Mania "Asus TUF FX504G 15.6ƒ?? FHD Gaming Laptop (I5-8300H, 4GB, 1TB, GTX1050 4GB)" https://computermania.com.bd/product/asus-tuf-fx504g-bd-price/ 73900 https://computermania.com.bd/wp-content/uploads/2018/04/asus_tuf_fx504g_de40_SCd3d-240x240.jpg Computer Mania "Asus TUF FX504G Gaming Laptop (I5-8300H, 8GB, 1TB, GTX1050 4GB)" https://computermania.com.bd/product/asus-tuf-fx504g-15-6-fhd-gaming-laptop-i5-8300h-8gb-1tb-gtx1050-4gb/ 77900 https://computermania.com.bd/wp-content/uploads/2018/04/asus_tuf_fx504g_de40_SCd3d-240x240.jpg Computer Mania "Dell Alienware M15 Gaming Laptop (I7-8750H, 16GB, 1TB+8GB+256GB, GTX1070 8GB, W10)" https://computermania.com.bd/product/dell-alienware-m15-price-in-bd/ 199000 https://computermania.com.bd/wp-content/uploads/2019/01/dell_alienware_15_m1_DNpO4-240x240.jpg Computer Mania But I get an error like the title of this question. My django model is like below: class ProductLaptop(models.Model): laptops_name = models.CharField(max_length=500) laptops_url = models.CharField(max_length=500) laptops_price = models.IntegerField(null=True, blank=True) laptops_image = models.CharField(max_length=400) brand_name = models.CharField(max_length=20) def __str__(self): return self.laptops_name Any solution for this problem? -
I am stuck with Levenshtein. It keeps saying "No module named 'Levenshtein'. I have installed Levenshtein. What should I do?
File "/Users/karanpraharaj/Desktop/IIIT Hyderabad - Spring 2019/Project - CV Jawahar/RMS-master/RMS/Each_Paper_Analytics/views.py", line 7, in import Levenshtein ModuleNotFoundError: No module named 'Levenshtein' -
Django Use values in static files
I have some standard colors set in my settings.py colors = [ ("blue", "#4a3ed0"), ("green", "#4ad041") # And some more ] I load my static files using: <link rel="stylesheet" href="{% static 'defaults/default.css' %}"> And I want to access green in my default.css. I made a template tag (named utils): @register.simple_tag def get_settings_color(color): for c in settings.colors: if c[0] == color: return c[1] In my default.css I tried to access "get_settings_color" but it didnt work. defaults.css: {% load utils %} div.green{ color: #fff; background-color: {{ get_settings_color:"green" }} /* And some other fields */ } -
refresh component state every time it is rendered react
I have an API running and I am trying to fetch that to get some information about some products. I am using react router to route the products and using that to fetch the API. However, when I try clicking on a different product the information from the previous product remains no matter what I do. Here is my fetch: componentWillMount(){ let id = this.props.params.id + 3; let url = 'http://localhost:8000/api/item/' + id + '/'; return fetch(url) .then(results => results.json()) .then(results => this.setState({'items': results})) .catch(() => console.log(this.state.items)); and where I call the fill the information render() { return ( <div className="itemPageWrapper"> <div className="itemImgWrapper" /> <div className="itemInfoWrapper"> <Link className="backLink" to="/"> <span className="small"> <svg fill="#000000" height="13" viewBox="0 0 18 15" width="13" xmlns="http://www.w3.org/2000/svg"> <path d="M7 10l5 5 5-5z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg> </span>All Items </Link> <h3 className="itemName">{this.state.items[Number(this.state.id)].name}</h3> <p className="itemCost frm">{this.state.items[Number(this.state.id)].price}</p> <p className="description"> {this.state.items[Number(this.state.id)].description} </p> <p className="seller frm">By <span>{this.state.items[Number(this.state.id)].brand}</span></p> <button className="reqTradeBtn normalBtn">Order</button> </div> </div> I receive an error saying TypeError: Cannot read property 'name' of undefined if I change anything. I am using a +2 because my API starts at 3. How would I make this work for all products -
Using Luigi within Django
I developed a pipeline with Luigi framework. Now I would like to trigger it, within a webapp (Django), by pressing a button. However, when I run the pipeline from the webapp, I get the following error: signal.signal(signal.SIGUSR1, self.handle_interrupt) ValueError: signal only works in main thread" Here is my code: def run_pipeline(): p = Pipeline() exec p def index_view(request): if request.GET.get('btnRun'): t = threading.Thread(target=run_pipeline) t.setDaemon(True) t.start() return render(request, 'index.html') -
The empty path didn't match any of these. (Python3, Django, URLS)
Sorry for my english, im from RU Im learning Python3, im install python and django on my webserver. But i have a problem with urls, im reading any topic but i dont finding answer for my question (so sorry for my eng). sctructure: expnk.ru HelloDjango (1) HelloDjango (2) setting.py .......... urls.py cat ... any apps app "cat" im create from ssh command: python3 manage.py startapp cat next im going to HelloDjango (2) and edit file setting.py, for INSTALLED_APPS im add 'cat' after im going to file HelloDjango (2) -> urls.py, im add on this file next string: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^cat/', include('cat.urls')), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), url(r'^test/', include('test.urls')), ] after im going to: cat -> urls.py and add on this file: from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] last, im edit file views, code from this file: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse("Hello world!") # Create your views here. I created the cat application similar to the blog application, as a result: the blog is running, cat is not. Please, help -
Celery use Django Result Backend on Remote tasks
I have a Django application that use Celery to create async tasks. Some of these tasks live within the Django project and other live on a remote worker with its own code base. I currently use the django-celery-results package to store the results of task calls within the Django database so that I can easily query the status of calls using the Django ORM. This works fine when I call my "local" tasks, but it does not seem to work as well when I call remote tasks. For example: app.send_task("django.foo") # Return status SUCCESS and store result in DB app.send_task("remote.bar") # Stuck in PENDING and never create result in DB By reading the Celery Docs I found out that tasks can be stuck in PENDING if the client and worker doesn't use the same CELERY_RESULT_BACKEND setting. In this case I can't use the django-db backend on my remote worker, since it's not a Django application. So in this case... How do I store my results when doing remote calls in this manner? Note that in the case of remote.bar, I confirm that the remote worker receives the message and executes the method. Its just that my client (Django App) doesn't … -
Django-FCM returns OK but I didn't receive the notification
I made an backend with Django for an Android Application. I have to send some notifications to the device and for that, i installed Djando-fcm (https://django-fcm.readthedocs.io/en/stable/quickstart.html). My problem is when i test "python manage.py fcm_messenger --device_id=3 --msg='my'" The application returns Succesfull, but the notification doesn't recieved. [OK] device #3 (Test): ([u'fZwT3TGUMig:APA91bGa1QVfKzKjrKUwCFQKKRk5cjiKfli52-nKtWf6T1EYc9rxg9LRje1YOw6OHt-M6ho4n9ps4JZkRqZ3vmhBfH3k9WE88c80tqHbgck4lLiBpBGOW7kMLJxFVKrSDhwv5kKUWXIb'], {u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8479349601166653607L, u'results': [{u'message_id': u'0:1548084391335752%150287e038eb0007'}]}) My requirements.txt is (Python 2.7): Django==1.11.10 djangorestframework==3.7.7 mysqlclient==1.3.12 pytz==2018.3 virtualenv==15.1.0 amqp==2.4.0 billiard==3.5.0.5 celery==4.2.1 certifi==2018.8.24 chardet==3.0.4 Django==1.11.10 django-fcm==0.1.1 djangorestframework==3.7.7 idna==2.7 kombu==4.2.2.post1 mysqlclient==1.3.13 pytz==2018.3 requests==2.19.1 urllib3==1.23 vine==1.2.0 -
Is there any way to run channels on azure app service?
I have currently run websocket locally with django channel (tutorial chat) I would like to submit the project on azure app service, I have enabled websockets in the control panel. however this does not work, once in my browser on the site I cannot connect to the socket either in http or https. I changed my webconfig also by putting <webSocket enabled="false" /> in order not to use the IIS module. What would you recommend me? isn't it because of the wsgi handler? -
How do I write a Django ORM query with a relation that isn't defined in the model?
I'm using Django and Python 3.7. I have the following two models in my models.py file ... class Article(models.Model): created_on = models.DateTimeField(default=datetime.now) ... class ArticleStat(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, ) elapsed_time_in_seconds = models.IntegerField(default=0, null=False) I would like to write a Django ORM query where I select articles have a stat that's at least 5 minutes (300 seconds) old. However, I don't know how to reference the ArticleStat object from the Article object. Unsurprisingly, this Article.objects.filter(articlestat.elapsed_time_in_seconds.lte==300) produces a NameError: name 'articlestat' is not defined error. -
How to get the result from async function in python using Celery + Redis
I am new to task queue. When i open the shell and execute the function add.delay(3,4) from the function in the shell to perform the task. I get : <AsyncResult: 30db3528-5b0f-4e74-bf47-51956a1f83e9>. How do I get a result from this function and what should i do to schedule the result to be executed 5 second later? celery.py from future import absolute_import, unicode_literals import os from celery import Celery app = Celery('RedisQueue') app.autodiscover_tasks() @app.task def add(a, b): return a + b init.py from future import absolute_import, unicode_literals all = ['celery_app'] settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
How to loop through extended user model fields in Django template?
I have extended Django's user model with a Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') date_of_birth = models.DateField() address = models.CharField(max_length=300) postcode = models.CharField(max_length=15) Then, I pass this data into a template via this view: def profile(request): args = {'user': request.user} return render(request, 'users/profile.html', args) Then I can access each field of the Profile model individually in the template with: <p>Your DOB is: {{ user.profile.date_of_birth }}</p> However, I want to use a for loop to say: {%for field in Profile model %} <p>{{field name}} = {{field value}} {% endfor %} But I've tried a lot of different things, none of them work, e.g. {% for field in user.profile.all %} <p>{{ field }}</p> {% endfor %} (This compiles but is blank when the template is ran) -
Django - code after Object creation is not executed
My code is: if part_one is None: print("########### PART ONE") part_one = Company.objects.create( name=name, owner=request.user, source=source ) print("########### PART TWO") PartTwo.objects.create( first_names=name.split(" ")[0], last_names=" ".join(name.split(" ")[1:]), source=source, party=party ) The problem I am facing is that the second print statement or any code thereafter is not executed anymore. Is this something django specific? I do not seem to find any reason why the function gets aborted after creating Part One -
Run Django with gunicorn, Celery and Celery Beat
I have a docker-compose file like this: backend: image: ${API_IMAGE} env_file: - .env depends_on: - db volumes: - ./data/server/static/:/usr/src/api/static - ./data/server/uploads/:/usr/src/api/uploads restart: always frontend: image: ${FRONTEND_IMAGE} env_file: - .env ports: - "80:80" volumes: - ./data/server/logs:/usr/src/web/logs - ./configs/nginx:/etc/nginx/conf.d - ./data/server/static/:/usr/src/app/static - ./data/server/uploads/:/usr/src/app/uploads restart: always celery: image: ${API_IMAGE} env_file: - .env working_dir: /usr/src/api/ environment: DJANGO_SETTINGS_MODULE: 'core.settings' depends_on: - redis command: /bin/sh -c "celery -E -A core worker -l info" beat: image: ${API_IMAGE} env_file: - .env working_dir: /usr/src/api/ environment: DJANGO_SETTINGS_MODULE: 'core.settings' depends_on: - celery command: /bin/sh -c "celery -A core beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler" Everything is accessed through the frontend container which is a Nginx application using proxy to send request to others containers. The backend is running with the CMD in a bash file with: /usr/local/bin/gunicorn --access-logfile - -w 4 core.wsgi:application -b 0.0.0.0:80 & Everything is fine, and running. But if I access the admin site, and try to use Celery Beat to create a Periodic Task, show me this error: Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ backend_1 | return obj.__dict__[self.__name__] backend_1 | KeyError: '_modules' backend_1 | backend_1 | During handling of the above exception, another exception occurred: ... File "/usr/local/lib/python3.6/site-packages/celery/app/base.py", line 684, in … -
How to test a view using the request object
I need to make tests to see if my view is working properly. However, I did not find how to use the request object in the test file. My view function is: def track_view(request): user_email, user_order = request.session['email'], request.session['order'] if request.method == 'POST': client_id = request.META.get('HTTP_HOST').split(':8000')[0] payload = "{ \n\"description\": \"Rastreio de pedido\", \n\"subject\": \"Rastreamento " + user_order + ' ' + user_email + "\", \n\"email\": \"" + user_email + "\", \n\"priority\": " + str( priority['low']) + ", \n\"status\": " + str(status['closed']) + ", \n\"group_id\": " + str(group[ 'Logística']) + ", \n\"type\": \"Rastrear Pedido\", \n\"product_id\": " + str(client[client_id]) + "}" headers = { 'Content-Type': "application/json", 'Cache-Control': "no-cache" } response = requests.request("POST", url, data=payload, headers=headers, auth=('XXX', 'X')) print(response.text) context = {'email_variable': user_email, 'order_variable': user_order} return redirect('atendimento:final_view') logo_image = 'client_logo/' + request.META.get('HTTP_HOST').split(':8000')[0] + '.png' context = {'logo_image': logo_image, 'user_email': request.POST.get('email'), 'user_order': request.session['order']} return render(request, 'atendimento/track_page.html', context) How can I make that work to test different inputs to that view? -
How to update nested serializers with file field
I have 2 models: Profile and Image. Profile field "logo" related to Image with models.ForeignKey() construction. I want to update my Profile record with update request (Patch with JSON payload). How can I do that? I've tried to send this JSON { "name": "TestName", "company": "myCompany", "phone": "33222111", "website": "site.com" } And it's OK, record have updated. But! In Image model I have models.ImageField(). How I should deal with this field through another serializer? Then I've tried to send this JSON (122 id of existed Image record in DB) REQUEST: { "logo": 122 } ANSWER: { "logo": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } OK, so, think I should send object of exist record REQUEST: { "logo": { "id": 122, "uuid": "bf9ba033-208f-47e0-86e5-93c44e05a616", "created": "2018-12-20T12:54:57.178910Z", "original_name": "hello.png", "filetype": "png", "file": "http://localhost/upload/img/0a9lg1apnebb.png", "owner": 1 } } ANSWER: { "logo": { "file": [ "The submitted data was not a file. Check the encoding type on the form." ] } } Here my two models and serializers class Image(models.Model): id = models.AutoField(primary_key=True) uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add = True) original_name = models.CharField(max_length = 256, default=None) filetype = models.CharField(max_length = 10, default=None) file = models.ImageField(upload_to=update_img_filename, … -
ModelForm with ModelMultipleChoiceField how to group choices based on their parent model?
What I want to achieve is this: Category1 Choice1 Choice2 Choice3 Category2 Choice1 Choice2 etc. I use a custom ModelMultipleChoiceField. The problem is in my template I can not present them in their categories. Instead they all are generated under eachother. my forms.py: class CustomAmenitiesSelectMultiple(CheckboxSelectMultiple): """ CheckboxSelectMultiple Parent: https://docs.djangoproject.com/en/2.1/_modules/django/forms/widgets/#CheckboxSelectMultiple checkbox_select.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_select.html multiple_input.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/multiple_input.html checkbox_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_option.html input_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html """ template_name = "forms/widgets/custom_checkbox_select.html" option_template_name = 'forms/widgets/custom_checkbox_option.html' class AmenitiesForm(ModelForm): class Meta: model = Venue fields = ('choices',) choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=CustomAmenitiesSelectMultiple,) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()] forms.ModelForm.__init__(self, *args, **kwargs) def save(self, commit=True): instance = forms.ModelForm.save(self) instance.amenity_set.clear() instance.amenity_set.add(*self.cleaned_data['choices']) return instance custom_checkbox_option.html: {% if widget.wrap_label %} <label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %}>{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} {{ widget.label }}</label> {% endif %} custom_checkbox_select.html {% with id=widget.attrs.id %} <div class="inline field"> <div {% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}> {% for group, options, index in widget.optgroups %}{% if group %} <div> {{ group }} <div> {% if id %} id="{{ id }}_{{ index }}" {% endif %}>{% endif %}{% for option in options … -
Can't save image to django ImageField
im currently facing a problem i really dont understand. i have several models in my models.py beside a post model also a category_request model. Anyways, i'm able to save the ImageField for the post model but not for the category_requests model. i diff the two a lot of times but i m not able to see the issue :( the fields simply does not get saved at the database. models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=20, verbose_name="Title") description = models.TextField(max_length=175, null=True, blank=True) cover = fields.ImageField( blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor(format='JPEG',quality=99,scale={'max_width': 700, 'max_height': 700}))]) published_date = models.DateField(auto_now_add=True, null=True) status = StatusField() STATUS = Choices('Waiting', 'Rejected', 'Accepted') up_vote = models.IntegerField(default=0) down_vote = models.IntegerField(default=0) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "CategoryRequest" verbose_name_plural = "CategoryRequests" ordering = ['title'] def __str__(self): return self.title As already mentioned, the working post model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=25) content = models.TextField(max_length=5000) tag = models.CharField(max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] ) postcover = fields.ImageField( upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor(format='JPEG',quality=99,scale={'max_width': 700, 'max_height': 700}))]) published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "Post" verbose_name_plural … -
django upgrade from 2.0.2 to 2.1.5
I upgraded django 2.0.2 to 2.1.5 Because 2.0.2 has maybe distinct() and count() error. After I upgrade django with pip install -U django, when I python manage.py runserver there was it: You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin. Run 'python manage.py migrate' to apply them. So I type that: python manage.py migrate Then, this comes: Operations to perform: Apply all migrations: admin, auth, contenttypes, ipn, sessions, sites Running migrations: Applying admin.0003_logentry_add_action_flag_choices... OK If being on production, Is it okay to do that? What does that means? -
Django 2 namespace and app_name
I am having a difficult time understanding the connection between app_name and namespace. consider the project level urls.py from django.urls import path, include urlpatterns = [ path('blog/', include('blog.urls', namespace='blog')), ] consider the app level (blog) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] if I comment out app_name, I get the following. 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. If I rename app_name to some arbitrary string, I don't get an error. app_name = 'x' I've read the documentation but its still not clicking. Can someone tell me how/why app_name and namespace are connected and why are they allowed to have different string values? -
Django 2.1 Model Observers
Does DJango 2.1 have any support for observers on models? I've looked into https://github.com/lambdalisue/django-observer, but it appears to only support up to 1.6. My goal is that everytime a model is updated, I want to fire and command that executes other functions. -
Django generics.ListAPIView accepting POST method
I have a Django view which extends generics.ListAPIView. It works fine with get requests, however since the char limits of the URL, now I need to send the request via POST. It is the same request, the only thing I need to change is the method to POST. My current code is pretty simple: class MyClass(generics.ListAPIView): serializer_class = MySerializer paginate_by = 1 def get_queryset(self): queryset = SomeClass.objects.all() # do some filtering How could I add POST support to this class? -
Default Value 0 (Zero Number) in Django Model
I want input default value whenever the entry is Null inserted. Always it is inputing null value in my MySQL Database. So i Changed my Model but defuault entry 0 is not inserting class TimesheetHours(models.Model): timesheet = models.ForeignKey(TimesheetEntry, on_delete=models.CASCADE,related_name='timesheet_hours') timesheet_hour_regular = models.IntegerField(default=0,blank=True, null=True) Views.py - Saving Form form_hour = TimesheetHours( timesheet=form_timesheet, timesheet_hour_regular = form.cleaned_data['timesheet_hour_regular'], timesheet_hour_overtime = form.cleaned_data['timesheet_hour_overtime'], timesheet_hour_doubletime = form.cleaned_data['timesheet_hour_doubletime'], timesheet_hour_travel = form.cleaned_data['timesheet_hour_travel'], timesheet_hour_admin = form.cleaned_data['timesheet_hour_admin'], timesheet_hour_other = form.cleaned_data['timesheet_hour_other'], timesheet_hour_created_by=self.request.user, timesheet_hour_updated_by=self.request.user ) form_hour.save()