Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to re-upload/Update data with django-import-export
I have uploaded data into the system. I however went ahead and edited soe of the data in the excel, meaning there are changes in that excel. When I want to re-upload so that the changes made can reflect, it doesn't accept. I can't tell why. It says like such data already exists in the system. I have skip_unchanged = True but that isn't helping. Is my model setup having a hand in this? unique_together = ("school", "student_id",)? class ImportStudentsResource(resources.ModelResource): def __init__(self, school_id,klass,*args, **kwargs): super().__init__() self.school_id = school_id self.klass = klass self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Student,'id')) self.fields["stream"] = fields.Field(attribute="stream",column_name="stream",widget=StreamForeignKeyWidget(klass,),) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id instance.klass_id = self.klass#2 def before_import_row(self, row, **kwargs): row['stream'] = row['stream'].lower() class Meta: model = Student import_id_fields = ('id',) fields = ('student_id','name','year','stream') import_order = ('student_id','name','year','stream') skip_unchanged = True The view . class uploadF1Students(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): klass = get_object_or_404(Klass,school_id=request.user.school.id,name=1).id school_id = request.user.school.id form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportStudentsResource(school_id,klass) try: result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) except Exception … -
using curly double brackets inside another curly double brackets in django template
I started studying Django few days back, while doing a project I came across a situation. In the views.py, I'm passing def chat_rooms(request): context = dict() context['title'] = 'Chat' rooms = Chat_rooms.objects.filter(Q(user1 = request.user.id) | Q(user2 = request.user.id) ) context['rooms'] = rooms for room in rooms: rmssg = Chats.objects.filter(room_id = room.id) lmssg = Chats.objects.latest('id') context[str(room.id)] = lmssg return render(request,'previlageGroup/chat_rooms.html',context) In the Django template,chat_room.html {% for room in rooms %} <div class="card" style="width: 100%;"> <a href="{% url 'pgroup:chat.screen' room.id %}"> <div class="card-body"> <p class="card-text"> {{ {{room.id}}.message}} </p> </div> </a> </div> {% endfor %} In models.py class Chat_rooms(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user1') user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user2') created_on = models.DateTimeField(auto_now_add=True) class Chats(models.Model): date = models.DateTimeField(auto_now_add=True) has_viewed = models.BooleanField(default= False) message = models.CharField(max_length = 200) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') room = models.ForeignKey(Chat_rooms, on_delete=models.CASCADE) Django is giving me a error, that {{ {{room.id}}.message }} is not possible. How can I do this? Is there any other way? Thanks in advance -
Error when deploying django web application with daphne: Requested setting INSTALLED_APPS, but settings are not configured
I have been battling with an error that I encountered when trying to deploy a django application that uses channels. Error in heroku logs Starting process with command `daphne friendship.asgi:application --port 52589 --bind 0.0.0.0 -v2` 2021-06-02T19:51:57.338171+00:00 heroku[web.1]: Process exited with status 1 2021-06-02T19:51:57.105387+00:00 app[web.1]: Traceback (most recent call last): 2021-06-02T19:51:57.105477+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-06-02T19:51:57.105796+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-06-02T19:51:57.105861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-06-02T19:51:57.106200+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-06-02T19:51:57.106259+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-06-02T19:51:57.106713+00:00 app[web.1]: application = import_by_path(args.application) 2021-06-02T19:51:57.106774+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", line 12, in import_by_path 2021-06-02T19:51:57.107059+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-06-02T19:51:57.107118+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-06-02T19:51:57.107436+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-02T19:51:57.107491+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-06-02T19:51:57.107783+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-06-02T19:51:57.107986+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-06-02T19:51:57.108196+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-06-02T19:51:57.108533+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-06-02T19:51:57.108768+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-06-02T19:51:57.108967+00:00 app[web.1]: File "./friendship/asgi.py", line 5, in <module> 2021-06-02T19:51:57.109233+00:00 app[web.1]: import errands.routing 2021-06-02T19:51:57.109290+00:00 app[web.1]: File "./errands/routing.py", line 2, in <module> 2021-06-02T19:51:57.110045+00:00 app[web.1]: from . import consumers 2021-06-02T19:51:57.110094+00:00 app[web.1]: File "./errands/consumers.py", line 3, in <module> 2021-06-02T19:51:57.110331+00:00 … -
How do I get stripe's application fee to reflect the adjustable quantity during checkout?
I added the adjustable quantity for Stripe's check out session call. I understand that the fee object is created after the payment. I'm looking at the application fee object in stripe's documentation and it says it is capped at the final charge amount. How do I retrieve the charge amount or better, quantity during the checkout session? checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], customer=customer.id, payment_intent_data={ 'application_fee_amount': int(stripe_price * fee_percentage), 'transfer_data': { 'destination': seller.stripe_user_id, }, }, line_items=[ { 'price_data': { 'currency': currency, 'unit_amount': price, 'product_data': { 'name': title }, }, 'adjustable_quantity': { 'enabled': True, 'minimum': 0, 'maximum': available_quantity, }, 'quantity': 1, }, ], metadata={ "product_id": product.id, "client_reference_id": user.id, }, mode='payment', ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) -
Django Class Based Views Flow
My app is data driven with a postgres db. When a user first sees my “customers” page I would like all existing db entries to be displayed. This part I am using ListView in my class based view. I would also like for these fields to be update-able, removable, as well as have the ability to create new entries. What is the proper way to implement this? -
Django display foreign key on admin dashboard when inheriting from AbstractUser not working?
I'm having a model like a restaurants model from django.db import models class Restaurants(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=250) location = models.CharField(max_length=200) rating = models.DecimalField(null=True,decimal_places=2,max_digits=5) def __str__(self): return self.name class Meta: db_table = "Restaurants" verbose_name_plural = "Restaurants" And three different User models: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from restaurants.models import Restaurants class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) … -
Add a field in the database using the Django function
this is my model class : class complete_taxi_driver_account(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) STATUS_CHOICES = (('woman', 'Woman'), ('man', 'Man'),) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) phone_number = models.CharField(max_length=11) life_place = models.CharField(max_length=120) birth_date = models.DateTimeField(null=False, blank=False) gender = models.CharField(max_length=25, choices=STATUS_CHOICES, default='man') number_plates = models.CharField(max_length=8) national_code = models.CharField(max_length=10) car_number = models.CharField(max_length=50) name_and_type_of_car = models.CharField(max_length=50) # Check if this car is taxi , this field will change to True else False confirmation = models.BooleanField(default=False) # If the taxi app starts, this section will change True, meaning the taxi is ready to pick up passengers online = models.BooleanField(default=False) #I do not know what to do here to add these two fields to the database when this function is called def location(self): # Location of the taxi lat = models.DecimalField(max_digits=20, decimal_places=10) lng = models.DecimalField(max_digits=20, decimal_places=10) I want to have a function in the model class that, when called, creates two fields in the database and fills them in, and from now on be updated by calling it. How can I do this? -
DRF, in perform_authentication() the test for request.user is set to an empty string only when multiple tests are run
When I run a test by itself the test always passes, but when run even with one other test in the same test class it fails. I've tracked down the cause to the perform_authentication() method not having the AnonymousUser set instead, it is set to an empty string. This is not happening on all tests but maybe 20% of the 415 tests I've written. The change I made to the code was to use the Authorization header and removed the code that put credentials in the body of the login request. This should not have affected most of the tests that are now failing. If I override the perform_authentication() by catching the exception and just exiting the method the test works fine, but this is not what I want to do obviously. I would show code, but am not sure what to show. The tests have many layers since the same tests need to be done on many endpoints. Does anybody have a better idea as to how this authorization works? -
ReactJS How can I edit user with functional component useSelector
With the code I have, I am getting the user in input but the input won't change when I type here is the input <div className="pInput"> <label>last Name</label> <input type="text" className="ppInput" value={user.last_name} onChange={(e) => HandleEditDesc(e)} placeholder={user.last_name} /> </div> Here is my on change function e.preventDefault() user.last_name = useSelector((state) => e.target.value); state.auth.user.last_name = user.last_name } Here is how I am getting the user import React from "react"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; import Axios from "axios"; const Profile = () => { const user = useSelector((state) => state.auth.user); const subscriptionStatus = useSelector( (state) => state.auth.subscriptionStatus ); I am using Django as my backend -
Filtering three related models in django-filter
I have three models in my models.py file: models.py ################################## Application models ################################## class attack(models.Model): attack_name = models.CharField(max_length=200) defense_mechanism = models.CharField(max_length=200) def __str__(self): return self.attack_name ACTIONS = ( ('malware', 'Malware'), ('hacking', 'Hacking'), ('social', 'Social'), ('misuse', 'Misuse'), ('physical', 'Physical'), ('error', 'Error'), ('environmental', 'Environmental') ) class action(models.Model): action = models.CharField(max_length=15, choices=ACTIONS) attacks = models.ManyToManyField(attack) def __str__(self): return self.action ATTRIBUTES = ( ('confidentiality', 'Confidentiality'), ('integrity', 'Integrity'), ('availability', 'Availability') ) ACTORS = ( ('external', 'External'), ('internal', 'Internal'), ('partner', 'Partner') ) class security_incident(models.Model): asset = models.CharField(max_length=200) #one asset actor = models.CharField(max_length=15, choices=ACTORS) #one actor action = models.ForeignKey(action, on_delete=models.CASCADE) # one security incident can have several actiobns attributes = models.CharField(max_length=15, choices=ATTRIBUTES) #as many attributes as wished, should be two for hierarchial tree def __str__(self): return self.asset I am trying to filter these models in a django-filter filterset: class SecIncFilter(django_filters.FilterSet): asset = django_filters.CharFilter(lookup_expr='icontains', distinct=True, label='Search for security incidents, related attacks and defense mechanisms to an asset') attributes = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple(), choices=ATTRIBUTES, label='Choose categories') action = django_filters.MultipleChoiceFilter(name='action') class Meta: model = security_incident fields = ['asset','attributes'] def __init__(self, *args, **kwargs): super(SecIncFilter, self).__init__(*args, **kwargs) # at sturtup user doen't push Submit button, and QueryDict (in data) is empty if self.data == {}: self.queryset = self.queryset.none() And then rendering results into this … -
display different elements based on even and odd in Django html template
I am a noob at django. And I faced this problem: dest over here is a list which is coming from views.py. I want to use this(code below) for even occurrences : <div class="row no-gutters"> <div class="col-lg-6 order-lg-2 text-white showcase-img" style="background-image:url( {{baseUrl}}/{{dest.img}} );"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2> {{dest.name}} </h2> <p class="lead mb-0">{{dest.desc}}</p> The Price : <p class="lead mb-0" style="font-weight:bold">Rs. {{dest.price}}</p> </div> </div> and this(code below) for odd positions : <div class="row no-gutters"> <div class="col-lg-6 text-white showcase-img" style="background-image:url(&quot;{% static 'img/bg-showcase-2.jpg' %}&quot;);"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2>Updated For Bootstrap 4</h2> <p class="lead mb-0">Newly improved, and full of great utility classes, Bootstrap 4 is leading the way in mobile responsive web development! All of the themes are now using Bootstrap 4!</p> </div> </div> how to achieve this ? -
Refresh <div> element in a Django html template
How can I refresh an element within a Django HTML template Example <div class="container" id="myForm"> <form action="/cgi-bin/hello_get.cgi" method="get"> Fill the Detail: <br/> <textarea rows="5" cols="50" name="description">{{ bar_codes }} </textarea> <input type="submit" value="submit"/> </form> </div> I have JavaScript code that tries to refresh the div element with id myform. <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'detect_barcodes' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#myForm').append(response); append_increment += 10; }); }, 10000) </script> the variable bar_codes data gets being updated contantly. The data is not from an api but from a barcode scanner. This is the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False bar_codes = stream.used_codes print(bar_codes) return render(request, 'detect_barcodes/detect.html', context={'bar_codes': bar_codes, 'cam_status': status}) This is the url.py file urlpatterns = [ path('', views.detect, name='detect_barcodes'), path('camera_feed', views.camera_feed, name='camera_feed'), ] -
How to sort and search a time field in 12 format? DRF
I have two fields of type time in postgresql, which saves these values in 24 format (03:30 PM would save 15:30:00). How can I run a search with a time in format 12 and match it with its equivalent in format 24? How can I order these fields in 12 format? the fields are 'ho_inicio' and 'ho_fin'. My Viewset (I override the list method to search regardless of accents): class HorasEscolaresViewSet(ListModelPagination, viewsets.ModelViewSet): queryset = TbledcHora.objects.all() serializer_class = HorasEscolaresSerializer filter_backends = [DjangoFilterBackend, AliasedOrderingFilter] filterset_class = HorasEscolaresFilter search_fields = ['id_nivel_academico__nb_nivel_academico', 'nu_hora'] filterset_fields = ['id_nivel_academico', 'in_status'] ordering_fields=('id_nivel_academico', 'nu_hora', 'ho_inicio', 'ho_fin') ordering= 'id_nivel_academico' renderer_classes = (EmberJSONRenderer, ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if "search" in request.GET: if request.GET['search'] != '': q_list = [] q_list.append(Q(id_nivel_academico__nb_nivel_academico__unaccent__icontains=request.GET['search'])) queryset = queryset.filter(reduce(operator.or_, q_list)) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many = True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) My serializer: class HorasEscolaresSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] ho_inicio = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) ho_fin = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) class Meta: model = TbledcHora fields = '__all__' depth = 1 -
Why my user model is not saving even after the code is running successfully
I want to create a social media web app. I am currently working on the signup functionality Please help me find why my user model is not saving My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser import string import random # Create your models here. def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if ProfileUser.objects.filter(user_name=code).count() == 0: break return code class ProfileUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name = models.SlugField( unique=True, max_length=30, default=generate_unique_code) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] My SignUp View class signUpView(APIView): def get(self, request, format=None): try: user_name = request.GET.get("name") password = request.GET.get("password") email = request.GET.get("email") first_name = request.GET.get("first_name") last_name = request.GET.get("last_name") except Exception as e: print(e) return Response({"Invalid Data": "Not Enough Data"}, status=status.HTTP_206_PARTIAL_CONTENT) user = ProfileUser(email=email, user_name=user_name, first_name=first_name, last_name=last_name, password=password) user.save() return Response({"User Created": { "name": user_name, "email": email, "password": password }}, status=status.HTTP_201_CREATED) I am a beginner in Django -
Django DRF / JS - React Notifications API
I am working on a browser extension with a Django DRF backend and currently JS frontend ( working to convert it to React ). What I am trying to achieve is when a user clicks a buttons to trigger the Notification API for a set of users. Reading about this I have found some solutions: Websockets - currently the API is WSGI, seen that in order to add ASGI I need to change pretty much the entire foundation of my app or can I just hook up a different module that can talk to WSGI side? Sorry not very confident that I understand how this actually some clarification would be awesome. Also if for example you have 100 users with their channels open to the server how would that impact performace? The Super Hacky way - have an ajax/axios request that runs every 2 min or so and checks for DB changes, if true create the notification object. Again if you have 100 users pining the server constantly I assume performance will take a big hit Cron Job - would something like this work? Could also have a signal, post_save do something but I am not sure how I can … -
How to convert x-www-form-urlencoded to json with Python (Django)
From api i recive x-www-form-urlencoded data. data = 'leads%5Bstatus%5D%5B0%5D%5Bid%5D=29078079' when i try to convert it with urllib.parse.parse_qs or urllib.parse.unquote i got a dict like { "leads[status][0][id]": [ "29078079" ] } how can i convert it to normal json or dict ? like this { "leads": [ "id": "29078079" ] } -
Django Rest Framework Error: Unsupported Media Type: 415
Clicking on the like buttons is throwing the following error: Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) The code is supposed to submit the like action, retrieve the like counts and return the new serialized data. After doing some debugging on chrome, it looks like there is something wrong in the request header as when I inserted a print statement as the first line to the view function, it was never printed on the console, which indicates the error happens before the code makes it to the backend. But, I have set all the required headers, to the best of my knowledge. Searching online did not help either. So, here I am. Here is the Vanilla JavaScript code: function handleLikeButtons(){ let likeButtonsEls = document.querySelectorAll("[id^='likeBtn-']") likeButtonsEls.forEach( (likeBtn) => { likeBtn.addEventListener( 'click', event => { event.preventDefault(); // Submit the like const method = "POST" const url = likeBtn.getAttribute("data-like-endpoint") const headerOptions = "json" const commentId = likeBtn.getAttribute("data-comment-id") const data = JSON.stringify({"id": commentId, "action": "like"}) // createXHRRequest(method, url, data, updateLikeCount, commentId, headerOptions) createXHRRequest(method, url, data, null, commentId, headerOptions) }) }) } function createXHRRequest(method, url, data=null, callbackFn, extraData = null, headerOptions = null){ const xhr = new … -
Incorrect dispatching of url
When I use the configuration below of urls.py, I can see all the API response correctly. path('blog-tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), ])), But if I use this configuration: path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), path('tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), ])), I can't see the response from BlogTagAPIView and BlogTagDetailsAPIView and instead I see this message: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Why happen this? -
Why response is None testing view using RequestFactory()?
I am trying to test my view using RequestFactory(). However, calling this view in the test responded as None: View def add_to_basket(request): cart = Cart(request) if request.POST.get('action') == 'post': # GETS game DATA FROM AJAX REQUEST game_id = request.POST.get('gameId') game_qty = int(request.POST.get('gameQty')) # check if game exists try: game = Game.objects.get(pk=game_id) except Game.DoesNotExist: return JsonResponse({'message': 'Game not found'}) Test setUp def setUp(self) -> None: # request factory self.factory = RequestFactory() self.middleware = SessionMiddleware() Test itself def test_add_to_basket(self): # set sessions middleware request = self.factory.get(reverse('order:add-to-cart')) self.middleware.process_request(request) request.session.save() # request.user = self.test_user response = add_to_basket(request) print(response.status_code) print(response.content) Printing response outputs None - though apart test, view is working as expected. What could cause this? -
How to download a archive using django response?
I want to download the archive after i created. The code is bellow: def downloadArchive(room, catalog): test = RoomTest.objects.get(idRoom=room) zip_name = room.name + "_" + token_urlsafe(5) + '.zip' zip_path = 'media/zipFiles/' + zip_name if test.OLD_Archive != '' and os.path.exists(test.OLD_Archive): # remove old file. os.remove(test.OLD_Archive) with ZipFile(zip_path, 'w') as zipObj: for student in catalog: zipObj.write('media/' + str(student.file), student.studentFullName() + os.path.splitext('media/' + str(student.file))[1]) test.OLD_Archive = zip_path test.save() response = HttpResponse(zipObj) response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename=' + zip_name return response Every time i try to download, got error "The archive is either in unknown format or damaged". I think the route is broken. Any ideas how can i check the response route? Btw: if i download the archive manually (after archive), it's working fine. -
Redirect in django to diferents objects
Well I've a trick question (for me at least). I want to redirect to 'clients_update' if client doesn't have adresse field complete or redirect to 'client_info' if field adresse is complete. In booth cases the redirect will be done after boolean field 'valide' in class ContactValidation change to 'True'. models.py class Contact(models.Model): id = models.BigAutoField(primary_key=True) RECLAMATION = 'Reclamation' RDV = 'Marcation de Rdv' MOTIF = [ (RECLAMATION, 'Reclamation'), (RDV, 'Marcation de Rdv') ] motif_contact = models.CharField( max_length=40, choices=MOTIF, default=RDV, ) categorie = models.CharField(default=None, max_length=40) type_client = models.CharField(default=None, max_length=40) date_debut = models.DateTimeField(default=None) date_fin = models.DateTimeField(default=None) description_contact = models.TextField(max_length=1000) intervenants = models.ForeignKey(User, on_delete=models.CASCADE) client_contact = models.ForeignKey(Clients, on_delete=models.CASCADE, default=None) class Meta: verbose_name = 'contact' def __str__(self): return self.motif_contact class ContactValidation(models.Model): contact_validation = models.OneToOneField(Contact, on_delete=models.CASCADE, default=False, primary_key=True, parent_link=True) valide = models.BooleanField(default=False, null=True) def creation_contact (sender, instance, created, **kwargs): if created: ContactValidation.objects.create(contact_validation = instance) signals.post_save.connect(creation_contact, sender=Contact, weak=False, dispatch_uid='models.creation_contact') views.py def validation_contact(request): validation = Contact.objects.all() confirmer = ContactValidation.objects.all() context = { 'validation' : validation, 'confirmer': confirmer } return render(request, 'validation_attente.html', context) @login_required(login_url='login') def validation_confirmation(request, pk): form_validation = ContactValidationForm() contact_validation = get_object_or_404(Contact, pk=pk) if request.method == 'POST': form_validation = ContactValidationForm(request.POST or None) if form_validation.is_valid(): newconfirmation = form_validation.save(commit=False) newconfirmation.contact_validation = contact_validation newconfirmation.save() return redirect('client_update', pk=pk) else: form_validation = … -
How can i upload multiple files with base64 in Django Rest Framework?
I started learning DRF and I'm trying to clone Twitter on VueJs to improve myself. On the VueJs side, I use FileReader for file upload and send the base64 code of the uploaded images to DRF when the form is submitted. On the DRF side, I convert these base64 codes to ContentFile, but at the end I get the errors I mentioned below. {'files': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ContentFile.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ContentFile.', code='invalid')]}]} Internal Server Error: /api/add-tweet/ Traceback (most recent call last): File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\utils\encoders.py", line 50, in default return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte How can I … -
Deploying self-hosted Django dynamic website
So here's the thing: I have a Django app and I want to self host it (LAMP). Superficially, the dynamic website receives images, a OCR process is made and the results are returned to the client. The app could be accessed on average by 5 people at the time (to start with). The memory use could amount to 500 MB per client but it is erased afterwards (I'm not storing data whatsoever after the client has received the website output). So here is one of my doubts: I have some Compaq towers without using (processor: AMD Athlon X2 Dual-Core 7550. Memory: 2GB. Hard-Drive: 250 GB). Are there any restrictions towards installing Apache web server and deploying a dynamic website in desktop machines (besides the speed given by processors such as the Intel Xeon Platinum)? For example, could this tower receive requests from 5 different clients at the same time or this can't be done by a desktop processor? Or should I expect the tower overheating and the dynamic website being really slow? ---- I'm thinking about recycling and saving some money at the cost of a slower website (not extremely low I hope). Any recommendations about what Linux distribution to … -
Django 3 - null value in column "x" of relation
I'm struggling with the django rest project. I want to have some data in my database visible only for current logged in user. I did it by using my serializer and filtering - it's working. The next step is to add data to the database. My purpose is to add data only by admin user, so I have added my custom permission class: permission_classes = (IsAdminOrReadOnly,). Admin also has to have the possibility to specify used owned the data. It's working when I'm using django admin panel. And finally I want to post the data e.g: { "unix": 0, "user": "example@email.com" } Based on the email - I want to specify the user and assign posted data to the user. I have some idea how to resolve this but right now I'm struggling with the error: django.db.utils.IntegrityError: null value in column "user_id" of relation "rest_userstats" violates not-null constraint But did not find the solution yet I did prepare some model class: models.py class UserStats(models.Model): user = models.ForeignKey(get_user_model(), related_name='statistics', on_delete=models.CASCADE, null=True) user_email = models.EmailField() unix = models.IntegerField() serializers.py class UserStatsSerializer(serializers.ModelSerializer): class Meta: model = UserStats fields = ( 'unix', 'user_email', ) views.py class UserStatsViewSet(viewsets.ModelViewSet): serializer_class = UserStatsSerializer queryset = UserStats.objects.all() permission_classes … -
Django Make user to superuser on the frontend
I want to allow an admin/superuser to set already created users to be also a superuser. How would I go about this? I am new to Django. There is a separate user editing page and I want to add a button that would by clicking it change the is_superuser to True.