Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django easypost buy returns malformed syntax when using test api key but insufficient funds with production
Using the easypost python library I call the buy function passing in the rate like the documentation says but it returns an error. Can you use your test api key with buy for easypost or not? I didn't see anything in the documentation with it. It might seem to work with production but I am not able to test that yet so I was wondering if I could test it with the test api key? The code is: import easypost def get_shipment(shipment_id): return easypost.Shipment.retrieve(shipment_id) ...... shipment = get_shipment(shipment_id) try: shipment.buy(rate=shipment.lowest_rate()) except Exception as e: raise ValidationError({'detail': e.message}) The error message I get with test key Traceback (most recent call last): File "/app/returns/serializers.py", line 237, in handle_shipment_purchase shipment.buy(rate=shipment.lowest_rate()) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 725, in buy response, api_key = requestor.request('post', url, params) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 260, in request response = self.interpret_response(http_body, http_status) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 321, in interpret_response self.handle_api_error(http_status, http_body, response) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 383, in handle_api_error raise Error(error.get('message', ''), http_status, http_body) easypost.Error: The request could not be understood by the server due to malformed syntax. -
Django Redirect does not work at all within view
I am trying to get my view to redirect to another page after clicking a button that triggers the POST request. I cannot seem to figure out why the redirect doesn't work or why it doesn't even seem to try to redirect. Here is my view: def cart1(request): if request.user.is_authenticated: #POST if request.method == "POST": #JSON Data data = request.body new_data = ast.literal_eval(data.decode('utf-8')) customer = request.user user_order = Order(user=customer) user_order.save() x = 0 while x < len(new_data.keys()): obj_title = new_data[x]["title"] obj_price = new_data[x]["price"] obj_quantity = new_data[x]["quantity"] obj_extra = new_data[x]["extra"] total = round(float(obj_price.replace("$", ""))) m = OrderItem(order=user_order, title=obj_title, price=total, quantity=obj_quantity, extra=obj_extra) m.save() x += 1 redirect('checkout-page') return render(request, 'cart.html') Any help would be appreciated, thank you -
Registration of application in Django
I need a custom section of application on admin site. It must not consider any model (proxy, unmanaged, etc), without template overriding, just a "phantom" application in programmatic way. I expect it looking like a bunch of URLs, registered in admin and located in separated section on index page. Hours of search and other answers without result. I tried this way in existing application, but links didn't appear. I did class MyModel(models.Model): class Meta: managed = False registered as ModelAdmin, and it's work, and for my luck URL fully matches with my view, so I don't need make real migrations, but I find this approach too rough. I really hope, there is more elegant way, but, perhaps, I must know Django deeply. -
img src returning 404 when path is correct
html template: {% load static %} <img src="{% static image_url %}"> <p>{{ quote }}</p> view: def makeImage(request): image = request.FILES['image'] quote = request.POST['quote'] fs = FileSystemStorage(location="static/") filename = fs.save(image.name, image) image_url = fs.url(filename) return render(request, 'app/makeImage.html', {'image_url': image_url, 'quote': quote}) error [05/May/2022 15:56:13] "POST /app/makeImage/ HTTP/1.1" 200 49 [05/May/2022 15:56:13] "GET /static/Space_Yzkaqwp.jpg HTTP/1.1" 404 1810 ........................................................................................................................................................................................................................................................................................................................... -
Django: how to filter posts based on view in django
i want to filter posts based on views e.g view>100 that is to filter course if only the view is greater is 100 views but it keeps showing this error SyntaxError: positional argument follows keyword argument. the way i am filtering the posts is the issue but i don't know the right way to do this. I have a field views = models.In... in my models.py, so that is why i am trying to filter course like course = Course.objects.filter(views>100) then it shows the error models.py class Course(models.Model): course_title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True) views = models.IntegerField(default=0) views.py def index(request): pop_courses = Course.objects.filter(course_publish_status="published", views>100).order_by('?') -
Django forms - Pandas displaying integer as columns names instead of actual names
I'm building a form to select columns from a CSV/XLSX file and then convert the selection to a dataframe. The parsing is working and I can get a dataframe. But in the dataframe, columns names are integers and not the actual names. I can't figure out why. My forms in forms.py which enables me to select columns: class CompareFormTransporteur(forms.ModelForm): file = forms.FileField(label="Fichier (CSV, XLSX, XML) ", required=True) header_row = forms.IntegerField(label="Header row", required=True) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.request.session['header_row'] = self['header_row'].value() super().__init__(*args, **kwargs) def clean(self): super().clean() extension = os.path.splitext(self.request.FILES['file'].name)[1] integer = self.request.session['header_row'] print(integer) if extension in ['.xlsx', '.xls']: uploaded = parse_excel(self.request.FILES['file'], rowheader=2) elif extension == ".csv": uploaded = parse_csv(self.request.FILES['file']) elif extension == ".xml": uploaded = parse_xml(self.request.FILES['file']) self.request.session['uploaded'] = uploaded self.request.session['profile'] = self.cleaned_data.get('profile') class CompareFormPartTwo(forms.Form): columns = forms.MultipleChoiceField(label="Colonnes", widget=forms.CheckboxSelectMultiple()) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.uploaded = request.session['uploaded'] columns_choices = [] for key in enumerate(self.uploaded): columns_choices.append(key) self.fields['columns'].choices = columns_choices def clean_columns(self): """Valide les données sur les columns et transforme les choix en int.""" columns = self.cleaned_data['columns'] return [int(column) for column in columns] def clean(self): super().clean() self.request.session['selection'] = self.cleaned_data.get('columns') print(self.request.session['selection']) My code in views.py: class FormCompareTransporteur(RequestFormMixin, … -
How to add custom claim in django rest_framework_simple_jwt?
Their official doc only shows implementation for class based views. How to get this done for a function, ie. Refreshtoken.for_user()? from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } Snippet from here. This only shows how to create token manually. I know using pyjwt would make life simpler but there will be another workaround for blacklisting. -
I can not render a new user registration form from a model ViewSet in Django Rest frame work
class RegisterViewSet(viewsets.ModelViewSet): http_method_names = ["post"] permission_classes = (AllowAny,) serializer_class = RegisterSerializer renderer_classes = [TemplateHTMLRenderer] template_name = "api/authentication/template/authentication/register.html" def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response( { "success": True, "userID": user.id, "msg": "The new user is successfully registered", "serializer":serializer, "form": UserRegisterForm }, status=status.HTTP_201_CREATED, ) i just want to render a form to display to HTML . basically , how to render form from a model viewset from django rest framewor k. -
Django dumpdata serializing an int as string
I've been trying to make a custom class/type, defined in a separate db.py file, to be properly serialized as an int when doing a manage.py dumpdata command, but this BitFlagField always ends up exported as a string, the value accompanied by double quotes, while other integer fields are properly exported without the quotes in the JSON file. The person that made it left the place almost a year ago, so I can't get any help from him. This is the class' code - note that I've fixed the __str__ function and also changed the __repr__ to return repr(self.value) This is how it looks after the dumpdata: (...), "blocked": "8"}} ; For comparison, two other integer fields don't come with the value enclosed by quotes: "pk": 1, "bit":8,. Because of this, manage.py loaddata fails: django.core.serializers.base.DeserializationError: Problem installing fixture '/home/abcd/djangoapp/data.json': '>=' not supported between instances of 'str' and 'int': (core.userextra:pk=1) field_value was '8' If I manually remove the quotes from the "blocked" field's value, the loaddata command works. If I delete both __str__ and __repr__ functions, the object type is what ends up as the data: (...), "blocked": "<core.db.BitFlag object at 0x7f9f2eb0bf40>"}}. If I make either of them return self.value, it complains … -
I am trying to pop up error message in Django using messages, but it's not working
I am trying to pop up error message but it's not working. Do you see any problem in this coding? Thank you. -
Using double underscore to directly update foreign key's field in Django?
I am using double underscore to filter a model or get values from it in Django like this: # filtering model furthers = myModel.objects.filter(foreignKeyField__furtherField=value) # getting values furtherField = myModel.objects.get(id=10).values("foreignKeyField__furtherField") But when I try to use update() method with double underscore like this: myModel.objects.filter(id=10).update("foreignKeyField__furtherField") I get an error: django.core.exceptions.FieldDoesNotExist: myModel has no field named 'foreignKeyField__furtherField' I looked up documentations about this but there is neither usage example of double underscore for update() method nor a word I cant use it like this way. So could we say update() method cannot be used like this? -
what should i write in the settings.py to import my Template
I have deployed my project on pythonanywhere and there i am getting an error that template does not exist It's working properly on local host File directory settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] Can someone tell what should i add my template DIRS -
Forbidden (403) CSRF verification failed. Request aborted. django error
I want to post a form with HTML <form method="POST" enctype="multipart/form-data"> {% csrf_token %} // some inputs </form> My middlewares are these MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] When I try to post a form, it is showing the following error Forbidden (403) CSRF verification failed. Request aborted. -
Installation of Spatialite with Django on windows 10
I am struggling to find out how to install spatialite for geodjango on windows but I don't know what I am doing wrong. I follow the instructions as per the django page https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/spatialite/ but the tutorial doesn't say what to do after getting the binarys of spatialite I have tried to put them everywhere but every time I get the same error: Exception Value: Unable to load the SpatiaLite library extension as specified in your SPATIALITE_LIBRARY_PATH setting I tried to put the mod_spatialite.dll file everywhere and try to set to SPATIALITE_LIBRARY_PATH but it seems I can't get the solution Any suggestions would be appriciated Thanks -
Django multiple upload drag and drop not working
I want to do an update on a current web app I developed with Django. The current version has multiple uploading fields: And I changed it to this: Now I don't know how to update the code to do exactly the same thing, I made some changes, but I can't seem to get the files from the dropzone using request.FILES.getlist('files') Here is my old code: HTML: <h5>Documents de base</h5> {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} View: ................... if request.method == "POST": dossierForm = DossierForm(request.POST) formset = DocumentFormSet( request.POST, request.FILES, queryset=DocumentdeBase.objects.none() ) formset2 = PhotoAvantFormSet( request.POST, request.FILES, queryset=PhotoAvant.objects.none() ) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): ................... for form in formset.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form: image = form["documentdebase_image"] photo = DocumentdeBase( dossier=dossier_form, documentdebase_image=image ) photo.save() for form2 in formset2.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form2: image2 = form2["photoavant_image"] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() .................... else: dossierForm = DossierForm() formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) Form: class DocumentdebaseForm(forms.ModelForm): documentdebase_image = forms.ImageField(label="") class Meta: model = DocumentdeBase fields = … -
Django Admin disable a html field by a another field value
I have a django model and I want to disable the other field according to the selection of one field in my admin panel. Look at the picture if the "User Auth Filter" field is "Only Unauthenticated Users", I want the "Linkedin Filter" field to be disabled from html. like this: How can I do the "disabled html" operation before saving from the admin panel. -
Django & React integration without using an API
Is there anyway to use django and react while keeping the business logic, routing, etc on the django side ? I want to use react for the ui features and the state management but on the other hand i don't like to do the business logic on the front end and just use drf as an api for the data. The way i would imagine it is to render mini react apps instead of django templates but i have no clear way to implement this and i don't even know if it's technically possible. I would like to get some guidance from more experienced developers. Thanks -
Django throws "connection to database already close" error on Scrapy + Celery task
Context I have a Django application running inside a Docker container. This application uses Celery and Celery-beat for async and scheduled tasks. One of those tasks scrapes texts from different webs using Scrapy. This task runs every minute looking for new texts on the pages. If there is new information, it creates a new object in MyModel. This logic (querying the database to check if data exists, and create the object or update the info) is performed by a custom Scrapy item pipeline. Issue When using Development environment (using locally Docker Compose to turn on one container for the app, one container for PostgreSQL plus other services containers) everything runs smoothly. However, when using Stage environment (one Docker container for the app on a DigitalOcean droplet and a PostgreSQL self-managed cluster) the tasks throws this error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/twisted/internet/defer.py", line 857, in _runCallbacks current.result = callback( # type: ignore[misc] File … -
Django: Create a superuser in a data migration
Goal: automatically creating a superuser I'm trying to create a default user, specifically a superuser, in an early data migration, so whenever my Django application is run in my Docker container, it already has a superuser with which I can access the admin site. I had already tried different options for creating said superuser, and although I have some functioning ones (based on the command parameter of my docker-compose file), I've seen when adding initial data to a Django project, the best practice is to do it through a Data Migration. My custom user In my Django project I've extended the AbstactBaseUser so I can change the default username field requirement for the email field. My User is as such: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): # Implementation... def create_superuser(self, email, password, **extra_fields): # Implementation... class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="email address", max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email Failed attempts By following the Django documentation here I tried making my superuser in a data migration with the following code, located in a file called 0002_data_superuser in the migrations folder of my app: … -
Deploying FrontEnd and BackEnd as two separate applications with Google Cloud App Engine
I have two application that I want to deploy with Google Cloud App Engine. One of them is react front end, and I want to serve this through www.videoo.io Second one is back-end, which will be served via api.videoo.io Frontend yaml file react.yaml : runtime: nodejs16 env: standard handlers: - url: /static static_dir: static secure: always - url: www.videoo.io/* service: frontend script: auto secure: always% API yaml file, api.yaml : runtime: python37 entrypoint: gunicorn -b :$PORT videoo.wsgi service: "videoo-api" env: standard handlers: - url: api.videoo.io/* service: backend script: auto secure: always% Is this the correct way to achieve this ? What is the best strategy to serve these two separate applications that will interactively communicate (Frontend will make calls to API to get object information that is stored Django app) ? Here is also my domain name information in Google App Engine settings : -
Django kwargs doesn't retrieve value after page reload
I got this code in my view. @login_required(login_url='login_user') def user_profile(request, **kwargs): user = request.user post_form = PostForm(instance=user) post_func = post(request) user_n = kwargs.get('username') READ THIS PLEASE! user_n it returns the username of the current user, but for some reason, after I create posts with the post function it doesn't get the username, but it gets str:username instead when I print it to console. Does anyone know why and how I can fix this? print("This is the user logged in: ", user.username, user_n) EXAMPLE for the print above("This is the user logged in: ", user.username = current username, user_n = str:username (this is happening only when I use the post function to post some content. Any other time user_n = current username)) user_data = {} try: current_user_username = NewUser.objects.get(username=user_n) current_user_profile = Profile.objects.get(relation_id=current_user_username.id) except: return redirect("profiles") is_self = True if current_user_username: current_profile_posts = Posts.objects.filter(post_relation_id=current_user_username.id) user_data['current_profile_id'] = current_user_username.id user_data['current_profile_username'] = current_user_username.username user_data['current_profile_email'] = current_user_username.email user_data['current_profile_title'] = current_user_profile.title user_data['current_profile_avatar'] = current_user_profile.avatar user_data['is_self'] = is_self else: pass if post_func is not None: print("If post_func is not none: ", post_func) return post_func elif post_func is None: print("If post_func is none: ", post_func) pass else: print("This state of post_func should never activate: ", post_func) return http.HttpResponseRedirect('/UserProfile/<str:username>/') context … -
by inheriting the class base view, my own form does not work in django
I write my own login form inheriting LogonView, with my own Form. My own form does not have a password field! because I send a temperory password to the email given by a user. But when I inherit LoginView, the form has 2 fields : username and password. If I inherit CreateView instead of LoginView, instead of displaying profile, it returns: User matching query does not exist. I am newdeveloper. Your help is appreciated. -
Django Rest Framework: KeyError when Overriding 'update' Function in a Serializer
I have a User model and a Group model, which are presented below: class User(models.Model): username = models.CharField(primary_key=True, max_length=32, unique=True) user_email = models.EmailField(max_length=32, unique=False) user_password = models.CharField(max_length=32) user_avatar_path = models.CharField(max_length=64) class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=32, unique=False) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='my_groups') members = models.ManyToManyField(User, related_name='groups', through='UserGroup') Every group can have multiple users associated with it and every user can be associated to multiple groups, which is modeled with a ManyToManyField and a through model between the models. When I create a group, the user which creates the group is automatically assigned as the group admin and therefore added as a member of the group: class MemberSerializer(serializers.ModelSerializer): # The nested serializer used within the GroupSerializer username = serializers.ReadOnlyField(source='user.username') class Meta: model = User fields = ['username'] class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(source='user_groups', many=True, required=False) group_admin = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) # A Group object is related to a User object by username class Meta: model = Group fields = ['group_id', 'group_name', 'group_admin', 'members'] def create(self, validated_data): # Overriden so that when a group is created, the group admin is automatically declared as a member. group = Group.objects.create(**validated_data) group_admin_data = validated_data.pop('group_admin') group.members.add(group_admin_data) return group def update(self, instance, validated_data): members_data = validated_data.pop('members') # … -
Function of defining an absolute URL in a model in Django
I am currently completing the final capstone project for Django on Codecademy, and I've come across a comprehension issue. On Codecademy, they state that it's used to redirect to the homepage when a user submits data, while the Django documentation for get_absolute_url seems to make no reference to redirects. I currently have no absolute urls defined for any of my models, and these are my url patterns and views. At this stage, I'm just trying to understand the purpose of defining an absolute URL in a model, and where the appropriate places to utilize it are. I'm very confused about it's function currently, and would appreciate a simplified explanation with examples. -
Django Rest API is producing 500 status code
I am tasked with creating a Django Rest API containing a serializer. Here is the specific instructions: Instructions Here is my model.py: from django.db import models class Wish(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100,blank=True,default='') wishtext = models.TextField() class Meta: ordering = ('created',) My serializers.py: from rest_framework import serializers from wishes.models import Wish #Add WishSerializer implementation here class WishSerializer(serializers.Serializer): created = serializers.DateTimeField() title = serializers.CharField(max_length=100, default='') wishtext = serializers.CharField() my views.py: from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from rest_framework.response import Response from rest_framework.parsers import JSONParser from wishes.models import Wish from wishes.serializers import WishSerializer @csrf_exempt def wish_list(request): pass """ List all wishes or create a new wish """ if request.method == 'GET': qs = Wish.objects.all() serializer = WishSerializer(qs, many=True) return Response(serializer.data) if request.method == 'POST': serializer = WishSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) @csrf_exempt def wish_detail(request,pk): pass """ Retrieve, update or delete a birthday wish. """ try: wish = Wish.objects.get(pk=pk) except Wish.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = WishSerializer(wish) return Response(serializer.data) elif request.method == 'PUT': serializer = WishSerializer(instance=wish, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) elif request.method == 'DELETE': wish.delete() return Response(status=204) and my url.py: from django.conf.urls import url …