Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local desktop not loading updated content for the web app as cloud server
I deployed a Django app in a Windows cloud server using Apache and mod_wsgi. With the url for the app(IP:8000), contents of the lastest version loads successfully on the cloud server but on my local desktop with the same URL, the earlier version loads. The page content has been updated several times before but I never encountered this problem. I never change anything for deployment. Only static picture is changed in this update but Static content changed in earlier updates loads fine. What might cause this and how can I debug this? Thanks. -
Django Import-Export DateTime Naive DateTime Error
Importing DateTime Error Message: RuntimeWarning: DateTimeField Entry.date received a naive datetime (2020-07-20 09:23:19.881763) while time zone support is active. RuntimeWarning) Is there a way a user can select the datetime they are in or at least import the data with +00 added? Currently, I can't seem to be able to import once I add the datetime field. Right now I'm trying this issue solution resources.py class TzDateTimeWidget(DateTimeWidget): def render(self, value, obj=None): if settings.USE_TZ: value = localtime(value) return super(TzDateTimeWidget, self).render(value) class EntryResource(resources.ModelResource): date = fields.Field( column_name='date', attribute='datetime', widget=TzDateTimeWidget(format='"%Y-%m-%d %H:%M:%S"')) class Meta: model = Entry fields = ('date', 'entry_type', 'amount', 'price', 'fee', 'reg_fee', 'id',) import_order = fields skip_unchanged = False report_skipped = True csv file 2020-07-17 7:42:39,,40,14.56,0,Entry,0 2020-07-17 7:47:16,,40,14.78,0,Entry,0 -
How to recieve formdata in django backend
I want to send the recorded wecam video to django backend, But can't figure out how to generate the video in backend. function sendVideoToAPI () { const url = '/upload/' let blob = new Blob(chunks, {type: media.type }); let fd = new FormData(); let file = new File([blob], 'recording'); fd.append('data', file); fetch(url1, { method: 'POST', body: fd }) .then(res => console.log(res)) .catch(err => console.log(err)) } In django views how to generate the video Is there any way to do it..? -
DRF, remove primary key from routed extra action
I have a view with some extra actions: class MonthsViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) def get_queryset(self): query_set = Month.objects.filter(user=self.request.user) return query_set serializer_class = MonthSerializer @swagger_auto_schema( manual_parameters=[AUTH_HEADER_PARAM, MonthParameters.DATE, MonthParameters.DAYS, MonthParameters.FARM]) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) @action(detail=True) def get_next_year(self, *args, **kwargs): """ Return the next 12 months. """ first_month, last_month = get_12_months(last=False) query_set = self.get_queryset().filter(date__range=(first_month, last_month)) serializer = MonthSerializer(query_set, many=True) return Response(serializer.data, status.HTTP_200_OK) @action(detail=True) def get_last_year(self, *args, **kwargs): """ Return the last 12 months available. """ first_month, last_month = get_12_months(last=True) print(first_month, last_month) query_set = self.get_queryset().filter(date__range=(first_month, last_month)) serializer = MonthSerializer(query_set, many=True) return Response(serializer.data, status.HTTP_200_OK) And I'm using the default router in my url: months_router = DefaultRouter() months_router.register('months', MonthsViewSet, 'months') urlpatterns = [ path('', include(months_router.urls)), ] So currently this is my URL: /months/{date}/get_last_year/ the date is the primary key in my model. Is there any way to change the action decorator settings to NOT use the primary key? so the URL would become: /months/get_last_year/ -
Django: validation in models -> is it possible to customize message with data from database that raise the error?
I know there is different way to customize error messages in forms or in models I customize unique message in my model ... ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True) pat = models.CharField("Patient number", max_length=8, unique=True, null=True, blank=True, validators = [ RegexValidator( regex='^[A-Z]{3}-[0-9]{4}$', message= 'L\'identifiant doit être au format XXX-0000', code='invalid_participant_id' ), ], error_messages={'unique': u'Ce patient a déjà été randomisé dans le bras X. Veuillez vérifier votre saisie.'}, ) ... but I would like X in the message be replaced by data from database for example, if user try to enter SMI-0001 that already exist in the database, i would to replace X by ran_bra value of SMI-0001 is it possible? -
How update related fields in django models
I am trying to update Parent model a related record, but getting an error. django.db.utils.IntegrityError: update or delete on table "t_parent" violates foreign key constraint "t_child_marz_name_am_620d4c8d_fk_t_parent_marz_name_am" on table "t_child" DETAIL: Key (marz_name_am)=(Avan) is still referenced from table "t_child". There is my models: class Child(models.Model): child_pk = models.CharField(primary_key=True, max_length=60, blank=True, null=False) marz_name_am = models.ForeignKey('Parent', on_delete=models.CASCADE, to_field='marz_name_am', db_column='marz_name_am', blank=True, null=True) class Meta: managed = True db_table = 't_child' verbose_name_plural = 'Child' def __str__(self): return self.child_pk class Parent(models.Model): marz_name = models.CharField(primary_key=True, max_length=60, blank=True, null=False) marz_name_am = models.CharField(max_length=60, blank=True, null=False, unique=True) class Meta: managed = True db_table = 't_parent' verbose_name_plural = 'Parent' def __str__(self): return self.marz_name When I delete a record everything works well. I tried to reassign the save() method, but I got an error about infinite recursion (maybe I did something wrong ...); I read that I can reassign the pre_save(), post_save() method - but as I understand it, they are used mainly for checks before saving and in general I do not know how to do this. P.S. This is just an example of the models for which I am testing the problem! -
Not receiving emails with celery
I'm trying to send an email to a user when the order.manu_date is due in 7 days. On my terminal I'm successfully running the task and getting this response "Task accounts.tasks.check_for_orders[c30bdf70-d4ad-451e-8ecb-316a8245c7a1] succeeded in 0.030911363999990726s: None", but I'm not receiving any emails in my gmail. celery.py from __future__ import absolute_import, unicode_literals from django.conf import settings from celery.schedules import crontab import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dash.settings') app = Celery('dash') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') app.conf.beat_schedule = { 'celery_test': { 'task': 'accounts.tasks.check_for_orders', 'schedule': crontab(), }, } # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @shared_task def check_for_orders(): orders = Order.objects.all() now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc,second=00, microsecond=00) week_old = now - datetime.timedelta(weeks=1) for order in orders: if order.manu_date == week_old: send_mail('Manufacturing Reminder', '{{Order.id}} is due {{manu_date}}', 'dummyguy1680@gmail.com', ['dummyguy1680@gmail.com'], ) return None EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER ='dummyguy1680@gmail.com' EMAIL_HOST_PASSWORD ='password' CELERY_BROKER_URL = 'amqp://myuser:mypassword@localhost:5672/myvhost' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = … -
How can I delete user made by django rest_auth in admin page
I made a user using rest_auth. And I want to delete those users from the django_admin page. But when I try to delete it, the following error occurs. OperationalError at /admin/auth/user/ no such table: allauth_socialaccount Through the search, I got results to put 'allauth.socialaccount' in INSTALLED_APPS, but this didn't help me. how can I solve it ? -
In Django form, is there an equivalent for initial={'authuser':request.user} in formset_factory?
[Short version of the question] So I have been using normal forms so far. In this case, I used form = myForm(initial={'authuser':request.user}) code to distinguish the user from others and let him/her fill his/her own form. (I had authuser as foreign key to User model, obviously). But then I tried to use inlineformset_factory this time, but can't figure out how to do what I've done with normal forms. Any advice on this? Thank you very much. [Longer version of the question] So I have the following model. class Question(models.Model): questionNumber = models.IntegerField(primary_key=True) title = models.CharField(max_length=20, default="") question = models.CharField(max_length=100, default="") def __str__(self): return self.questionNumber class Answer(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None) questionTitle = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, default=None) answer = models.CharField(max_length=500) dateAnswered = models.DateTimeField(auto_now_add=True) def __str__(self): return self.questionTitle What I'm trying to do is let users answer to each question. But here I'm trying to use inlineformset_factory, since I want to let user add their answers as time goes by. So I believe I'll have to use Question as the parent model and Answer as the child model. However the problem is, how do I let each user fill in his/her own answer form? In normal forms, I used form … -
I dropped a collection, Can I remove related migration files?
I dropped the 'test' collection via MongoDB Compass. The last migration file's number is 28. Migration files 16-28 are only relevant for 'test'. So is it okay to remove the 16-28 migration file? -
Django-photologue: To generate image title and slug automatically during save
I am using Django-Photologue in my project. I want to generate image title, slug automatically during save, if not specified. As a newbie in Django, I dont know how to do this. If I have to customize Django-photologue, then how should I do it? -
How to render the items from the views to the template?
I am a beginner in django and I have encountered a problem here . My models from django.db import models # Create your models here. class course_name(models.Model): faculty_name=models.CharField(max_length=100) def __str__(self): return self.faculty_name class subject(models.Model): subject_name=models.CharField(max_length=100) faculty_names=models.ForeignKey(course_name,on_delete=models.CASCADE) def __str__(self): return self.subject_name class lectures(models.Model): lecture_topic=models.CharField(max_length=100) lecture_number=models.IntegerField(null=False) subjects=models.ForeignKey(subject,on_delete=models.CASCADE) def __str__(self): return self.lecture_topic class lecture_dets(models.Model): lecture_pdfs=models.FileField(upload_to='documents',null=True) lecture_vids=models.FileField(upload_to='videos',null=True) lecture_notes=models.FileField(upload_to='notes',null=True) lecture_name=models.ForeignKey(lectures,on_delete=models.CASCADE) def __str__(self): return f'{self.lecture_name}' also my views.py def Lectures(request,lecture_number): Lectures = lectures.objects.filter(lecture_number=lecture_number) context={"lectures":Lectures} return render(request,'home/lectures.html',context) I want to render the views in my templates and I am not being able to use lecture_number in the template lectures.html. I think there is default id field but don't know how to begin ?? -
Django view prints None on variable passed to it
My URL.py is : path("/clean/<str:sub1>/<int:sub2>/", ..), My url in browser is: .../clean/craft/549/ My view is : def clean(request, sub1, sub2=None): print(sub2) #prints None ... ... clean view prints sub2 as None. However, it should print 549. Why does it print None? -
Djnago - oracle DB - int() argument must be a string, a bytes-like object or a number, not 'list'
I configured Django 2.0.2 with Oracle DB. python 3.8, cx_Oracle 5.3 and oracle instant client 19. I am not able to run python manage.py migarte. While run migrate, we getting Error like int() argument must be a string, a bytes-like object or a number, not 'list' So help me with to configure a Django project with Oracle DB. -
Upper limit for Django group membership?
Is there an upper limit(hard or soft) to how many users can be added to a group in Django? Curious about technical limitations as well as general best practices(eg: don't add more than 10 million users to 1 group or the 4 horsemen of the apocalypse will show up, performance will go down the toilet validating whether a user is a group member, etc..). Or can I just add every user on the site to 1 group and not worry about it even if the site takes off and every person on planet earth with an internet connection decides to join? -
authentication_form not working on the LoginView class in DJango
I actually creating a customize authentication form in LoginView class but it is not working. here is the forms.py: class LoginForm(AuthenticationForm): class Meta: widgets = { 'username': forms.TextInput(attrs = { 'class': 'input100', }), 'password': forms.PasswordInput(attrs = { 'class': 'input100', }) } my class view: class Login(LoginView): authentication_form = LoginForm template_name = 'content/login.html' but in the templates its still loading the default form. -
How to use only() method in django
I am having one issue .... required_fields = needed_fileds()//THis function will return the required fields Example required_fields = ['first_name','last_name','contact_number'] // Required Fields inside a list How do I make a query set with ony() method obj = Profile.objects.only(required_fields) // Currently showing an error -
Django, select_related with slicing
It seems, when you do Foo.objects.select_related('bar')[:10] The caching doesn't help because of the slicing. -
Django User Register, auto login & redirect
I collect two forms at signup - a register form and a user profile form. The form submission works alright - I get to see the new user and their profile on the admin panel. The problem would be automatically logging them in and redirecting them to a specific page doesn't seem to work. This is what my views.py file look like: def registerView(request): regForm = RegisterForm proForm = UserProfileForm if request.method == 'POST': regForm = RegisterForm(request.POST) proForm = UserProfileForm(request.POST) if regForm.is_valid() and proForm.is_valid(): user = regForm.save(commit=True) profile = proForm.save(commit=False) profile.user = user profile.save() username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return render (request, 'main/dashboard.html', {}) else: return HttpResponse("There was a problem signing you up!") regDic = {'regForm': regForm, 'proForm': proForm} return render(request, 'person/register.html', context=regDic) What would be the best way to automatically log in & redirect the registered user upon form submission? -
How do i filter model objects in django by date?
def ajax_total_cash_statistics(request): cash = CashBox.objects.all() dt = request.GET.get('created') if dt: print(type(dt)) dt = datetime.strptime(dt, '%d/%m/%y') cash = cash.filter(created=dt) print(cash) return HttpResponse(to_json(cash), content_type='application/json', status=200) I receive date from json in this format str(17/7/20), and want to filter by this date, how can i do that? Sorry for bad english. -
How to access a django model field in views?
So basically I have a django model which has a Frequency field that I'd like to access inside my views.py file so that I can update it. class Search(models.Model): Search_value = models.CharField(max_length=100, null=True) Search_User = models.CharField(max_length=200, default=None, null=True, blank=True) Frequency = models.IntegerField(null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) What I'm tryin to do is increase the frequency field by 1 instead of creating a new object. if models.Search.objects.filter(Search_value=search, Search_User=user): x = models.Search.objects.filter(Search_value=search, Search_User=user) print(x) else: models.Search.objects.create(Search_value=search, Search_User=user, Frequency=1) This is the logic I use to try to figure it out but the print(x) returns "<QuerySet [<Search: Shirts>]> ". How can I access the Frequency field inside this form so that I can update it. -
Error in Django,docker,PostGIS: Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
I have a Django project with PostGIS database and I need to dockerize this project. This is what I have for now. In settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ.get('pgdatabase'), 'USER': os.environ.get('pguser'), 'PASSWORD': os.environ.get('pgpassword'), 'HOST': os.environ.get('pghostname'), 'PORT': '5432', }} Dockerfile: FROM python:2.7 WORKDIR /orion-amr/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r requirements.txt RUN apt-get update RUN apt-get install -y binutils libproj-dev gdal-bin COPY . /orion-amr/ docker-compose.yml : version: '3' services: db: image: kartoza/postgis:12.0 environment: - POSTGRES_DB=amr_or - POSTGRES_USER=postgres - POSTGRES_PASSWORD=root ports: - "5432:5432" web: build: ./ command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2" ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db .env.dev : SECRET_KEY=z)mf(y#w7-_8y1)0(v*n@w@lzf)!0=g_rj5$%1w6g-t!7nbk05 PGDATABASE=amr_or PGPASSWORD=root PGHOSTNAME=db PGUSER=postgres DEBUG= Now db service works correctly, but web service raises this error: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I tried many solutions (adding "sleep 10" or changing volumes,etc.) but nothing worked for me. Ho could help me, please? -
List Field in Django for responsing through views.py
In my django project, I have a code that returns a list of lists like this: [["2019-01-04", "0:00:00", 0.0], ["2019-01-04", "0:30:00", 0.0]] I want to store this list into my database, but it seems that there is nothing called ListField in django models. I also tried to change the list into String and save it in CharField, but since the list contained quotation mark inside, django would format it into something like this [[\"2019-01-04\", \"0:00:00\", 0.0], [\"2019-01-04\", \"0:30:00\", 0.0]] Could anyone please suggest a way to overcome this. Thanks. -
In django templates, how to dynamically update header section depending on a customized tag parameters in body section
I am building a Django listing app. to use it, a template should looks like this : {% load django_listing %} <html> <head> ... {% include "django_listing/header.html" %} ... </head> <body> ... {% render_listing data some_parameters %} ... {% include "django_listing/footer.html" %} </body> </html> This template is directly used in a TemplateView. It is important to know that the user can define all parameters in the template, the listing is created on-the-fly in the custom render_listing tag thus some_parameters is only known in template side (not known at TemplateView side). The user only gives the data in the TemplateView context. I want to dynamically declare some CSS and JS depending on the some_parameters values. I succeded to do that for JS in {% include "django_listing/footer.html" %}, but not for CSS because when rendering {% include "django_listing/header.html" %} the listing object has not been created yet. Do you have an idea how to dynamically declare some CSS depending on the some_parameters ? May be there is a way to postpone {% include "django_listing/header.html" %} rendering ? -
How to access HTTPS hosted api (using nginx ) in microsoft azure environment using public IP?
Requirement is to access my HTTPs hosted api using public ip provided by microsoft azure windows 10. What i have done so far. i have a djnago based app with all apis (apis when hosted as http i was able to access it using public ip given by microsoft azure, to access it as http i simply run my djnago server as python manage.py runserver publicIP:port number) Now requitrement has changed now i have to host the apis as HTTPS for that i used nginx to create a self signed certificate. STEPS took help form this website http://nginx.org/en/docs/http/configuring_https_servers.html created self signed cert and pem file using ip address (not public ip) now running my djnago app on local host (127.0.0.1:8000) and setting server_name = IP address https is running fine i can access the urls as https but when i try to access the same https api with public ip of the machne it says page not found? please help where i am wrong or what i need to do?