Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store ChangeList object for access in later requests
I'm trying to store a ChangeList object that I need access to in another (ajax) request. I need to get the (filtered) queryset from the changelist. This is (parts of) the code: class TimeReportEntryAdmin(admin.ModelAdmin): ... def changelist_view(self, request, extra_context=None): changelist = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter, self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_max_show_all, self.list_editable, self) # i'd like to store the changelist object here ... I've tried storing the ChangeList object in the cache with: cache.set("time_report_changelist_%s" % request.user, changelist, 0); This gives me a PicklingError: Can't pickle <type 'module'>: attribute lookup __builtin__.module failed And storing in in the session doesn't work: request.session["time_report_changelist"] = changelist This gives me a TypeError: <django.contrib.admin.views.main.ChangeList object at 0x1051da890> is not JSON serializable Perhaps there's a completely different approach to this? Thanks for any help. -
Scheduler is not running jobs
I have some code here as: from apscheduler.schedulers.background import BackgroundScheduler def myjob(): print('hello') scheduler = BackgroundScheduler() scheduler.start() scheduler.add_job(myjob, 'cron', hour=0) This is just a sample code. In my project, I'm adding so many jobs. But these jobs are not running at all. I found one reason on apscheduler doc as: The script above will exit right after calling add_job() so the scheduler will not have a chance to run the scheduled job. After searching on internet I found something like this: import time while True: time.sleep(1) But further this creates problem while restarting application, it prevent application from restarting. My requirement is to use BackgroundScheduler not BlockingScheduler. So my question is 1) how to solve this problem ? 2) Is there any working way to keep my scheduler alive? -
Client send ws://[host]:[port]/path to server, and my server is Nginx+uwsgi+Django,But I always meet 404 error when I launch get to server
Websocket cannot be accpeted by Nginx+Uwsgi to my Django I have add some to my nginx.conf { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Origin xxx; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; } but it still not work and when I see the brower I see this Status Code:404 Not Found -
Video Upload and display on a Django Website
I have a model where I upload a video, i want to display the same in the browser but somehow I am not able to. Kindly help me. I made an app with the name deploy, where I am uploading the video and saving it. Kindly tell me where I am doing wrong and what should be done here. I want the video which was uploaded should be displayed on the page and there should be a option for download as well. I shall be extremely thankful for the help. My models.py file: class Video(models.Model): Video_Description= models.CharField(max_length=500) slug = models.SlugField(unique=True) videofile= models.FileField(upload_to='deploy/videos/%Y/%m/%d/', null=True, verbose_name="") timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timestamp'] def get_absolute_url(self): return reverse ("deploy:detail", kwargs={"slug":self.slug}) def __str__(self): return self.Video_Description + ": " + str(self.id) My views.py file is: class VideoDetailView(DetailView): queryset = Video.objects.all() class VideoListView(ListView): paginate_by = 10 # <app>/<modelname>_list.html def get_queryset(self, *args, **kwargs): qs = Video.objects.all() print(self.request.GET) query = self.request.GET.get("q", None) if query is not None: qs = qs.filter( Q(Video_Description__icontains=query) | Q(videofile__icontains=query)) return qs def get_context_data(self, *args, **kwargs): context = super(VideoListView, self).get_context_data(*args, **kwargs) return context video_list.html file is: <br><br> <video width='400' controls> <source src="{% static 'deploy/object.videofile' %}" type='video/mp4'> Your browser does not support the video tag. … -
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
My main codes part: class AutoManagementServiceV2(object): def __init__(self): self.plan_lists = SmbAmmRuleCampaign.objects.filter(status=1) self.chunk_size = 50 def run(self): new_loop = asyncio.new_event_loop() # plan_lists = SmbAmmRuleCampaign.objects.filter(status=1) self.iter_plans = ( self.plan_lists[i:i + self.chunk_size] for i in range(0, len(self.plan_lists), self.chunk_size) ) asyncio.set_event_loop(new_loop) for chunk_plans in self.iter_plans: task_list = [ asyncio.ensure_future(self._handle_campaign_data(campaign_plan)) for campaign_plan in chunk_plans ] new_loop.run_until_complete(asyncio.gather(*task_list)) def auto_manage(): AutoManagementServiceV2().run() if __name__ == '__main__': auto_manage() model SmbAmmRuleCampaign : class SmbAmmRuleCampaign(models.Model): campaign_id = models.CharField(max_length=64, blank=True, null=True) rule_id = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) smb_user = models.IntegerField(blank=True, null=True) account_id = models.CharField(max_length=64, blank=True, null=True) access_token = models.CharField(max_length=255, blank=True, null=True) user = models.CharField(max_length=64, blank=True, null=True) need_execute = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'smb_amm_rule_campaign' main.py use apscheduler to execute every 3 hours scheduler = baseScheduler.scheduler scheduler.add_job( func=auto_manage, trigger='interval', hours=3, start_date=(datetime.datetime.now() + datetime.timedelta(seconds=20)).strftime("%Y-%m-%d %H:%M:%S"), id='auto_manage', jobstore='default', replace_existing=True) scheduler.start() There are many rules I want to execute in a batch way regularly. It works well as expected At first, but after several hours, I got Lost connection to MySQL error as below: Error : Traceback (most recent call last): File "/data/home/smb/work/smb_auto_management/venv3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/data/home/smb/work/smb_auto_management/venv3.5/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/data/home/smb/work/smb_auto_management/venv3.5/lib/python3.5/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/data/home/smb/work/smb_auto_management/venv3.5/lib/python3.5/site-packages/pymysql/cursors.py", … -
How to fix Django runserver errors: __path__ and process?
I use Django version 2.1.1 . I want to fix this errors: (myvenv) C:\Python373\mywebsite\myvenv\Scripts\mysite>python -m manage.py runserver C:\Python373\mywebsite\myvenv\Scripts\python.exe: Error while finding module specification for 'manage.py' (ModuleNotFoundError: __path__ attribute not found on 'manage' while trying to find 'manage.py') (myvenv) C:\Python373\mywebsite\myvenv\Scripts\mysite>django-admin runserver Fatal error in launcher: Unable to create process using '"' -
Django 1.11. Is it possible to use user and group names in the fixture for user_group?
Django 1.11 python 3.6 I would like to make existing users to existing groups with a fixture if possible. I do not know user and group ids, only names. I know I can look them up or even write a generator get id maps. I am curious if there is some fixture syntax that would allow me to load a fixture with user and group names directly? E.g.: [ { "model": "auth.user_group", "fields": { "user": "some_user_name_from_user_table", "group": "some_group_name_from_group_table" } } ] -
Is there something I missed for using django's admin to choose an image for the site?
I'm almost done fixing my django portfolio when I bumped into a problem when choosing a photo for one of the pages of my site. Check this -> Django Admin Here is my models.py from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='/img') Did I miss something? -
How to refresh access_token with refresh token if access_token is expired using google.oauth2 library in python?
I'm initializing credentials object in following way and refreshing token if it is expired. The approach mentioned down below. When I used the instance I'm getting error which say ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}') import google.auth.transport.requests from googleapiclient.discovery import build import google.oauth2.credentials from oauth2client import GOOGLE_TOKEN_URI, client try: self.credentials = google.oauth2.credentials.Credentials( self.google_access_token, refresh_token=self.google_refresh_token, token_uri=GOOGLE_TOKEN_URI, client_id=settings.GOOGLE_CLIENT_ID, client_secret=settings.GOOGLE_CLIENT_SECRET) if self.credential.expired: request = google.auth.transport.requests.Request() self.credentials.refresh(request) except: pass self.analytics = build('analyticsreporting', 'v4', credentials=self.credentials) Please provide suggestions. -
django can we prefetch related field on a select related model?
I need to get the latest image of the creator for each event. For example I have 3 models: class Event(..): create_by = ForeignKey(User, related_name='events_set') class User(..): ... class ProfileImage(..): user = ForeignKey(User, related_name='profile_images_set') image = ImageField(..) So i need to get detail info about Event, I have got a guery like this: Event.objects.all().prefetch_related('..').select_related('created_by') The problem is that I also need to get the last image of event creator. I tried Prefetch but it only works to control prefetch_related. Something like this: Event.objects.all().prefetch_related('..').select_related(Prefetch('created_by', queryset=User.objects.latest('pk').prefetch_related('profile_images_set')) -
How to make a ManyToOne in Wagtail with RadioSelect on admin page?
I would like to set up a radio select option in admin for my blog's category. ManyToMany fields do not work with a RadioSelect widget. I want the category to be a ManyToOne relationship with the articles. Right now I have a ParentalManyToMany field and I register the snippet for the blog category. class BlogPage(Page): ... category = ParentalManyToManyField('blog.ArticleCategory', blank=True) ... @register_snippet class ArticleCategory(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) panels = [ FieldPanel('name'), FieldPanel('slug'), ] def __str__(self): return self.name I don't know how to change this into a ManyToOne option, so I could have a radioselect instead of a CheckboxSelectMultiple. Help would be appreciated. Thanks! -
settings.DATABASES is improperly configured. Please supply the ENGINE value in postgres while installing Nadine
I am trying to install Nadine and while running ./manage.py migrate command i am getting the error : raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.strong text -
azure django websocket Error 200 not able to upgrade to websocket
I have a django app that uses websockets that works fine locally but when deployed to azure it results in an error 200 (not able to upgrade to websocket) I have enabled all of AR afininty and web socket inside Azure and always on option and i have tested it on both http(1.1 & 2) not working and results in the same error , i have also modified the web.config to add the websocket enabled (tried both false & true) and not working my web cofig is <configuration> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="chatproject.wsgi.application" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="pythonpath" value="D:\home\site\wwwroot\env\Lib\site-packages" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_venv_handler()" /> <add key="DJANGO_SETTINGS_MODULE" value="chatproject.settings" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python27\python.exe|D:\Python27\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> <rewrite> <rules> <rule name="Django Application" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="false" /> </rule> </rules> </rewrite> <httpErrors errorMode="Detailed"></httpErrors> </system.webServer> <system.web> <customErrors mode="Off" /> </system.web> </configuration> I excpect a response of 1.1 from the request of upgrading to web socket -
Display CheckboxSelectMultiple inputs in one line
How can I display forms.CheckboxSelectMultiple inputs in one line? By default it is looking like this: -
How to get username of user's post in Django REST API instead of number?
I'm trying to get username for iOS app through REST API. I could get user number. How do I get actual username? The "author" should be username of user post. http://127.0.0.1:8000/api/posts/ Result HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "author": 1, "title": "Test Title Post", "contents": "Test contents post" } models.py User = settings.AUTH_USER_MODEL class PostDetail(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="PostDetail.author+") title = models.CharField('*Title', max_length=50) contents = models.TextField('*Contents', max_length=450) serializer.py from rest_framework import serializers from .models import PostDetail from django.contrib.auth import get_user_model from django.contrib.auth.models import User class PostDetailSerializer(serializers.ModelSerializer): class Meta: model =PostDetail fields = (author, title, 'contents', ) apis.py from rest_framework import viewsets, routers from blog.models import PostDetail from blog.serializer import PostDetailSerializer from django.contrib.auth import get_user_model from django.contrib.auth.models import User class PostViewSet(viewsets.ModelViewSet): queryset = PostDetail.objects.all() serializer_class = PostDetailSerializer router = routers.DefaultRouter() router.register(r'posts', PostViewSet) I expect "author": 1, to be like "author": admin,. -
Django format DateTimeField output to {YYYY-MM-DD} {HH:MM AM/PM}
Im using the auto_now_add field for DateTimeField in django and I'm displaying a date like this 2019-05-08T09:23:09.424129Z and I want to convert it to this format {YYYY-MM-DD} {HH:MM AM/PM} without changing the model since we are in production. Most of the examples I found on the web require you to add something in the model any work arounds?. Model created = models.DateTimeField(auto_now_add=True, null=True) -
Nuxt.js-Django project on Heroku
I have an application: Nuxt.js is on frontend and Django is on backend. But how I can both deploy to Heroku? Example of project is bellow: https://github.com/akozyreva/recipe-app -
Generating dummy urls (while unit test) in django using Factory boy
I am trying to write unittest in django. I use Factory Boy in my Django project.Currently, I am blocked at a place where I need to provide dummy url value. How do I do it? -
How can I use "?" character in url path? (django 2.1)
I tried this: path('posts/?page=<int:page_number>', posts_api_view, name="posts") But django shows "Page not found (404)". It works when I delete "?" from path. how can I use "?" character in my path for paginating my posts? -
TypeError- can't subtract offset-naive and offset-aware datetimes For Finding Time Difference
I am trying to find the time difference between clock_in and clock_out. For that i am using save method in model.py. The time differnce between will be stored in clock_duration. But it is giving me TypeError Error - while saving data in model TypeError at /timesheet/clock-out/ can't subtract offset-naive and offset-aware datetimes Models.py from django.db import models from django.conf import settings class Timesheet(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="timesheetuser") clock_in = models.DateTimeField(auto_now_add=True) clock_out = models.DateTimeField(null=True, blank=True) clock_date = models.DateTimeField(auto_now_add=True) clock_duration = models.DateField(blank=True, null=True) def save(self, *args, **kwargs): if self.clock_in and self.clock_out: self.clock_duration = self.clock_out - self.clock_in super(Timesheet, self).save(*args, **kwargs) class Meta: db_table = "timesheet" -
pre-built django project gives error on migrate
I have a pre-built django project, and need to run it on ubuntu 18. Went through & installed all prerequisites, using postgresql as db engine. created a db for project and added user with required privilleges & then updated those settings into settings.py file then I ran following commands to ready migrations & implement it. # python manage.py makemigrations No changes detected & # python manage.py migrate Traceback (most recent call last): File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.ProgrammingError: permission denied to create extension "postgis" HINT: Must be superuser to create this extension. 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/hsn/env_banax_api/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/hsn/env_banax_api/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/hsn/env_banax_api/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 77, in handle connection.prepare_database() File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 26, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/hsn/env_banax_api/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) … -
Shortest way algorithm
I have a places hierarchy like Region-District-City-Vilage, lets imaging that the distance between two places equal to 1, how I can find the shortest way between to places? I think it is impossible -
How to check validation of an IntegerField?
I have a form that have a IntegerField, this field is not required. When I submit my form I'd like to check if this field is correctly filled. The only value that are accepted are 3, 4 or an empty field. forms.py class PhaseCreationForm(forms.ModelForm): typePhase = forms.CharField(label='Type of phase', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the type of the phase'})) nbTeamPerPool = forms.IntegerField(label='Number of teams per pool', required=False, widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'3 or 4'})) nbTeamQualified = forms.IntegerField(label='Number of qualified', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Enter the number of qualified'})) category = MyModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={ 'class':'form-control'})) class Meta: model = Phase fields = [ 'typePhase', 'nbTeamPerPool', 'nbTeamQualified', 'category', ] def clean_nbTeamPerPool(self, *args, **kwargs): nbTeamPerPool = self.cleaned_data.get("nbTeamPerPool") if nbTeamPerPool < 3 or nbTeamPerPool > 4: raise forms.ValidationError("The number of team per pool is between 3 and 4. Please try again.") return nbTeamPerPool When the field is empty I have this error : '<' not supported between instances of 'NoneType' and 'int' I understand this error, I just can't compare None with an integer, so my question is how can I compare none with integer or can you propose me a solution to make empty field accepted ? -
Upload multiple images to news using Django
I am trying to upload multiple images to the News module I have model like this : class News(models.Model): title = models.CharField(max_length=255,null=True, verbose_name ='Title') date = models.DateField(max_length=255,null=True, verbose_name ='Date') class NewsImages(models.Model): news = models.ForeignKey(News, related_name='newsimages',on_delete=models.CASCADE) file_name = models.ImageField(upload_to='news/', max_length=255, null=True, verbose_name ='Image') I have Form like this : class NewsAddForm(forms.ModelForm): class Meta: model = News fields = ['title', 'date'] class NewsImagesAddForm(forms.ModelForm): file_name = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True, 'required' : False})) class Meta: model = NewsImages fields = ['file_name'] My view file is : form_class = NewsAddForm imgform_class = NewsImagesAddForm if request.method=="POST": form = form_class(request.POST, request.FILES) if form.is_valid(): new = form.save(commit = False) new.save() imgform = imgform_class(request.POST, request.FILES) imgform.save(commit = False) for img in imgform: img.news = new img.save() messages.success(request, 'news added successfully') return redirect('listnews') else: form = form_class() imgform = imgform_class() context = {'form' : form, 'imgform' : imgform} return render(request, 'news/add.html', context) So can you please help me what I have done wrong here -
How to noshown the scale while all datasets is hidden (chartjs)?
I was using django and chartjs to render the charts. when I use legend onClick function hidding all the dataset, the yaxis will show like this while I want nothing to be shown, even the gridlines. Is there any solutions or proposal?