Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't get the GET response value - AttributeError: module 'django.http.request' has no attribute 'GET'
I'm trying to build a simple app that collects data on shoes and then displays it as a list. I want to use pagination, which is pretty simple using Django's paginator. My problem is that I cannot get Django to give me the value sent in a GET request. According to Django docs what I have been doing should work. I've tried it with request and HttpRequest and every time I get a a "no attribute" error. The following is the code I have in my views.py file. from django.views.generic import ListView from django.http import HttpRequest, request from .models import Shoes class ShoeListView(ListView): model = Shoes template_name = 'shoes/shoes-list.html' context_object_name = 'shoes' if request.method == "GET": shoespp = request.GET['shoespp'] else: shoespp = 2 paginate_by = shoespp And this is my template. <body> <h1>Shoes</h1> <h2>List of Shoes</h2> <form method="get"> <select name="shoespp"> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <input type="submit" value="List Shoes"> </form> <ul> {%for pair in shoes %} <li> <strong>{{ pair }} <em>{{ pair.brand }}</em></strong> <em>{{ pair.colorway }}</em> - {{ pair.size }} </li> {% endfor %} </ul> <p> {% if page_obj.has_previous %} <a href="?page=1"><button>&laquo; first</button></a> <a href="?page={{ page_obj.previous_page_number }}"><button>previous</button></a> {% endif %} <span> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages … -
django findstatic does not search the intended folder
When I run find static, I get venv) root@owner:/home/owner/blog/blog# python manage.py findstatic --verbosity 2 bootstrap.css No matching file found for 'bootstrap.css'. Looking in the following locations: /home/owner/blog/venv/lib/python3.8/site-packages/django/contrib/admin/static I want django to search /home/owner/blog/blog/static/css/bootstrap.css Why django does not find it? My /home/owner/blog/blog/blog/settings.py is """ Django settings for blog project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'bapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Push notifications from Django backend to iOS/Swift frontend
I'm in a hairy situation and not sure how to proceed. We needed to implement django push notifications for this project. I did research into the best library to use. django-push-notifications (https://github.com/jazzband/django-push-notifications) looked like the most up-to-date library to use. The APNS portion is built on apns2 (https://github.com/Pr0Ger/PyAPNs2) I did have to make a few modifications for BE testing. I essentially set up the project to do everything correctly on my end and then "pretend" to send a push notification to apple. At this stage the handshake didn't occur between django and apple. During testing a self-signed certificate is used just to make apns2 happy. Because heroku doesn't allow file uploads I had to do something a bit tricky to load the certificate into a file in django (basically reading from an environment variable and writing it to a file). Only recently did it hit me that the FE dev handed me just a private key, not a certificate. django_push_notifications requires a certificate. He further told me Apple discontinued certs in 2019 and only uses private keys. django_push_notifications didn't have any issues on the matter. [however, I did notice this page in the documentation: https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst] Generation of an APNS PEM … -
Use Django models.FileField to read file from memory and discard it before it is written to the directory
How can I read a file using Django's models.FileField, handle the data in memory, and then discard it before django tries to save/write it to my directory. I want to discard the file, but still save the other fields for the model. I now that I can use forms and views to handle files, but I want to do it through the admin interface without a lot of extra logic class DataField(models.Model): file = models.FileField() title = models.CharField() def save(self, *args, **kwargs): super(DataField, self).save(*args, **kwargs) some_background_task(self.file) # skip saving the file and avoid writing to directory, but save other fields -
pandas: Invalid comparison between dtype=datetime64[ns] and date
InvalidComparison Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\core\arrays\datetimelike.py in wrapper(self, other) 115 try: --> 116 other = _validate_comparison_value(self, other) 117 except InvalidComparison: ~\anaconda3\lib\site-packages\pandas\core\arrays\datetimelike.py in _validate_comparison_value(self, other) 95 elif not is_list_like(other): ---> 96 raise InvalidComparison(other) 97 InvalidComparison: 2021-03-01 During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-56-717029e30194> in <module> 30 #create 3m and 6m dataframes 31 ---> 32 tx_3m = tx_data[(tx_data.InvoiceDate < date(2021,3,1)) & (tx_data.InvoiceDate >= date(2021,1,1))].reset_index(drop=True) 33 tx_6m = tx_data[(tx_data.InvoiceDate >= date(2021,3,1)) & (tx_data.InvoiceDate < date(2021,9,1))].reset_index(drop=True) 34 ~\anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other) 63 other = item_from_zerodim(other) 64 ---> 65 return method(self, other) 66 67 return new_method ~\anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(self, other) 368 rvalues = extract_array(other, extract_numpy=True) 369 --> 370 res_values = comparison_op(lvalues, rvalues, op) 371 372 return self._construct_result(res_values, name=res_name) ~\anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in comparison_op(left, right, op) 228 if should_extension_dispatch(lvalues, rvalues): 229 # Call the method on lvalues --> 230 res_values = op(lvalues, rvalues) 231 232 elif is_scalar(rvalues) and isna(rvalues): ~\anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other) 63 other = item_from_zerodim(other) 64 ---> 65 return method(self, other) 66 67 return new_method ~\anaconda3\lib\site-packages\pandas\core\arrays\datetimelike.py in wrapper(self, other) 116 other = _validate_comparison_value(self, other) 117 except InvalidComparison: --> 118 return invalid_comparison(self, other, op) 119 120 dtype = getattr(other, "dtype", None) ~\anaconda3\lib\site-packages\pandas\core\ops\invalid.py in invalid_comparison(left, right, op) 32 … -
Несколько видов пользователей в django [closed]
Я пишу rest api на django и мне нужно создать несколько видов пользователей(покупателя и администратора). Не могли бы подсказать как это сделать? Их создание вынести в разные view и routs как их вообще разграничить? Пожалуйста можно поконкретнее или оставить ссылки на источники где об этом написано. Заранее спасибо за ответы) -
Django Rest Framwork PUT request to user model endpoint
I'm trying to update my user model by adding a profile picture. I'm stuck on the fact that DRF requires a lookup for PUT requests. But the client doesn't know the user pk they just have a login token. The user would normally be obtained in a view using request.user views.py: class UploadViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = serializers.ImageUploadSerializer parser_classes = [MultiPartParser] models.py class User(AbstractUser): profile_image = models.ImageField(upload_to='testuploads/', null=True) serializers.py class ImageUploadSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'profile_image', ) Posting give the following "detail": "Method \"PUT\" not allowed.", Which is caused by the fact that there is no individual resource identifier in the URL. Of course, the resource (a user) could be obtained from the request because it is an authenticated request. How can I update the user model using DRF? -
Django "Method \"POST\" not allowed."
When I test my endpoints using Postman I get the message "Method "POST" not allowed" when I try to create a new truck using my createTruck function. I am able to delete, update, and get trucks from my database. Also I am able to create a new truck in Django Admin. views.py @api_view(['POST']) def createTruck(request): data = request.data user = request.user truck = Truck.objects.create( user=user, image=data['image'], make=data['make'], prototype=data['prototyp'], year=data['year'], serviceInterval=data['serviceInterval'], nextService=data['nextService'], seats=data['seats'], bedLength=data['bedLength'], color=data['color'], vin=data['vin'], currentMileage=data['currentMileage'] ) print("request", request) serializer = TruckSerializer(truck, many=False) return Response(serializer.data) @api_view(['DELETE']) def deleteTruck(request, pk): truck = Truck.objects.get(id=pk) truck.delete() return Response('Truck Deleted!') urls.py urlpatterns = [ path('trucks/', views.getTrucks, name="trucks"), path('trucks/<str:pk>/', views.getTruck, name="truck"), path('trucks/create/', views.createTruck, name="create-truck"), path('trucks/delete/<str:pk>/', views.deleteTruck, name="delete-truck"), path('trucks/update/<str:pk>/', views.updateTruck, name="update-truck"), ] I might be passing in user wrong, but I'm not sure. thanks in advanced. -
How to make drag&drop with dropzone js in django?
I have a django website, and I would like to implement drag&drop to my form. This part is looking very old compare to the rest of site. Problem is that I don't know javascript, I have tried to make it from tutorials but did not make any sense. Just got confused even more, but don't have time to learn js from scratch right now. Can you help me to get simple solution for this. I have been suggested to try with dropzone js but did not work, can someone help me create this solution? cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} urls.py urlpatterns = [ path('', views.home, … -
How do you migrate a custom User model to a different app in Django?
In Django, I am trying to move a custom User model from one app to another. When I follow instructions such as found here, and try to apply the migration, I get errors with ValueError: Related model 'newapp.user' cannot be resolved that originate from django.contrib.admin.models.LogEntry.user, which is defined as models.ForeignKey(settings.AUTH_USER_MODEL, ...), so that is a model from the Django admin (which I also use) that has a foreign key to the User model. How can I do this migration? -
Docker build in GitHub Actions has different behavior than local build
i deploy a Django application with Docker running Apache2. If i build the image locally and push it to the server i can run it just fine. The problems start when i build and push the image to the server with GitHub Actions. The container runs fine but if i try to access the site i get an Apache internal server error. The error log shows: ModuleNotFoundError: No module named 'django' When i get a bash into the running docker container and execute pip freeze i see all needed packages from my requirement.txt (including django). My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get dist-upgrade -y WORKDIR /var/www/api # add code ADD . /var/www/api # install python dependencies RUN apt-get install default-mysql-client -y && apt-get install default-libmysqlclient-dev -y && apt-get install libssl-dev -y && pip install -r requirements.txt # install apache2 and additional modules RUN apt-get install apache2 -y && apt-get install libapache2-mod-wsgi-py3 -y RUN a2enmod headers # copy server configs COPY 000-default.conf /etc/apache2/sites-available/ RUN sed -i 's/Listen 80/Listen 8000/g' /etc/apache2/ports.conf RUN python manage.py collectstatic CMD ["apache2ctl", "-D", "FOREGROUND"] GitHub Actions: name: CI on: push: branches: [ main ] pull_request: branches: [ main ] workflow_dispatch: jobs: … -
Setting a default of 0 to IntegerField not working
In my Django project the user inserts values of items from 1 to 5. I am trying to add them together so I got at first an error: unsupported operand type(s) for +: 'int' and 'NoneType' so I added the default for each IntegerField to be 0, but still receiving the same error. My question how can I add these classes in Model avoiding this error. class Info(models.Model): item_1_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 1 Amount') item_2_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 2 Amount') item_3_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 3 Amount') item_4_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 4 Amount') item_5_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 5 Amount') total_assets= models.IntegerField(null=True, blank=True, verbose_name='Total Assets') @property def get_total_assets(self): return int(self.item_1_amount) + int(self.item_2_amount) + int(self.item_3_amount) + int(self.item_4_amount) + int(self.item_5_amount) # @property # def get_total_assets(self): # return self.item_1_amount + self.item_2_amount + self.item_3_amount + self.item_4_amount + self.item_5_amount def save(self, *args, **kwargs): self.total_assets = self.get_total_assets super(Info, self).save(*args, **kwargs) -
Clone items with django CreteModelMixin
I have a class-based viewswet that uses the CreateModelMixin mixin. when I make requests from the front to my viewSet it does things correctly, in this case it is creating a new item. now I want to use that same viewset but from another viewSet ... Actually what I want to do is a copy of all the services that the Order contains, I have tried in several ways but I have not been able to and now I am thinking of making requests to the viewSet itself that creates the services. I already tried eliminating the IDs of the services and doing a .save () but it doesn't work .. also use serializer but nothing ... If you see, in the first part of the code if I could correctly clone the Order but when trying it with the services it does not work ... # **This works correctly** class ServicioViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Servicio_r.objects.all() serializer_class = ServicioRserializer // front endpoint... await self._create(`create_service/`, self.grupoDatos, (response) => {})... # Here I want to clone the services ... or make requests to the previous # viewset to be able to clone them (create them) class DuplicarOrdenViewSet(generics.ListAPIView): … -
What's a good shared hosting for django app?
I am looking for a hosting for my Django webapp. It's a very simple website but it may grow in the future. I know everybody says it is not a good idea to get a shared hosting for django and that I should get a VPS. But the VPS I've found are way too expensive for me, also they might be too big for the size of my project. Any shared hosting recommendations for a small Django project? I know there are some questions about this on StackOverflow already but the ones I've read may be outdated. -
Creating links on my blog site to share blogs to other social media sites
I am creating a blog website and I want in the blog_details page to create an anchor tag for Facebook, Instagram and Twitter such that a user can share the blog to the sites with only one click. Which is the best way to do this? So far I have nothing since I dont have a good idea of how to do it. Am using Django. And also, I have come across articles saying that its possible to integrate a blog site to social media platforms so that when a blog is published, it automatically creates a post on the social media platforms. How can I do this? -
How to include Address Model in Profile Model (Django)
I am struggling with how I should structure my application and some things are not working as expected. What I am working on is a form that is supposed to let a user set a billing (possibly also a shipping) address. Unfortunately, if I include the option billing address in the profile form, it lets the user choose from all addresses in the database, also from other users. If I omit this, the address that the user enters gets saved in the database, but it is not connected to the user, and every time the user updates the form it saves the address again. What I want is: Address gets saved in relation to the user Addresses are not redundant Users shouldn't be able to see the address of another user I will attach the snippets that I think are relevant below. I am not sure if and how to change the views function in order to save the input from the billing address in relation to my user or if I should change the models, which I would rather avoid because I want to keep them simple. forms.py ... class ProfileEditForm(forms.ModelForm): date_of_birth = forms.DateInput() class Meta: model = Profile … -
How can I treat allauth password reset as email verification?
My system is already aware of the users' email addresses. When a user signs up, they get an error message from allauth: A user is already registered with this e-mail address. I advise users to reset their password when they see this message. However, once they've reset their password, allauth triggers the email address confirmation flow, since ACCOUNT_EMAIL_VERIFICATION = True. It is inconvenient and unneccessary for the user to also do email validation at this point. How can I avoid email verification in this scenario? -
how can i filter queryset by checked form checkboxes in django?
I need to update the model according to the marked checkboxes in the django shape How can I get only some of the table fields in a query the "checked" line should be updated through the queryset models.py class moIn(models.Model): date = models.DateTimeField(auto_now_add=True, verbose_name='') dateUpdate = models.DateTimeField(auto_now=True) ts = models.IntegerField(verbose_name='') pl = models.IntegerField(verbose_name='') rem = models.IntegerField(verbose_name='') comment = models.TextField(max_length=200, verbose_name='', blank=True) staffer = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='') checked = models.BooleanField(verbose_name='', default=False) checkedUser = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='', blank=True, null=True, related_name='checkedUser') by clicking this checkbox, you will need to receive database records forms.py class checkForm(ModelForm): checked = fields.BooleanField(required=False) class Meta: model = moIn fields = {"id", "checked"} views.py def dashboard(request): if request.user.groups.filter(name='DashBoardAccess').exists(): form = checkForm f = tableDashFilter(request.GET, queryset=moIn.objects.all()) if request.method == 'POST': form = checkForm(request.POST) if form.is_valid(): tt = form.save(commit=False) data = form.cleaned_data field = data['checked']=True f.qs.filter(checked=field).update(checked=True, checkedUser=request.user) return HttpResponse('ok') else: context = { 'filter': f, 'form': form } return render(request, 'dashboard/index.html', context) else: raise Http404() in a line in bold, you need to get only those lines in which the checkbox is marked f.qs.filter(checked=field).update(checked=True, checkedUser=request.user) html <form action="" method="post"> {%csrf_token%} <tbody class="table-view__body"> {% for out in filter.qs %} <tr> <td> <label class="custom_Label"> {{form.checked}} <span class="checkmark"></span> </label> </td> <td>{{out.date|date:"d(D).m.Y"}}</td> <td>{{out.ts}}</td> <td>{{out.pl}}</td> <td>{{out.rem}}</td> … -
how to pass an object by url to serializer
I want to create an API that takes care of a site to list movies and make ratings of each movie. Kind of like a movie review. The problem I have is how to make the qualification, how could it be? I leave you the models that I have! class Movie(models.Model): """Movie model.""" title = models.CharField(max_length=250) image = models.ImageField( default='movies/images/default.jpg', upload_to='movies/images/', ) description = models.TextField(blank=True, null=True) duration = models.TimeField() director = models.CharField(max_length=100) rating = models.FloatField(null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): """Return title.""" return self.title class Rating(models.Model): """Movie rating model.""" movie = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='rated_movie' ) rating_user = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, related_name='rating_user', ) comments = models.TextField(blank=True) rating = models.IntegerField(default=5) def __str__(self): """Return summary.""" return f'@{self.rating_user.username} rated {self.rating}: {self.movie}' The idea is that it is accessed through the url, e.g. api/v1/rate/1/ and the rating can be done with a comment and the score that is given. -
Heroku with whitenoise not serving django staticfiles
How do I get heroku to serve my static files on my django project? Ok, on a push to heroku, I get this message rlated to staticfiles: $ python manage.py collectstatic --noinput remote: 130 static files copied to '/tmp/build_48c64d55/staticfiles', 410 post-processed. But when I go to my site, clear static files not being recognized and Network tab shows me: GET https://pure-everglades-09529.herokuapp.com/static/style.css 404 Not Found This is the content of my html referencing the css I cannot find: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <title>{% block title %}My amazing site{% endblock %}</title> </head> Here is the bottom of my settings.py which is configured just like everywhere says it should be like: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Activate Django-Heroku. django_heroku.settings(locals()) Here is higher up in my settings, I have added whitenoise dependencies as recommended everywhere: INSTALLED_APPS = [ 'myapp.apps.MyappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # … -
How to provide user types while registering as a user using google in Django rest framework
I have a customeuser model which inherits from AbstractUser. I have also used sign-up using google feature. But now later in my project, I have to add user types. For eg user can be owner,manager and staff and they have their own privileges. My model: ROLE = (('owner','OWNER'),('manager','MANAGER'),('staff','STAFF')) class User(AbstractUser): SOCIAL_AUTH_PROVIDERS = ( ("GOOGLE", ("GOOGLE")), ("FACEBOOK", ("FACEBOOK")), ("TWITTER", ("TWITTER")), ) name = CharField(_("Name of User"), blank=True, max_length=255) email = EmailField(_("Email Address"), unique=True) mobile = CharField( _("Mobile Number"), max_length=16, unique=True, blank=True, null=True ) email_verified = BooleanField(default=False) social_auth = CharField( choices=SOCIAL_AUTH_PROVIDERS, max_length=100, blank=True, null=True, ) role = models.CharField(max_length=15, choices=ROLE, default='staff') #added this field later first_name = None last_name = None username = None USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() Here I migrated a new field role to the user model because I needed it because of business requirements. The change in my serializer will be like this. class UserRegisterationSerializer(serializers.ModelSerializer): def validate(self, data): email = data["email"] password = data.get("password") role = data["role"] #added this part mesg = "This email has been already registered." if User.objects.filter(email=email).exists(): raise serializers.ValidationError({"email": mesg}) if password: user = User(email=email,role=role) #added role here too try: validate_password(password=password, user=user) except Exception as e: raise serializers.ValidationError({"password": e.messages}) return data Here … -
Latest() function gives, addPost(ModelName) matching query does not exist error
I had an object that their id was 47(this was a latest object) so latest() method was giving me the correct result but when i deleted the object that their id had 47, now my latest object is that, which id has 46.. When i am trying to get the latest object it raise error matching query does not exist.. it should give me the latest object.. models.py from django.db import models from datetime import datetime # Create your models here. class addPost(models.Model): postId = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) image = models.ImageField(upload_to="blog/images", default="") content = models.TextField(default="") date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = "date" views.py def index(request): obj = addPost.objects.all().latest() print(obj.postId) -
Running Django tests without collect static
I am trying to run a test suite for django that uses inlinecss. inlinecss references a static file in the template as follows: {% load inlinecss %} {% inlinecss "css/emails/base.css" %} When running in Debug mode this works fine, when running in production (having run collectstatic) this also works fine. However when running tests (without running collectstatic before) I get the following: FileNotFoundError: [Errno 2] No such file or directory: '/app/project-name/staticfiles/css/emails/base.css' This makes sense as django is looking for the file in STATIC_ROOT (STATIC_ROOT = os.path.normpath(join(os.path.dirname(BASE_DIR), "staticfiles"))) I am wondering if there is a way to allow Django to access this file without having to run collectstatic? It would be ideal if I could add some settings to test.py so that it could collectstatic to a tmp directory or not require collectstatic at all (like when running in debug mode) but I have had no success trying this. I am using pytest to run tests. -
Show folium map received in django JsonResponse using javascript
I am sending a folium map through django JsonResponse. While rendering, I just can't make it show the map. I am using d3.js. I just don't understand how to add a '|safe' equivalent action. Here is my view: def show_map(tuple_lat_lon, name): start_coords = tuple_lat_lon[0] folium_map = folium.Map( location=start_coords, zoom_start=14 ) folium.CircleMarker( tuple_lat_lon[0], radius=8, popup=name, color='#3186cc', fill=True, fill_color='#3186cc' ).add_to(folium_map) folium.Polygon(tuple_lat_lon).add_to(folium_map) buffer = io.BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') return graphic farm_map = show_map(tuple_lat_lon, 'MyMap') return JsonResponse({ 'farm_map':farm_map, }) Here is my d3.js code: var farm_map = block_details_response['farm_map']; d3.select('#block_map').append('img').attr('src', farm_map); here is the html: <div id="block_map"></div> I can see when I inspect html, the image code...but not the image. So I want to know: Is it a good idea to send folium map in response? I did it cause I call a lot of my own apis on the web page. As tutorials suggest, this the way to show the map:{{ farm_map | safe }} . I can't do that since I am using d3.js . Essentially javascript. I tried d3.select('#block_map').append('img').attr('src', farm_map + '|safe'). Did not work. Any ideas suggestions are welcome -
Get a javascript element by ID from select and pass to Django url
I have select options and I want to send the value to a url offside the form (because I'm using a image as a link). html: <form action="" method="GET" id="maintenanceForm"> <div class="form-group col-md-4"> <label for="assigned" style="font-size:medium;">Assigned</label> <select class="form-control" id="assigned" name="assigned"> <option value=""></option> <option value="a.takao">André Takao</option> <option value="adam.m">Adam William</option> <option value="alex.matos">Alex Matos</option> </select> </div> </form> <a href="{% url 'maintenance_issue_validation_approved' %}?id={{ maintenance_issue.id }}&assigned=assigned"> <img src="{% static 'images/icons/approved.png' %}"> </a> <script> var assigned = document.getElementById('assigned').value; return assigned; </script> views: def maintenance_issue_validation_approved(request): if request.method == 'GET': issue_id = request.GET.get('id') assigned = request.GET.get('assigned') print(assigned) How to get the "assigned" select value and send it to my view? The expected value is, print the selected assigned value: for example: adam.m