Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The home page translation link is static and is not used to translate all pages
I have a problem I hope to solve it as I display in the navbar languages used in the site and I want whenever you click on the language the page appears with the translation in all pages and not only the main page ,with the translation link changes with each page http://127.0.0.1:8000/fr/ http://127.0.0.1:8000/fr/our-company So add on the home page link. How to fixed the link on the home page so that the translation is displayed for all pages and keep on the same page translated Navbar home page in all pages <ul class="navigation__dropdown-wrap--language"> <li> <a data-culture="ar" data-lang="True" href="/">العربية</a> </li> <hr> <li> <a data-culture="en" data-lang="True" href="/en/" lang="en">English</a> </li> <hr> <li> <a data-culture="fr" data-lang="True" href="/fr/" lang="fr">français</a> </li> <hr> </ul> -
AptUrl Error when I try to use module for input selection in django-forms
On my django form I want to have inputs that have several options so I created a file names "choices.py" I basically followed what this guy does here https://stackoverflow.com/a/24404791/8993840 Here's the code forms.py class Createjob(forms.Form): title = forms.CharField(label= "", help_text= "") job_sector = forms.ChoiceField(choices=JOB_SECTOR, label="", initial='', widget=forms.Select(), required=True) location = forms.ChoiceField(choices=LOCATION, required=True) experience_level = forms.ChoiceField(choices=EXPERIENCE_LEVEL, required=True) description = forms.CharField(widget=forms.Textarea) models.py class Emprego(models.Model): id = models.AutoField(primary_key=True) # Id_autogerated title = models.CharField(max_length=70) description = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) publisher = models.ForeignKey(Empresa, on_delete=models.CASCADE) location = models.IntegerField(choices=LOCATION, default=1) # Pode ser Remote, no Local da empresa ou noutra sede ou sth else # Professional Details type_job = models.CharField(max_length=50) # Contrato, part-time, etc experience_level = models.IntegerField(choices=EXPERIENCE_LEVEL, default=1) job_sector = models.IntegerField(choices=JOB_SECTOR, default=1) # IT, Economy work_functions = models.CharField(max_length=50) # as Executive, worker, it guy, etc file = models.FileField(blank=True) # Can post a PDF with more details of the job, but it's totally optional def __str__(self): return str(self.id) + self.title choices.py from AptUrl.Helpers import _ JOB_SECTOR = ( (1, _("Software Development")), (2, _("Analyst")), (3, _("Project Management")), (4, _("Sales")), (5, _("Administrative")), (6, _("Finance")), (7, _("Art/Design")), (8, _("Human Resources")), (9, _("Medical/Healthcare")), (10, _("Cashier")) ) ... When I try to run the following error appears: File "/home/dias/Desktop/Universidade/TPW/jobber/job_app/choices.py", line 1, in … -
Redirect from one page to another by AJAX request, passing parameters with Django
I have a table in a view where according of the element Id which is clicked, that view redirect to another via Ajax request to a Django Rest Framework endpoind and render a dasboard with Chartjs, with dynamic data and sending an user_id. I make the request success and get back the results of the endpoing as json format, but when it should redirect to the other page, it redirects to an empty html template displaying the json result but without my html template. This probably is a really dummy problem, but I can't figure out the error. This answer have an useful code, but hasn't the behaviour that I need My project structure is as below: core --api --core --static --web (...and other folders) These are the routes related: core/urls.py urlpatterns = [ url(r'^socialanalyzer/recent_search_twitter/$', RecentSearchTwitterView.as_view(), name='recent_search_twitter'), url(r'^socialanalyzer/timeline_search_twitter/$', TimelineSearchTwitterView.as_view(), name='timeline_search_twitter') ] api.py/urls.py urlpatterns = [ url(r'^api/search/recent_search/user/<int:user_id>/social_network/<int:social_network_id>', SearchViewSet.as_view({'post': 'recent_search'}), name='recent_search'), url(r'^api/search/word_details/user/<int:user_id>/social_network/<int:social_network_id>/word/<string:word>', SearchViewSet.as_view({'post': 'word_details'}), name='word_details') ] So in my web/views.py, i need to navigate from: RecentSearchTwitterView (recent_search_twitter.html) to TimelineSearchTwitterView (word_searched_details_twitter.html) In that sense, in recent_search_twitter.html I have a table with each row as below: <td><a href="" onclick='wordSearchedDetail("{{key.word}}")'><b>{{key.word}}</b></a></td> That call to wordSearchedDetail where is in: static/js/custom.js function wordSearchedDetail(word){ $.ajax({ url:'/socialanalyzer/timeline_search_twitter/', type: 'GET', data: … -
Django postgres connector psycopg2
As i run pip install psycopg2 in my django virtualven in windows it start downloading and at the end of downloading this Error comes |████████████████████████████████| 430kB 61kB/s ERROR: Command errored out with exit status 1: command: 'c:\users\tusha\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\setup.py'"'"'; file='"'"'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info' cwd: C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info writing C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPIe install the PyPI 'psycopg2-binary' package instead. st' file (also at For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). egg_info Check the logs for full command outpu ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. so how to solve this ERROR -
Is converting timestamp to datetime in django will convert datetime by default to datetime in UTC
I am creating an app which will use peoples from different timezones. I have a model class Fixture(models.Model): fixture_id =models.IntegerField(primary_key=True) event_date = models.DateTimeField(null=True) I want while creating objects from this model that event_date field save datetime object in UTC to convert it in user's timezone while show him this data in front-end. In django documentation i read that When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms. Now i am creating an object b = Fixture.objects.create(fixture_id = fixture, event_date = datetime.datetime.fromtimestamp(variable_contained_timestamp)) Is according django documentation in event_date field will be stored datetime object in UTC not in datetime object with my database time zone -
Can't access foreignKey in template
I'm trying to access a foreignKey object in my template, but it doesn't show anything at all. I'd like to show the url to the ImageField saved in the db Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) taskhtml = Usertasks.objects.filter(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: imagepath = fullpath + "/" + img task_image = TaskImages() task_image.UserTasks = task task_image.image = imagepath task_image.save() return render(request, 'dashboard/task.html', {'query':taskhtml}) html {% for item in query.image_set.all %} <img src="{{ item.url }}"> {% endfor %} -
problem with pagination in function based view in django
can’t understand how to use pagination in this kind of function. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products, }) -
Updating to non-standard database in DRF
Using Django Rest Framework, how to execute update/PUT calls to a non-standard database? In my Django project I'm using a separate database for the application data: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'bookstore': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'bookstore.sqlite3'), } } I use the ModelSerializer and ModelViewSet to automatically create the API for me. I loop over the models to automatically generate all the Serializers and ViewSets (quite a big number of tables), the generated classes end up looking like this: ModelSerializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' ModelViewSet: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.using('bookstore').all() serializer_class = BookSerializer I needed to add the using('bookstore') here to make this work. Reading (GET) works fine. When I try to do a PUT update, I get a no such table: book Sqlite error. It seems like the update isn't routed to the bookstore database. For completeness, I use these loops to generate the ModelSerializer and ModelViewSets from the models: ModelSerializer, generator: models = dict(apps.all_models['api']) for name, model in models.items(): class_name = name[:1].upper() + name[1:] + 'Serializer' Meta = type('Meta', (object, ), {'model': model, 'fields': '__all__'}) print(class_name) globals()[class_name] = type(class_name, (serializers.ModelSerializer,), {'Meta':Meta, }) ModelViewSet, generator: models … -
How to make Nginx config file for Django Project?
I made Nginx config for My Django project. For DNS I associate with my IP. But this config not working, when I'm checking xyz.com in web but getting error ERR_CONNECTION_REFUSED. server { listen 80; server_name xyz.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project/project.sock; } } Please correct me if i'm doing wrong. -
how to set username to python request explicitly
Trying to set token and username to python request.get session, so that next consecutive session.post must have both the session and username. I am able to set the token, however I tried setting the username, but next post call doesn't carry it. request.session['account_token'] = encoded_token - this works request.user = username - doesn't work Expected result should be - with the get call, I should be able to set the username and encoded token to the session and using these set values next post call should be able to authenticate the request and proceed as intended. -
Save data from radio button to database Django
I need to know how to save data to database if I use radio button and it name is inconstant becuase I use template tag for name value. I want to save item.id in database, I can use function save() but in this case I don't know what is parameter that I should to save. models.py (It's in different app) #in item app class Item(models.Model): item_name = models.CharField(max_length=255, blank=True, null=True) #in borrow app class Borrow(models.Model): borrow_date = models.DateField(auto_now=False, auto_now_add=True, editable=False) return_date = models.DateField(auto_now=True, auto_now_add=False) class Borrow_Item(models.Model): borrow_id = models.ForeignKey(Borrow, on_delete=models.PROTECT) item_id = models.ForeignKey(Item, on_delete=models.PROTECT) item\views.py def item(request): item_list = Item.objects.all() items = request.GET.get([some parameter that I don't know]) items = Borrow_Item.save([some parameter]) context = { 'item_list': item_list, } return render(request, 'item/main-item.html', context) main-item.html <form method="GET" action="{% url 'item' %}"> <input type="submit" value="SAVE"> {% for item in item_list %} <input type="checkbox" name="item{{item.id}}" value="{{item.id}}">{{item.item_name}} {% endfor %} </form> -
How can i perform PUT request using ajax and jquery in Django?
I have been struggling for hours trying to update my database in django using PUT request. I'm gathering my data from a form and I want to update a database entry based on the text which the user types. I specifically have to use PUT request method but I have no idea how to do it. Any help would be greatly appreciated Here i am getting the data from the form: $("#modify-btn").click(function(){ console.log('modify pressed') $.ajax({ url : "{% url 'modify item' %} ", method : "POST", data: $("#detailsForm").serializeArray(), success : function (data) { console.log(data.id,data.name,data.brand,data.model) ///// $.ajax({ /// this is where i need to use the PUT request url : }) /// } }) }) This is my views.py file: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.template import loader from phonemodels.models import Phone def index(request): return render(request,'phonemodels/index.html',{ 'phones' : Phone.objects.all(), }) def items_json(request): return JsonResponse({ 'phones' : list(Phone.objects.values()) }) def new_item(request): phone_name = request.POST['Brand'] phone_model = request.POST['Model'] phone_price = request.POST['Price'] phone = Phone (brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price) phone.save() return JsonResponse({ 'id' : phone.id, 'brand': phone.brandName, 'model' : phone.phoneModel, 'price' : phone.phonePrice }) def modify_item(request): phone_name = request.POST['BrandModify'] phone_model = request.POST['ModelModify'] phone_price = request.POST['PriceModify'] phone = Phone.objects.get(brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price) phone.id … -
SQLite 3.8.3 or later is required (found 3.7.17)
I completed my project and uploaded into the host using cpanel and install all my necessary packages. but now when run the server I have this error : SQLite 3.8.3 or later is required (found 3.7.17). I can't upgrade the sqlite3 with pip install --upgrade sqlite3 my database is sqlite3 how can i fix this problem???? -
Django How can I unittest a wait function for db written in bash script when using dockerized database service?
After searching stackoverflow for a while, I found plenty of ways to check if dockerized database service is ready before connection. So I include both of them here. first one is written in bash script and I found it in here if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec "$@" The second one is written in python and I found it in here: class Command(BaseCommand): """Django command that waits for database to be available""" def handle(self, *args, **options): """Handle the command""" self.stdout.write('Waiting for database...') db_conn = None while not db_conn: try: connection.ensure_connection() db_conn = True except OperationalError: self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) I use this docker command ENTRYPOINT ["/usr/src/app/entrypoint.sh"] to run the first one. I know how to write unit tests for the second one, because it's in python. But can anyone help me find a way to write tests for the first one? In addition, Can anybody name what are the drawbacks and advantages of each method and also if there exists some other important considerations for writing such function? Thanks -
(migrations table) django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
When I run migrate it raises this error. I can't figure out where can be the problem because it is caused by the built-in functionality of adding migration data inside the migrations table. Running migrations: Applying matches.0023_auto_20191102_1717...Traceback (most recent call last): File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, matches, 0023_auto_20191102_1717, 2019-11-02 17:17:38.046421+01). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 71, in record_applied self.migration_qs.create(app=app, name=name) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, … -
Login page as startpage in Django
Currently I have my home view as my homepage by the following in urls.py: url(r'^$', views.home) I added a login form today with a template in /templates/registration/login.html and the following in urls.py: path('', include('django.contrib.auth.urls')) This works great but I have been trying to find how I can set a login path as homepage, I tried with the following uncommented lines: from django.conf.urls import url from . import views from django.urls import path, include #from django.contrib.auth.views import LoginView urlpatterns = [ path('', include('django.contrib.auth.urls')), #url(r'^$', views.login), #url(r'^login/$', include('django.contrib.auth.urls')), url(r'^$', views.home), -
Django 'ImageFileDescriptor' object has no attribute 'save'
I'm trying to save this Image to the db with a ForeignKey attached also, so I can look it up later. When trying to save it , I just get this error 'ImageFileDescriptor' object has no attribute 'save' Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: imagepath = fullpath + "/" + img with open(imagepath, 'rb') as f: data = File(f) TaskImages.image.save(img, data, True, UserTasks=task) return render(request, 'dashboard/task.html', {'path':fullpath, 'image':files}) -
are there any ways to add paginator to search results page in django?
I want to ask if there any way for add paginator to my search results when i'm using chian i mean like this (Multi Databases) I have tried many ways for do this but it's doesn't work I have this in views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) # results= sorted(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database),key=attrgetter('name')) results = sorted( chain(pcprograms_database,home_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database), key=attrgetter('name'),reverse=True) paginator = Paginator(results, 2) # Show 25 rows per page page = request.GET.get('page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') -
DRF nested instance update has blank validated_data
I'm using Django 2.x and DRF. I have two models class Component(Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, default='Unnamed') group = models.ForeignKey(AnalyticsGroup, on_delete=models.CASCADE) class ComponentData(Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='data') analytics_type = models.ForeignKey(AnalyticsType, on_delete=models.PROTECT) User can create/update ComponentData object using Component serializer and for that, I have class ComponentDataSerializer(serializers.ModelSerializer): class Meta: model = ComponentData fields = [ 'id', 'analytics_type', ] class ComponentSerializer(serializers.ModelSerializer): data = ComponentDataSerializer(many=True) class Meta: model = Component fields = [ 'name', 'group', ] def create(self, validated_data): component_data = validated_data.pop('data') component = Component.objects.create(**validated_data) for data in component_data: ComponentData.objects.create(component=component, **data) return component def update(self, instance, validated_data): component_data = validated_data.pop('data') # Update instance for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() # Update or create component data for data in component_data: # data.items() has no data and prints # Updating with data: odict_items([]) print('Updating with data: {}'.format(data.items())) return instance def to_representation(self, instance): response = super().to_representation(instance) response['group'] = AnalyticsGroupSerializer(instance=instance.group).data return response I have overridden create and update method to create nested objects as well. create is working fine but with update method, there are OrderedDict() objects in the validated_data.pop('data') field but the OrderedDict object has no data in it. The request body has data: group: "2" data[0].id: "1" data[0].analytics_type: … -
Why can I retrieve environment variable in one part of my code, but not another?
I've stored an API token as an environment variable in my wsgi file. I'm able to retrieve it in one instance in my Django app, but not another. I'm able to use the token successfully during a save_model operation in my admin. When I use nearly identical code in a management command I get an auth error. My wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application os.environ['SLACK_TOKEN'] = '12344567890qazxswedcvfrtgbnhyujmkiolp' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() Working admin.py usage: import os from slacker import Slacker def save_model(self, request, obj, form, change): if obj.condition == True: super().save_model(request, obj, form, change) token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#test-channel', 'mymessage') Not working management command usage: import os from slacker import Slacker def handle(self, *args, **options): try: #test condition except: token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#newsflow-test', 'mymessage') Troubleshooting indicates the env variable isn't loading -- print(token) produces None response when I run the management command or try to retrieve the token in the Django shell. -
Django doesn't pull data from fetch()
I'm using fetch() to make an ajax call to my server. request.POST returns an empty QueryDict while request.body retuns my actual data. Why am I doing wrong?!? Here's my js code: fetch(url, { method: "post", credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify(data) }) .then(async res => ({ status: res.status, body: await res.json(), isOk: res.ok })) -
I have problem with connect django and mysql
I have a problem connecting the mysql database with django. I have already tried to find solutions on the internet but nothing helped me. When I change the code in the 'setting.py' file and then enter 'python manage.py migrate' in the console: (blog) PS C:\Users\kacpe\Dev\blog\blog\blog> python manage.py migrate Traceback (most recent call last): File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\MySQLdb\connections.py", line 166, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, <NULL>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\validation.py", … -
Blank Page right after django form submit
I have a django code that is supposed to post the comments to a detailview but right after I click the submit button in the form, it directs me to a blank page and it also didn't post the comment in the detail view I have added a get_absolute_url but it still doesn't work, it keeps directing me to the blank page #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) context['form'] = CommentForm() return context #detail.html <form method="POST"> {% csrf_token %} <h3>Write a New Comment</h3> <div class="messagebox"> {{ form|crispy }} <button class="btn" type="submit"> Post Comment </button> </div> </form> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment'] #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) def get_absolute_url(self): return reverse("messaging-detail",kwargs={"id":self.id}) Any help would be appreciated, Please provide some code instead of just linking me to a documentation -
Loop in Django Template via JSON Data
i will to loop through this Json data in my Django Template. However, I have achieve it but I have some similar array which I find difficult to loop through because of the Similarity in their name. Like I have two flightSegment. {'segments': [{'flightSegment': {'departure': {'iataCode': 'JFK', 'terminal': '4', 'at': '2020-02-02T19:31:00-05:00'}, 'arrival': {'iataCode': 'AMS', 'at': '2020-02-03T09:10:00+01:00'}, 'carrierCode': 'KL', 'number': '6007', 'aircraft': {'code': '76W'}, 'operating': {'carrierCode': 'DL', 'number': '6007'}, 'duration': '0DT7H39M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'AMS', 'at': '2020-02-03T10:20:00+01:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2F', 'at': '2020-02-03T11:45:00+01:00'}, 'carrierCode': 'KL', 'number': '2007', 'aircraft': {'code': '321'}, 'operating': {'carrierCode': 'AF', 'number': '2007'}, 'duration': '0DT1H25M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'NLSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-03T13:15:00+01:00'}, 'arrival': {'iataCode': 'ABV', 'at': '2020-02-03T19:20:00+01:00'}, 'carrierCode': 'KL', 'number': '2054', 'aircraft': {'code': '332'}, 'operating': {'carrierCode': 'AF', 'number': '2054'}, 'duration': '0DT6H5M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLSRNG'}}]} -
Django save ImageField to ForeignKey object
I'm trying to save images in a folder and bind it to another database object using ForeignKey, so I can look it up later. I have the code for grabbing the images in the folder and now i'm just trying to save them. My current error is: 'ImageFileDescriptor' object has no attribute 'save' Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: fullpath = os.path.abspath(img) with open(fullpath, 'rb') as f: data = File(f) TaskImages.image.save(img, data, True, UserTasks=task) return render(request, 'dashboard/task.html', {'path':fullpath, 'image':files})