Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handle event.preventDefault inside fetch
I have this piece of code. I'm only using the fetch to validate email field on my database, in my form I have a lot of more fields. I have a problem here. Exactly as this code is written, it wont be submitted if result.exists == undefined and will be submitted if that is not the case (the form will be submitted on the else part). The problem is that I want all of the previous form fields to be sumitted on the this.submit() function. I realized that this.submit() only submits the email, not all the others I have in my form. If I cut the event.preventDefault(), put it only under the if condition, and delete the else statement, If the if condition is not true, the form submits all the previous form fields successfully, not only email. But if I put event.preventDefault() under that if, it's too late for the function to preventDefault in case the if condition is true. So i'm struggling to make the form submit all the form fields in the case of the else part of the code. And also making the form to be prevented from submit under that if condition (in case it's … -
Django Google cloud store: error 400 failed to upload image file
I'm writing a django rest project and recently deployed my project to google cloud. However, I'm having trouble uploading files. Here is the response that I get: 400 POST https://storage.googleapis.com/upload/storage/v1/b/project-id/o?uploadType=multipart&predefinedAcl=publicRead: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>) I have a pretty generic model and viewset as follows: class EndUser(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="users/", blank=True) name = models.CharField('Name', max_length=256) location = models.PointField() device = models.ForeignKey(FCMDevice, on_delete=models.CASCADE) current_task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class EndUserViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = EndUser.objects.all() def get_serializer_class(self): if self.request.method == "GET": return EndUserSerializer return CreateUpdateEndUserSerializer I believe my settings.py are prefect. But I'll add them here for reference: MEDIA_ROOT = "https://storage.googleapis.com/my-project-id/media/" STATIC_ROOT = "https://storage.googleapis.com/my-project-id/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "my-bucked-name" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "credentials.json" ) how do I solve this error? -
Django - Saving generated PDF in a model with xhtml2pdf
I am trying to save a generated PDF using xhtml2pdf app. I want it to save the pdf to the model. The pdf is created perfectly and the browser downloads the file, but instead of download, I would like to save it to the model, which in my models.py I've told it to save to a folder in the media folder. Models.py: class purchase(models.Model): purchase_id = models.AutoField(primary_key=True) transaction_date = models.DateTimeField() method_payment = models.CharField(max_length = 20) cmr_name = models.CharField(max_length = 60) cmr_address = models.CharField(max_length = 90) cmr_postcode = models.CharField(max_length = 10) cmr_tel = models.CharField(max_length = 14) cmr_email = models.CharField(max_length = 40) cmr_pod = models.FileField(upload_to='customers_id') cmr_signature = JSignatureField() receipt = models.FileField(upload_to='receipts', null=True, blank=True) added_by = models.CharField(max_length = 30) item_brand = models.CharField(max_length = 50) product = models.CharField(max_length = 100) model = models.CharField(max_length = 100) serial = models.CharField(max_length = 50) item_brand2 = models.CharField(max_length = 50) product2 = models.CharField(max_length = 100) model2 = models.CharField(max_length = 100) serial2 = models.CharField(max_length = 50) item_brand3 = models.CharField(max_length = 50) product3 = models.CharField(max_length = 100) model3 = models.CharField(max_length = 100) serial3 = models.CharField(max_length = 50) def __str__(self): return '{}'.format(self.cmr_name) Utils.py: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): … -
How to load the latest record on top Django New User
I am trying to load the latest record on top based on the time and date added. I have already assigned the following values in MODELS.PY date_posted = models.DateTimeField(default=timezone.now) I also try to add this in my view function but it didn't work def client_list(request): context = {'client_list':Client.objects.all()} ordering = ['-date_posted'] return render(request, 'client_register/client_list.html', context) -
socket.gaierror: [Errno 10109] getaddrinfo failed
I am getting this error when i try to send an email from django using the gmail smtp. I have already tried to use a different gmail address and also a different smtp server but it gives me the same error. File "c:\users\user\appdata\local\programs\python\python38-32\lib\socket.py", line 918, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 10109] getaddrinfo failed -
objects.all() is not returning all items from DB
I am following an online course about Django and I am encountering a strange problem: When I am referring to my db entry and when I am expecting to get all entries, I only receive the field that I designated to be returned as a string when I defined the class. My files are as follow: models.py from django.db import models class About_me(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) about = models.TextField(max_length=5000) location = models.CharField(max_length=100) email = models.CharField(max_length=100) linked_in = models.CharField(max_length=100) github = models.CharField(max_length=100) def __str__(self): return self.name views.py from django.shortcuts import render from .models import About_me # Create your views here. def cv(requests): cv = About_me.objects.all() return render(requests, 'cv/cv.html', {'cv': cv}) cv.html template <!DOCTYPE html> <head> <meta charset="utf-8"> <title>About me</title> </head> <body> <h1>CV</h1> {% for item in cv %} <p>{{item}}</p> {% endfor %} </body> </html> I am expecting to get a list with all fields: name, position, about, etc... but I am getting only the Name and to be honest I don't understand why. Since I am in a learning project, I would better like to know why is this happening rather than just fix it. Thank you all in advance -
how can i authenticate in django with GET method?
how can i login/authenticate in django using GET method? my login_user function: def user_login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,tag=cd['tag'],password=cd['password']) find = User.objects.filter(tag=cd['tag']) if user is not None: login(request,user) messages.success(request,'You logged successfully.','success') return redirect('roleplay:index') else: messages.error(request,'Your Username Or Password does not correct.','danger') else: form = UserLoginForm() return render(request,'account/login.html',{'form':form}) -
Ask again. i want django datbase update
Contanier.js ... deletePatient = ({ key, test }) => { const { deletePatient } = this.props; deletePatient({ key, test }); console.log(test) }; render() { const { deletePatient } = this; const handleDelete = (rowData) => { deletePatient({ key: rowData.key, test: rowData.delete }); } ... render: (text,rowData) => ( <IconButton color="primary" aria-label="delete" size="small" onClick={() => { handleDelete(rowData) }}> <DeleteForever fontSize="small" style={{ color: "#00ffff" }} /> </IconButton> ... const mapDispatchToProps = dispatch => { return { deletePatient: ({ key, test }) => { dispatch(patientActions.deletePatient({ key, test })); } }; }; Module.js ... export const deletePatient = ({ key, test }) => ({ type: DELETE_PATIENT, payload: { key, test } }); export const deletePatientSuccess = ({ user, token, key, test }) => ({ type: DELETE_PATIENT_SUCCESS, payload: { user, token, key, test } }); ... const deletePatientEpic = (action$, state$) => { return action$.pipe( ofType(DELETE_PATIENT), withLatestFrom(state$), mergeMap(([action, state]) => { // const token = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")).token : null; return ajax .patch(`/api/patient/${action.payload.key}` // , {"Content-Type": "application/json", Authorization: `token ${token}`} // , {'X-CSRFToken': state.CSRFToken.props.value} , { test : action.payload.test } ) .pipe( map(response => { const patient = response.response; return deletePatientSuccess({ patient }); }), catchError(error => of({ type: DELETE_PATIENT_FAILURE, payload: error, error: true }) ) … -
can't convert string to datetime python
how to convert '2020-08-26T12:09:14+0000' to datetime using python from datetime import datetime s = '2020-08-26T12:09:14+0000' f = '%Y-%m-%dT%H:%M:%S.%f%z' date_time_obj = datetime.strptime(s, f) but I got this error: time data '2020-08-26T12:09:14+0000' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' what's the correct format ? -
image is not showing in django
all the data from models is visible except images..tried everthing .. pillow is preinstalled.. static url and root are right.. but cant figure out whats wrong with images.. html.. <div class="col-sm-6"> <div class="profile-image"> <img src="{{About.imsge}}" alt="profile photo"> </div><!-- end profile-image --> </div><!-- end col --> <div class="col-sm-6"> <div class="about-text"> <p> {{ About.first.desc}}</p> models.py from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') -
Django urls. Why aren't urls.py included with new app?
Just curious, especially since Django is all about the DRY principle, why doesn't it include urls.py with creation of new app? Maybe it's just my case(I'm relatively new to Django), but at least 90% of the time, I need to create a urls.py file, which seems quite repetitive to me. There are other actions while doing a web project/app that I've found repetitive, but the URLs seems fundamental to the structure, so don't see what the harm would be for it to be included with the new app creation. Any thoughts, insights? -
How do I force Django 1.11 to create `migrations` folder automatically at custom location?
Disclaimer: the project is legacy, and we have no resource to migrate to Python 3. Originally, we had an application APP with its migrations in APP/migrations folder. The APP/migrations was .gitignored; the server could be launched easily by python manage.py runserver and produced no errors, while the APP/migrations folder remained absent. However, we needed to test our app APP on several different sets of data (indeed, they just represent different stages of a particular process). To do so, we created a symlink APP2 to APP folder (and a couple of similar symlinks like static/APP). However, the migrations in APP/migrations and APP2/migrations ran into a conflict; thus, we had to separate the migrations folders. The following code was added to settings.py: MIGRATION_MODULES = dict([(app, app + '.migrations.' + app) for app in INSTALLED_CUSTOM_APPS]) (INSTALLED_CUSTOM_APPS is concatenated to standard INSTALLED_APPS). Since that, Django refuses to start without the folders APP/migrations/APP and APP2/migrations/APP2: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f3e7edaa230> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File … -
How to inherit django model to make models records independent?
I'm creating ToDo app and I want to archive task when completed. To do so I have created Todo model and TodoArchive, which inherits after Todo: from django.db import models from django.utils import timezone class Todo(models.Model): date_added = models.DateTimeField(default=timezone.now) task = models.CharField(max_length=100) story = models.CharField(max_length=100, default="-") project = models.CharField(max_length=100) complete = models.BooleanField(default=False) def __str__(self): return self.task class TodoArchive(Todo): date_archived = models.DateTimeField(default=timezone.now) def __str__(self): return f'ARCH {self.task} - {self.date_added}' After that I loop through each task in view and create new archive object: def archive_completed(request): for todo in Todo.objects.all(): if todo.complete: archive_todo = TodoArchive(task=todo.task, story=todo.story, project=todo.project, complete=todo.complete, date_added=todo.date_added) archive_todo.save() todo.delete() return redirect('home') But after that elements moved to Archive model belongs to both models as shown on the picture below: https://i.stack.imgur.com/AVxHy.png The effect is that when I delete element from one model it removes it from the other immediately. Does anyone knows why and how to eliminate this behaviour? -
Combine multiple foreign key in a single field in Django serializer
My model.py camera_choices = ( ('0', 'Entry'), ('1', 'Exit'), ) class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True) DeviceCode = models.CharField(max_length=25, null=False, blank=False) IpAddress = models.CharField(max_length=15, null=True, default=None, blank=True) Description = models.CharField(max_length=250, null=True, default=None, blank=True) DefaultAccess = models.BooleanField(default=True, null=True, blank=True) EntryCamera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='EntryCameraId', related_name="entry_camera", null=True, blank=True, default=None) ExitCamera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='ExitCameraId', related_name="exit_camera", null=True, blank=True, default=None) DeviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') DeviceStatus = models.SmallIntegerField(default=1, null=True, blank=True) class Meta: db_table = "Device" class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50, unique=True) CameraUrl = models.URLField() CameraType = models.CharField(max_length=30, choices=camera_choices) class Meta: db_table = "Camera" my serialiser.py class DeviceListSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ['DeviceId', 'DeviceCode', 'DeviceName', 'IpAddress', 'Description', 'DefaultAccess', 'DeviceStatus', 'DeviceType', 'EntryCamera', 'ExitCamera'] depth = 1 my views.py def device_list(request): try: device = Device.objects.all() serializer = DeviceListSerializer(device, many=True, read_only=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) i got the response [ { "DeviceId": 3, "DeviceCode": "DevTest3", "DeviceName": "", "IpAddress": "", "Description": "", "DefaultAccess": false, "DeviceStatus": 1, "DeviceType": { "DeviceTypeId": 1, "DeviceType": "Devicetype1", "DeviceTypeStatus": true }, "EntryCamera": { "CameraId": 1, "CameraName": "Camera1", "CameraUrl": "http://www.dgdge", "CameraType": "0" }, "ExitCamera": { "CameraId": 2, "CameraName": "Camera2", "CameraUrl": "http://www.hth", "CameraType": "1" } } ] is it possible … -
Django Google Cloud Storage file upload failed with 400 error
I have written my django rest framework which I want to deploy to GCP. I decided to use Google Cloud Storages for files. I'm using this: https://github.com/jschneier/django-storages/blob/master/docs/backends/gcloud.rst I have an API endpoint, from where a user can upload his/her image. This is how the model looks like: class EndUser(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="users/", blank=True) name = models.CharField('Name', max_length=256) location = models.PointField() device = models.ForeignKey(FCMDevice, on_delete=models.CASCADE) current_task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name Here's how the view is set up: class EndUserViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = EndUser.objects.all() def get_serializer_class(self): if self.request.method == "GET": return EndUserSerializer return CreateUpdateEndUserSerializer Now, this works fine locally but if I change my settings and try to upload to google cloud storage it gives a 400 error: google.api_core.exceptions.BadRequest: 400 POST https://storage.googleapis.com/upload/storage/v1/b/my-project-id/media/o?uploadType=multipart&predefinedAcl=publicRead: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>) Here's the relevant part of my settings.py: GS_DEFAULT_ACL = "publicRead" MEDIA_ROOT = "https://storage.googleapis.com/project-id/media" STATIC_ROOT = "https://storage.googleapis.com/project-id/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "my-media-bucket" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "credentials.json" ) -
Disable Django Form Field only in UpdateView
I have a UserForm in forms.py which is common between Register and Edit Profile features, its Views are also common, as 90% of the functionalities are similar in both the views. I want to disable the EMailField from UserForm only in Edit Profile page but should be editable in Register page. Here is my code: forms.py class UserForm(forms.ModelForm): password = None email = forms.EmailField(required=False, disabled=True) salutation = forms.ChoiceField(choices=Choices.SALUTATIONS) blood_group = forms.ChoiceField(choices=Choices.BLOOD_GROUPS) class Meta: model = User fields = ('salutation', 'blood_group', 'email', 'first_name', 'middle_name', 'last_name', 'gender', 'birth_date', 'profile') Same Form is being rendered both the times in register and edit views. Here are my urls.py. path('register/', StudentView.as_view(), name='addview'), path('<int:pk>/edit/', StudentView.as_view(), name='editview'), in the views.py (For detailed views.py, check the accepted answer) userform = UserForm(request.POST or None, instance=self.object) admission.html <form class="form" name="admissionForm" id="admissionForm" method="post" enctype="multipart/form-data" action="{% url 'addview' %}"> {% csrf_token %} <div class="pages"> <h4 class="mt-2 mb-3">Personal Information</h4> {% include "student_errors.html" %} {{userform|crispy}} .... <div class="btn_container"> <button type="submit" class="btn btn-info float-right btn-next">Submit</button> </div> </div> -
How can I display my data in a table using django [closed]
I need to store the data from this API in a database. I managed that, but now I need to render this data in the following way: How can I display this data as a table, in the format as shown in the image? -
Allow ordering in list_display a property field
I am trying to setup ordering in django admin list_display, but I cannot make it to work. I have tried with using queryset annotations, but I have not found how to annotate it with a model property. The code: models.py class Person(models.Model): name = models.CharField(max_length=150, verbose_name='Nome Próprio') dob = models.DateField(verbose_name="Date of birth") @property def age(self): born = self.dob today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ['name', 'dob', 'age'] def get_queryset(self, request): qs = super(PersonAdmin, self).get_queryset(request) qs = qs.annotate(age='age') return qs This is my attempt so far, is there any easy fix? I am quite a novice on Django. Thank you -
Make static files from django's collecstatic part of Docker image
I want to include static files generated from python manage.py collectstatic in the Docker image. For this, I included the following line in my Dockerfile CMD python manage.py collectstatic --no-input But since it runs the command in an intermediate container, the generated static files aren't present STATIC_ROOT directory. The following lines I can see on the logs of build. Step 13/14 : CMD python manage.py collectstatic --no-input ---> Running in 8ea5efada461 Removing intermediate container 8ea5efada461 ---> 67aef71cc7b6 I'd like to include the generated static files in the image. What shall I do to achieve this? -
Django custom SimpleListFilter
I have this two models: class Intervencao(models.Model): ....... class Alvaras(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='IntervencaoObjects2',on_delete=models.CASCADE) data_alv = models.DateField(blank=True,null=True,verbose_name="Data do alvaras") I want to add a custom filter in my Intervencao.Admin, that do a query to the last record i have in Alvaras and check if the field data_alv it is empty or not. I already got it working, but i want only the last record. class Dataalv(admin.SimpleListFilter): title = ('data de alvaras') parameter_name = 'data_alv' def lookups(self, request, model_admin): return ( ('yes', 'yes'), ('no', 'no') ) def queryset(self, request, queryset): value = self.value() if value == 'yes': return queryset.filter(IntervencaoObjects2__data_alv__isnull=False) elif value == "no": return queryset.filter(IntervencaoObjects2__data_alv__isnull=True) class IntervencaoAdmin(admin.ModelAdmin): list_filter = Dataalv, -
Find reverse ForeignKey instances of Queryset?
The django documentation is pretty clear on how to look up fields on single instances but what about reverse relationship QuerySet objects. Example: class Author(models.Model) name = models.Charfield(...) class Book(models.Model) author = models.ForeignKey(Author, ...) I now create a queryset object: special_authors = Author.objects.filter(name__icontains="lui") Now, I want to find all books that belong to special authors. I want to do something like this: special_authros.book_set.all() Without doing this: books = [] for author in special_authors: books += author.book_set.all() Is there a way to do this easily? -
Well I am having issue with publish button in my django site .It is not performing its' function
I am using django 3.0.3,python 3.8.5 and Vs code as an IDE. I am clicking on the publish button but it is not working. ---Models.py--- def publish(self): self.published_data = timezone.now() self.save() ---views.py--- @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish() return redirect('post_detail',pk=pk) ---urls.py--- path('post/<int:pk>/publish/',views.post_publish,name ='post_publish'), --post_detail.html(template)-- <a class="btn btn-primary" href="{% url 'post_publish' pk=post.pk %}">Publish</a> Any help will be appreciated Thank you -
Django static files cannot find the path specified double backslash in path
I'm getting the following error when running collectstatic in Django: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\rutha_000\\Documents\\DjangoProjects\\jarvis\\static' with two backslashes rather than one in the path My stylesheet is located in C:\Users\rutha_000\Documents\DjangoProjects\jarvis\static\jarvis\css\ And my settings file looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Not sure why there is a double backslash or what's going wrong here? Thanks -
how to show and load another django website with access cookies in HTML
how can i load another website with accessing cookies for this features: Login / Register(POST Method) CRUD operations NOTE : my iframe run at local index.html: <iframe src="https://example.com" frameborder="0" width="800" height="800" sandbox="allow-same-origin allow-scripts"></iframe> NOTE : example.com written in django what should i do to django website(example.com) show and load in HTML with accessing cookies? my settings.py: X_FRAME_OPTIONS = 'ALLOW-FROM ALL' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' -
CSS isn't loading to style HTML-connected to static in Django
So basically I can't manage to connect .css file to my .html Previously it just wasn't finding the .css file but after I've referenced the full path it stopped giving me the 'not found' error on cmd local host so it does find it it just doesn't load it to change styling <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href=C:\Users\Any1\Desktop\personal_portfolio- project\blog\templates\blog\master.css"> </head> <body> <h1>Example heading</h1> <p>Lori is home blog</p> </body> </html> #my just trying to change h1 color to red for testing h1 { color: #FF0000; } #and my settings.py STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/'