Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How torrent sites live-update its torrent file's seeds and leeches? [on hold]
I'm new to programming through python. I like to create a Django based torrent sharing site. but I have a problem with seeds and leeches, It is, How torrent sites live update its torrent file's seeds and leeches. Is it some kind of Ajax technique? if you could, please describe it from python based examples. thank you. -
Django inline formset
I have a parent and several child forms using an inline formset. It works fine. Depending on a value in the parent form, I need to check that the right number of child forms has been submitted. I know I can access the parent form using self.instance.FOO when overriding BaseInlineFormSet and again this works fine, but I can't find a way to determine how many actual forms have been submitted and vitally have data in them. Anyone know how? Many thanks -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 6: invalid continuation byte
I tried a number of solutions on line, but still got the same error at my browser http://127.0.0.1:7000/json/json_data_dump. Can anyone please help? By the way, if I do below and only insert the non-French character in Teradata, my code will work. CREATE TABLE tablename( Category varchar(80) not null, -- CHARACTER SET UNICODE, Below is the python code: def json_data_dump(request): sql = """ select category as dept from db.tablename order by 1;""" df = pd.read_sql(sql, teradata_con()) df_dept = df[['dept']].drop_duplicates() dic = {'dept':[]} for index, row in df_dept.iterrows(): dic['dept'].append({ 'dept':row['dept'].decode('latin-1').encode("utf-8") #.encode("utf-8") #.decode('latin-1') #decode("utf-8") }) return HttpResponse(json.dumps(dic,encoding = "ISO-8859-1")) # return HttpResponse(json.dumps(dic,ensure_ascii=False) ) -
Where is User Class using MongoDB(Djongo) in Django
I am using Django2.1 with MongoDB, Djongo ORM. as you can see the documentation of Djongo is very short and incomplete. I want to write a custom user model that inherits from the django's original User Model. since it's nosql and MongoDB, I've installed djongo and all my models inherits from djongo.models.Model, not standard django.models.Model. and unfortunately this djongo.models unlike django.models has no such a class named User. but somehow there is a auth_user collection im my mongoDB after makemigration and migrate my project and registered normally in my admin panel. I understand probably there is no such a thing "inheritance" in nosql database, if that's so, where is this user model that creates auth_user collection ind DB and holds all my user's info. I want to manipulate it directly. Regards. -
Django calling a function and coming back to same function
Currently I have around 5 functions where I use a common code. I was trying to keep this common code as a function and call in these 5 functions. This will be my common function: def commonfunc(key): do something These are kind of my other 5 functions where I use this common code. To change something I have to edit all my 5 functions. I am looking to call this common function in these 5 common functions. def func1(request) do something... commonfunc(key) use commonfunc.... return httpsresponse(request,.....) In this code everything works till second line. Thereafter it does not comeback to func1 and do rest of things. What I am missing? -
Add Json data to Django model automatically and only once
I created a method that saves Json data to a Django model: models.py: class Object(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) @classmethod def save_json_data_to_model(cls): with open('data.json', encoding='utf8') as file: data = json.load(file) for obj in data: Object( name=obj['name'], address=obj['Street']).save() When i was testing the project I ran the method in the shell and everything is working fine. But I want the data to be populated in the model automatically and only one time. What is the best way to achieve this? I tried this in views.py: if __name__ == '__main__': Obj.save_json_data_to_model() -
Changing a function based view to a class based view
How would one change this function based view into a class based view? It represents a post view with a comments section. def post_detail(request, pk): post = get_object_or_404(Post, id=pk) comments = Comment.objects.filter(post=post).order_by('-id') is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(post=post, user=request.user, content=content) comment.save() resp = post.get_absolute_url() return HttpResponseRedirect(resp) else: comment_form = CommentForm() context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), 'comments': comments, 'comment_form': comment_form } return render(request, 'feed/post_detail.html', context) -
How to generate Bootstrap DatePicker datesDisabled dynimcally
Working with Django and Ajax. I have used Ajax to get my dynamic dates, now the issue is feeding the dates to the datesDisabled: [] array. When i alert(data) i get my dates alerted perfectly. Now i just need to pass the array to the datesDisabled. <script> (function($) { 'use strict'; $(document).ready(function() { $("#id_unit").change(function () { let unit_id = $(this).val(); $.ajax({ url: {% url 'unit_booked_date' %}, data: { 'unit': unit_id, }, success: function (data) { return data } }) }); $('.input-group.date').datepicker({ autoclose: true, todayHighlight: true, allowClear: true, datesDisabled: [ data ], }); }); })(window.jQuery); </script> -
Timezone randomly changes in Django admin
There are two instances of a Django project deployed using uWSGI server with NGINX proxy on Ubuntu server 14.04. In settings I have: TIME_ZONE = 'Europe/Moscow' # UTC +03.00 USE_TZ = True On one instance Dates and Times are displayed in correct time zone. On another instance time zone keeps changing between +03.00 and +12.00 and I didn't manage to notice any pattern in that. I checked: Ubuntu time zone with timedatectl status (the same on both servers) PostgreSQL timezone (the same on both servers) uWSGI and NGINX setting are kept in VCS, so they are the same as well (although doesn't seem to have anything time zone related) The only difference I can think of is that the properly working instance is on Azure, while the problematic one is physically hosted in UTC +03.00 (local cloud provider). However, other Django projects hosted there work properly. What else can I check to isolate and solve this problem? -
dj-stripe UpcomingInvoice usage
Towards the end of a free trial period I am trying to send customers a notification that they will soon be charged with dj-stripe. I am trying to use a webhook to initiate the notification and then UpcomingInvoice to retrieve the amount. I can see in my stripe dashboard that I have customers with trial ending tomorrow and an upcoming invoice, however dj-stripe always returns an empty queryset. In PDB when I try the code I also can't see any calls to the stripe api which would need to occur to pull the data. @webhooks.handler("customer.subscription.trial_will_end") def charge_upcoming(event, **kwargs): UpcomingInvoice(customer=event.customer).invoiceitems pdb.set_trace() <QuerySetMock []> What am I doing wrong? Thanks! -
Connexion impossible avec mon plist pour ipa (django)
Bonjour, J'ai fais un petit code pour télécharger mon ipa, son un iphone. J'ai utiliser plist, pour le télécharger. Cependant, quand j'essaye de le télécharger, il me dis "Connexion à monsite.com impossible". Je n'arrive pas a comprend d’où viens le problème? Voici mon code : return HttpResponse('<a href="itms-services://?action=download-manifest&url=https://polymission.polymont-itservices.fr/download/manifest.plist">Install ME!</a>') Merci d'avance :) -
Celery apply_async get get called multiple times
I have created a task @app.task(bind=True, max_retries=1) def notify_feedback(self, req_id): #some things I have called this task from my view with a delay of 1 hour like later = datetime.datetime.utcnow() + datetime.timedelta(hours=1) notify_feedback.apply_async((req_id,), eta=later) When I checked the SQS Messages in Flight it has 1 count pending after one hour this notify_feedback get called multiple times. Did any one encountered this kind of issue with celery? celery- 4.1.0 is used -
Pipenv installationError: Command "python setup.py egg_info" failed with error code 1 in
I have recently moved over to using pipenv and every now and then I get the following error when trying to install packages: $ pipenv lock --clear --verbose pipenv.patched.notpip._internal.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in $ pipenv install social-auth-core line 704, in from_line line, extras = _strip_extras(line) TypeError: 'module' object is not callable $ python setup.py egg_info (k, v) for k, v in attrs.items() File "/home/user/.local/share/virtualenvs/django-app-VE-name/lib/python3.6/site-packages/setuptools/dist.py", line 367, in __init__ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): AttributeError: module 'pkg_resources' has no attribute 'iter_entry_points' The github pages for the error have not been helpful, thank you -
Serving static content with Django, Gunicorn and Ngnix in shared development environment
I have seen many great answers to this question here on SO, but either I don't understand them or they don't apply to my particular circumstance. I have looked here: Serving static files with Nginx + Gunicorn + Django and many others. I have followed the recommendation in those answers and I still do not have solution that works. I hope that if I explain exactly what I am doing then maybe someone will tell me where I went wrong. I developing in a shared environment with several other teams and we share an ngnix server. I have a Django project on this shared server, sre-dev.example.com. The path to the Django project is /apps/capman/capman_port10001/capman. In my settings.py I have these values set: STATIC_ROOT = '/apps/capman/capman_port10001/capman/static' STATIC_URL = '/static/' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', ... 'django_db_logger', 'rest_framework_swagger' ] I have created a /etc/nginx/sites-enabled directory and sym link, ln -s /apps/capman/capman_port10001/capman/nginx.conf caasa-dev.example.com I also created alias (CNAME), caasa-dev.example.com in our DNS for sre-dev. And in added a nginx.conf file, /apps/capman/capman_port10001/capman/nginx.conf with the contents of: server { listen 10001; server_name caasa-dev.example.com; location /static { alias /apps/capman/capman_port10001/capman/static/; } } I have executed ... python manage.py collectstatic ... … -
RuntimeError: Model class users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
there I am having trouble searching for the solution for the error posted above for a long time. I looked at several of other similar questions on StackOverFlow but could not figure it out. The exact error is the following: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10473e840> Traceback (most recent call last): File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate app_config.ready() File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "~/@Python_project/webservice/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "~/@Python_project/webservice/applications/users/admin.py", line 1, in <module> from applications.users import models File "~/@Python_project/webservice/applications/users/models.py", line 38, in <module> … -
Django Rest Framework update() with kwargs from validated_data
Can I update instance in one line without specifying all instance fields? For example: def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.save() return instance So imagine if there's many more fields next to name and address. Can I do something extracting kwargs from validated_data? Just like in create() method: def create(self, validated_data): return Person.objects.create(**validated_data) -
Django : array within a query string as foo[]=bar1&foo[]=bar2
I need to prepare a Django microservice that offer the following url pattern : http://<myserver>/getinfo/?foo[]=bar1&foo[]=bar2 it seems to be a very PHP way of doing but i have to mimic it in django ... Is there a standard way in Django for both designing the URL and retrieving the querystring parameter as a list in the View ? -
Adding fields for User in admin page in django
This problem seems to be very simple, yet i can't find solution. I needed to extend my User model (add phone number) in django, and i picked the way of creating another model called UserInfo that is related 1to1 with User model. It works fine, the only problem is that I can't get the UserInfo fields (the phone number) to show up on User page in admin panel. What i tried: from app.models import UserInfo from django.contrib import admin from django.contrib.auth.models import User class UserInfoInline(admin.TabularInline): model = UserInfo class UserAdmin(admin.ModelAdmin): inlines = [UserInfoInline,] admin.site.register(UserInfo) -
Django WebDriverException at /test Message: connection refused
I am using Mozilla Firefox 59.0.2 Ubuntu 18.04 geckodriver 0.23.0 ( 2018-10-04) Selenium '3.141.0' driver = webdriver.Firefox(profile,executable_path="/usr/local/bin/geckodriver", log_path="/home/user/Project/geckodriver.log",firefox_options=firefoxOptions) when I execute it I get the following error message: WebDriverException at /test Message: connection refused -
Can't POST on django admin - Can't concat bytes to string
I'm using Django 2.0.9 and Python 3.4.2 on an apache 1and1 shared hosting. When I make any POST HTTP request to my Djando app, I get the following message: Traceback: File ".../python3.4/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File ".../python3.4/site-packages/django/core/handlers/base.py" in _get_response 119. response = middleware_method(request, callback, callback_args, callback_kwargs) File ".../python3.4/site-packages/django/middleware/csrf.py" in process_view 289. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File ".../python3.4/site-packages/django/core/handlers/wsgi.py" in _get_post 115. self._load_post_and_files() File ".../lib/python3.4/site-packages/django/http/request.py" in _load_post_and_files 302. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() File ".../python3.4/site-packages/django/http/request.py" in body 263. self._body = self.read() File ".../python3.4/site-packages/django/http/request.py" in read 322. return self._stream.read(*args, **kwargs) File ".../python3.4/site-packages/django/core/handlers/wsgi.py" in read 36. result = self.buffer + self._read_limited() Exception Type: TypeError at /adminlogin/ Exception Value: can't concat bytes to str I posted the trace of admin login page, but it's the same problem with any POST request. Here is my settings.py: #Cookie Domain CSRF_COOKIE_DOMAIN='mydomain.es' SESSION_COOKIE_DOMAIN = ['mydomain.es', 'www.mydomain.es', 'localhost'] BASE_URL='mydomain.es' CSRF_TRUSTED_ORIGINS=['mydomain.es'] ALLOWED_HOSTS = ['localhost', 'mydomain.es', 'www.mydomain.es'] SESSION_EXPIRE_AT_BROWSER_CLOSE=True Application definition INSTALLED_APPS = [ 'myapp.apps.MyAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'import_export', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_inlinecss', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['...myappdir/amma/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
When click change password is blank page but password was changed django
I create login page. My problem is with "forgotten password". User enter a mail and django send a message with link. When click on it must change password. When complet click on "Change password" we should move on next page but it is blank. But password was changed. account/urls.py from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'), path('logout/', auth_views.LogoutView. as_view(template_name='registration/logout.html'), name='logout'), path('logout_then_login/', auth_views.logout_then_login, name='logout_then_login'), path('dashboard/', views.dashboard, name='dashboard'), path('password_change/', auth_views.PasswordChangeView. as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change_done/', auth_views.PasswordChangeDoneView. as_view(template_name='registration/password_change_done.html'), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView. as_view(template_name='registration/password_reset_form.html', html_email_template_name='registration/password_reset_mail.html'), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView. as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView. as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView. as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete') ] password_reset_complete.html {% extends "base.html" %} {% block title %} <p>Password was changed</p> {% endblock %} settings.py LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard') LOGIN_URL = reverse_lazy('account:login') SUCCESS_URL = reverse_lazy('account:password_change_done') -
Trying to pass django-oscar products to custom template
I'm working on a custom template using a forked version of django-oscar apps (to have custom models). I am trying to display a list of all the products in the product table, just to start with. I looked at django-oscar templates but as they rely on a lot of custom tempaltetags I found it too complex to rewrite everything to work with my models. This is what I have in my views.py: def product(request): template = loader.get_template('/home/mysite/django_sites/my_site/main_page/templates/main_page/product.html') prodlist = Product.objects.all() return HttpResponse(template.render({}, request), context={'prodlist': prodlist}) And the code I am using in my template to try and display it {% for instance in prodlist%} <li>{{ instance.name }}</li> {% endfor %} However, this gives me an error TypeError at /product/ __init__() got an unexpected keyword argument 'context' /product corresponds to my product view in my urls.py This was my best guess from following tutorials and looking at other answers. What am I getting wrong? -
Django DB data delete and backup
I have one django project. Some data is restored in the Model database. But in the web, there is some function to delete such data for the new demonstration in the page. However, I don't want to complete delete such data for possible further usage like statistics. How could deal with such issues normally? I can think about transferring such data to another Model database before deleting, but is it too complicated? Or any other suggestion? Thx! -
Display log file on the page using Django
I am new to Django. I'm trying to display a log file which changes its contents dynamically because of background scripts writing into it. Now, I need to display it on my page. I'm using Django. I initially started with displaying a static file but that too isn't working. I am trying to do it using JS and no JQuery. -
Sub Columns in django admin
hH is there any libary or method to make one column and under it sub columns in django admin like on picture. Sub columns