Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Final/Landing Page
I am working on a Django based server and i take some attachments from the user and process it in this function def get_request(request): df = pd.DataFrame() flag = 0 # if this is a POST request we need to process the form data if request.method == 'POST': #Processing and generating results return render(request, 'result.html', {'data': to_send, 'file': df, 'flag': flag}) Initially, I wanted to render the results HTML page as above but instead I decided to send an email containing the results and send it to the user. I am able to send the results but I want to render a final page with some text while the results generate(might take some time depending on the size of the input). How can I do so without waiting for the processing to end and let it be in the background even if the user closes the tab? -
Django queryset filter with Q object or relationship is not working as expected
I have a model A with two fields: class A(models.Model): text = models.TextField() b = models.ForeignKey( B, null=True, blank=True, on_delete=models.SET_NULL ) And a model B: class B(models.Model): text = models.TextField() I have a record A with text field "12345" and a b field as null. When trying to filter model A with: queryset = queryset.filter( models.Q(text__icontains="123") | models.Q(b__text__icontains="123") ) But the record is filtered out. Did I miss anything? -
Django, CSVs, FileField and S3 - How to stream a CSV file into an S3 Bucket and also save it into a Django Model's FileField?
everyone. Hope you're doing well. I would like to start this question by prefacing that I'm a real newbie when it comes to AWS. Right now I'm working on a Django app with a friend that already has some more experience with web development and he had already set up everything in AWS that is, we have most of our files uploaded there, a staging app running and some other configs. I'm working on a backend implementation of transforming some database data from our web app into CSV files and uploading it into the cloud. Basically, we have an endpoint where a User can ask for data from another URL of the site, and our app will transform the data into a .CSV file, export it to S3 and AT THE SAME TIME saving it on a FileField of the model. Then, once the File is uploaded, the user will receive it in its e-mail. Since the file could be really big, the BIG question is: How do you stream .CSV file into a S3 Bucket and have Django save it into the FileField attribute of a model? Here's my code for reference (This is the only way it created … -
Django drops ListView and uses DetailView for a list object, then gives NoReverseMatch
PyCharm 2020.2 Python 3.9 Django 3.1 Ubuntu 20.04 LTS project urls.py: urlpatterns = [ path('', views.home, name='home'), path('admin/doc/', include('django.contrib.admindocs.urls')), path('admin/', admin.site.urls), path('ktab/', include('ktab.urls')), app.models.py: def get_absolute_url(self): return django.urls.reverse('EntryDetail_url', kwargs={"slug": self.slug}) app.urls.py: path('entry/index/', views.EntryIndex.as_view(), name='EntryIndex_url'), path('entry/list/', views.EntryList.as_view(), name='EntryList_url'), path('entry/<slug>:<title>/', views.EntryDetail.as_view(), name='EntryDetail_url'), app.views.py: class EntryIndex(ListView): model = Entry template_name = 'EntryList_.html' def get_context_object_name(self, object_list): return 'object' def get_queryset(self): return Entry.objects.all() def get_context_data(self, **kwargs): context = super(EntryIndex, self).get_context_data(**kwargs) context['searchbox'] = SearchBox() return context class EntryDetail(DetailView): model = Entry template_name = 'EntryDetail_.html' def get_context_data(self, **kwargs): context = super(EntryDetail, self).get_context_data(**kwargs) context['searchbox'] = SearchBox() return context class EntryList(ListView): model = Entry template_name = 'EntryList_.html' Error Message: NoReverseMatch at /ktab/entry/list/ Reverse for 'EntryDetail_url' with keyword arguments '{'slug': 'executive-summary-hattie-urls-and-views'}' not found. 1 pattern(s) tried: ['ktab/entry/(?P<slug>[^/]+):(?P<title>[^/]+)/$'] ...... In template /home/malikarumi/Projects/lifeandtimes/chronicle/templates/base_index.html, error at line 0 But of course, there’s nothing there at line zero but the DOCTYPE declaration. I am trying to call the index for this model’s objects, which is the same as a list. For reasons that I do not understand, and am tired of fighting with, it keeps trying to give me a single object on the detail template. The object 'executive-summary-hattie-urls-and-views' happens to be queryset[0]. You can see that I put entry/index and entry/list ahead of … -
Django - ModuleNotFoundError: No module named 'djangoformsetjs'
I have a new Django app, with the following module in my settings.py: INSTALLED_APPS = [ 'djangoformsetjs', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'rest_framework', 'djoser', 'app', # Enable the inner app 'phonenumber_field', ] When trying to make a first upload to Heroku, it returns the error : ModuleNotFoundError: No module named 'djangoformsetjs' Although it works fine locally. I tried re-installing from the terminal : pip install django-formset-js And everything seems fine : Requirement already satisfied: django-formset-js in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (0.5.0) Requirement already satisfied: django-jquery-js in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from django-formset-js) (3.1.1) Requirement already satisfied: Django in /Users/homepc/.local/lib/python3.8/site-packages (from django-formset-js) (2.2) Requirement already satisfied: sqlparse in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from Django->django-formset-js) (0.4.1) Requirement already satisfied: pytz in /Users/homepc/opt/anaconda3/lib/python3.8/site-packages (from Django->django-formset-js) (2020.1) Am i missing something in my setup please ? -
Django:: Cant update form
I have gone blind trying to figure this out... I have done everything correctly but for some reason I am unable to update a form. views.py def Mainpage(request): model = datas.objects.filter(qs_login='nicobari') context = {'items': model } return render(request,"main/auditform.html",context) def updateform(request, pk): model = datas.objects.filter(qs_login='nicobari') data= datas.objects.get(Task_ID=pk) form = auditForm(instance=data) if request.method == 'POST': form = auditForm(request.POST, instance=data) if form.is_valid(): form.save() context = { "items": model, "data": data } return render(request,"main/auditform.html", context) Everything works but when i try to click on : <input class="submit" type="submit" value="Submit"> It just refreshes the page but doesnt update the content. Could anyone help me understand what I could have done wrong? -
Delaying function in Django
I have the following button: <a href="/donations/{{donation.pk}}/delete/" onclick="showAlert" >Accept</a> The delete function: def deleteDonation(request, id=None): donation = get_object_or_404(Donation, pk=id) donation.delete() return redirect('/dashboard/') I also have a javascript function called onClick, which is triggered when my button is clicked. What I want: I want my program to call my javascript function, and wait a few seconds before the python function is called. How can I do this, I used time.sleep(5), but this only delayed the python function and did not call my javascript one. -
Customize register in django rest knox
How to make the user register with other fields like birth date besides the name and email, and how to do password confirmation? -
Error while loading website on Nginx & django
I had a server which is running django & Nginx. I had tried to install SSL certificate, but it seems that the certificate had been installed on apache. So, I had stopped Apache, and reboot the server, but I can't load the page. When I do netstat on nginx sites-enabled, then I see: tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 25609/nginx tcp6 0 0 :::80 :::* LISTEN 25609/nginx The result is for ports listening 9000 (which is django): tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 28178/python But the website is not running . How can I fix this? Thank you -
Where to serve files in deployment and production with django
I am in the process of building a website with Django. The web app is for a local store in my city. The store sells gardening courses and workshops (the store is my mom's btw). I want the admin of the page (the owner of the store) To be able to add new courses whenever she wants. So I made this model for the courses: class Curso(models.Model): title = models.TextField() photo = models.ImageField(upload_to='cursos/') description = models.TextField() price = models.IntegerField(null=False) content = models.JSONField(blank=True) clases = models.IntegerField(default=1) duration = models.IntegerField() isworkshop = models.BooleanField(default=False) I included an ImageField because in the fronted there should be an image related to the course. I added the path /cursos/ but I actually have no idea where the image is going. I saw people had a "media" folder. But I also read the "media" folder was only for images uploaded by the user? This is my static folder looks like: static |_app |_js |_css |_sass |_icons |_images |_homeslider |_plants |_pictures Should the images uploaded from the admins app in that same folder? Anyways I don't know where to store the images. And I don't have a hosting yet which leads me to my next question: What should … -
source.transform gives an error latitude or longitude exceeded limits
I get the following error when running this statement: Any suggestions on what might be going wrong This is the object details source : SRID=4326; POINT(-122.20874 47.68419) This is the statement: res = source.transform(32148, clone=True) The error is: GDAL_ERROR 1: b'latitude or longitude exceeded limits' Any suggestions on how I can fix this ? -
Extending ManyToManyField In Templates
I need to create a manytomany field that has some options and then next to each option there is an extra field My models: class Subject(models.Model): name = models.CharField(max_length=30) duration = models.IntegerField() price = models.IntegerField() class Student(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) subject = models.ManyToManyField(Subject,through="StudentSubject") class StudentSubject(models.Model) student = models.ForeignKey(Student,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) discount = models.IntegerField() I used the intermediate model StudentSubject(this contains the extra field) but I'm not sure how I should render this in a template I want to do something like this: Math DiscountField1 Physics DiscountField2 CompSci DiscountField3 -
How to return a custom validation error message ins django-enumchoicefield?
I am using django-enumchoicefield and I want to return a custom Validation Error instead of default Key Error if api receives incorrect value for model. class SexChoices(ChoiceEnum): male = "male" female = "female" class CandidateModel(models.Model): id = models.CharField(primary_key=True, max_length=20) name = models.CharField(max_length=50) sex = EnumChoiceField(enum_class=SexChoices) I have tried validators=[some_validator] in EnumChoiceField() but its not working. Also, if I define a custom model manager class for CandidateModel it still giving KeyError instead of Validation Error -
Twillio SMS not getting sent from Django python project
Twilio SMS not getting sent from Django python project I attempted to replicate the steps in blow article and send SMS using Twilio API https://www.twilio.com/blog/broadcast-sms-text-messages-python-3-django I keep geting HTTP/1.1" 401 16 printed to the console see my view method below from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from django.conf import settings from django.http import HttpResponse from twilio.rest import Client @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def SendPhoneCodeView(request): print('phone is') phone = request.data.get('phone') print(phone) message_to_broadcast = ("This is Me Testing the incredible Twilio SMS " "Not received yet? Wait for A Moment") client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) client.messages.create(to=phone, from_=settings.TWILIO_NUMBER, body=message_to_broadcast) return HttpResponse("messages sent!", 200) Also, all the print statements are NOT getting printed to console Can someone please advise me on what exactly I am doing wrong and how to resolve this Thanks -
how to depend on two fields to make a dropdown depend list django ajax
i'm trying to make an app for insert locations for a specific purpose , these my models : class City(models.Model): city = models.CharField(max_length=40) class Area(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.CharField(max_length=40) class Street(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.ForeignKey(Area,on_delete=models.PROTECT) street = models.CharField(max_length=40) def __str__(self): return self.street class Nearest(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.ForeignKey(Area,on_delete=models.PROTECT) street = models.ForeignKey(Street,on_delete=models.PROTECT) nearest_place = models.CharField(max_length=40) my views.py def load_city_area_street(request): city_id = request.GET.get('city') city = City.objects.get(id=city_id) area = Area.objects.filter(city=city_id).all() area_id = request.GET.get('area') area_name = Area.objects.get(id=area_id) street = Street.objects.filter(area=area_name) return render(request,'locations/dropdown.html',{'city':city,'area':area,'street':street}) my template $('#id_city').change(function(){ const url = $('#post-form').attr("data-city-area-street-url"); const cityId = $(this).val(); $.ajax({ url : url, data:{ 'city':cityId }, success:function(data){ $('#id_area').html(data); } }) }) <form id="post-form" method="POST" data-city-area-street-url="{% url 'locations:load_city_area_street' %}"> {% csrf_token %} <div class="card-body"> <div class="row"> {{form.as_p}} </div> </div> <button type="submit" class="btn btn-success">save</button> </form> but it works only for the area field , i need to make a change for several fields for example $('#id_city #id_area #id_street').change(function() but it doesnt work ! isnt there a better way to achieve that please? thank you -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'User.User' that has not been installed
I wanna use my custom user in my Django project and I wanna use the OTP system for login in my project so I delete the username and password field of the user and the user should login with a phone number but I get an error. these are my codes: class UserManager(BaseUserManager): def create_user(self, phone_number): user = self.model( phone_number = phone_number ) if not phone_number: raise ValueError('Phone number is required') user.save(using = self._db) user.is_superuser = False user.is_admin = False user.name = "green user" return user def create_superuser(self, phone_number): user = self.create_user( phone_number = phone_number ) user.is_superuser = True class User(AbstractUser): username = None password = None email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.IntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['phone_number',] objects = UserManager() def __str__(self): return self.phone_number class MyUserAdmin(UserAdmin): model = User list_display = ('phone_number', 'email') list_filter = ('phone_number', 'email') search_fields = ('phone_number') ordering = ('phone_number') filter_horizontal = () fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('phone_number',)}), ) in my stting i … -
Django how to automatically save user in froms?
When I am passing "user" fields to my Model froms. I am getting all user details as dropdown. see the picture: I am trying to save current user instance without showing this dropdown because I want user will be automatically save without selecting or showing this dropdown. here is my froms.py: class ProfileFroms(forms.ModelForm): class Meta: model = UserProfile fields = ["user","profile_pic","mobile","country","website_link"] when I remove "user" froms fields then getting this error: "NOT NULL constraint failed: members_userprofile.user_id" I aslo tried this code for saving current user but getting same error. views.py if forms.is_valid(): forms.user = request.user here is my full code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) mobile = models.IntegerField(blank=True,null=True) country = models.CharField(max_length=200,blank=True,null=True) website_link = models.CharField(max_length=3000,blank=True,null=True) views.py def UserProfileView(request): userinfo = UserManagement.objects.filter(username=request.user) forms = ProfileFroms(request.POST,request.FILES or None) if request.method == "POST": if forms.is_valid(): #forms.user = request.user #tried this line for save current user but didn't work forms.save() messages.add_message(request, messages.INFO,'Profile not updated sucessfully') return redirect("members:user-profile-private") else: messages.add_message(request, messages.INFO,'Somethings wrong. Profile not updated') print("invalid") context={"userinfo":userinfo,"forms":forms} return render(request,"members/privateprofile.html",context) -
how to patch only the foreign key of a nested serializer in django rest framework?
I have a nested serializer which binds some fields that are foreign keys to the related objects, when i make a get request I get the data as I want it, but when I make a patch request I would like to be able to only provide the foreign key id instead of the whole object representation. -
Docker Django Error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
I've been trying to dockerise my django project with postgresql but have been running into this same problem time and time again. web_1 | CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I've my environment variables in a .env set to: .env: DEBUG = True ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0:8000 and use the python-decouple module to configure them in settings.py from decouple import config DEBUG = config('DEBUG', default=False) ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(sep=' ') Running the project: python manage.py runserver works perfectly fine with no errors. However, when it comes to running: docker-compose up I get the following output Starting postgres_db ... done Starting project_web_1 ... done Attaching to postgres_db, project_web_1 postgres_db | postgres_db | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_db | postgres_db | 2021-07-30 17:58:52.695 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit postgres_db | 2021-07-30 17:58:52.696 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_db | 2021-07-30 17:58:52.696 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_db | 2021-07-30 17:58:52.747 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_db | 2021-07-30 17:58:52.887 UTC [27] LOG: database system was shut down at 2021-07-30 17:58:34 … -
Django webserver automatic failover design
I am trying to build a Django backend system combined with Celery. The idea is that there is a list of 500+ websites that will be processed by Celery every 5 min. Since it involves a lot of network operations which can take any amount of time and we have time constraint of 5 min, we are planning to have multiple Django webservers running in parallel with each processing some amount of websites. The idea is that each Django web server will process (500+ list of websites) / (total number of Django websites instances running), this way we can distribute the workload and in case if anyone goes down then others can take over. I have created a heartbeat rest API which other Django webservers will use to check the status of other servers but how can I make it scalable? What I want is each web server will auto-detect how many others are running and then will process the list accordingly, for example, if there are 5 web servers running then each of them will process only 100 websites, the first server will process first 1-100, then the second one will process next 101-200, the third one will process … -
how to add values from view to url in django
I have to give values from view to url like the name is the value from view : how can i achieve that -
Django [WinError 10053] when loading up server
Whenever I start up my Django server i get the errors shown below. The weird thing is that sometimes the [WinError 10053] doesn't show up and I can develop normally but when it does show up the project seems to malfunction and .css and .js files also don't get loaded. I have already looked into other stackoverflow questions that seemed related such as setting the correct code page to use with postgres or the python bug mentioned here https://bugs.python.org/issue27682. But I'm using python 3.9 so that bug should be fixed. Does anyone know how to fix this? The project works just fine on the computers of some other people and everything that we compared seemed the same (settings, pycharm configuration,...). Exception occurred during processing of request from ('127.0.0.1', 59986) ---------------------------------------- Exception occurred during processing of request from ('127.0.0.1', 55047) Traceback (most recent call last): File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) Traceback (most recent call last): File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__ self.handle() File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() … -
How to create Model with nested object in Django
I'm trying to create a small product manufacturing app with Django. There are two main models in the app. class Product(models.Model): name = models.CharField(max_length=100, blank=True, default='') class ProductionOrder(models.Model): created = models.DateTimeField(auto_now_add=True) entries = # not sure what goes here I would like ProductionOrder.entries to be a list of dictionaries which include the Product and a quantity value. The created ProductionOrder would appear as so (not exactly sure : productionOrder = { 'id': 2, 'entries': [ { 'product': 'product_1_ref', 'quantity': 10}, { 'product': 'product_2_ref', 'quantity': 10} ] } How can I accomplish this in a correct way? -
Database connection strings and running database dependency for testing stage in multi-stage Dockerfile
I'm building out a multi-stage Dockerfile and it is my first time doing so and have a couple questions related to it. Currently I'm working on the Django API with the following Dockerfile: # python-base stage FROM python:3.8-slim as python-base ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=on \ PIP_DEFAULT_TIMEOUT=100 \ POETRY_HOME="/opt/poetry" \ POETRY_VIRTUALENVS_IN_PROJECT=true \ POETRY_NO_INTERACTION=1 \ PYSETUP_PATH="/opt/pysetup" \ VENV_PATH="/opt/pysetup/.venv" ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH" # builder-base stage FROM python-base as builder-base RUN apt-get update \ && apt-get install --no-install-recommends -y \ curl \ build-essential ENV POETRY_VERSION=1.1.7 RUN curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python WORKDIR $PYSETUP_PATH COPY ./poetry.lock ./pyproject.toml ./ RUN poetry install --no-dev # Development stage FROM python-base as development COPY --from=builder-base $POETRY_HOME $POETRY_HOME COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh WORKDIR $PYSETUP_PATH RUN poetry install WORKDIR /app COPY . . EXPOSE 5000 ENTRYPOINT /docker-entrypoint.sh $0 $@ CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"] # test stage FROM development AS test RUN coverage run --omit='manage.py,config/*,.venv*,*/*__init__.py,*/tests.py,*/admin.py' manage.py test I'm running into with two issues with the test stage: Django starts up and performs its system checks and sees the os.environ[] are empty because the env vars don't exist in the Docker image. And they don't exist there because, from what I understand, … -
Formatting datetime field with Django Rest Framework serializers
I need to add "am/pm" next to a formatted datetime field and it is not showing up. Here is what I have in my serializer. class MySerializer(serializers.ModelSerializer): join_date = serializers.DateTimeField(format="%b %d %I:%M %p") Which just outputs Mar 2 8:30 However, with the same field usiing datetime.strftime(join_date, "%b %d %I:%M %p") I get Mar 2 8:30 am Is there a different variable I need for DRF serializer to format the am/pm?