Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle multiple lists with get_or_create in python?
At my Django application, I have a celery task that imports objects from an S3 Bucket. To make sure that I don't import objects twice, I use get_or_create, please also see the corosponding code: ... for key in keys: files_obj, created = Files.objects.get_or_create(file_path=key, defaults={'file_name': Path(key).name, 'libera_backend': resource_object}) if created: files_obj_uuids.append(files_obj.pk) resource_objects.append(resource_object.pk) if not files_obj_uuids and not resource_objects: print("No new objects found, everything already imported.") else: print(f'{len(files_obj_uuids)} new objects found. Importing now!') # Building-up task-group try: group([extract_descriptors.s(resource_object, key, files_obj_uuid) for (resource_object, key, files_obj_uuid) in zip(resource_objects, keys, files_obj_uuids)]).delay() return "Import jobs started" As you can see, I first fetch all objects (keys), then I check if the object already exists at the Database using get_or_create. If not I append files_obj and resource_object each to a seperate list. Later on I build a group task where I pass over resource_object, key and files_obj_uuid. At the extract_descriptors tasks I call with these parameters, the actuall error occours: django.db.utils.IntegrityError: (1062, "Duplicate entry 'some_uri/some_file_123' for key 'App_files_descriptor_080cec4f_uniq'") please also see the corosponding code: ... if json_isvalid: try: Files.objects.filter(pk=files_obj).update(descriptor=strip_descriptor_url_scheme(descriptor)) To get a better understanding please dont focus on the "descriptor" here. Its a unique helper field I need for a headless celery tasks that runs in the … -
Save many-to-many relationship after use the add() method on the field to add a record
I have models Book and I want to save new record this book after every update information about this book (duplicate information). It works good, but I don't know how to store many-to-many relationship. Wherein, I want that main book don't save in database, only duplicate information in database models.py class Book(models.Model): slug = models.SlugField(max_length=255) title = models.CharField(max_length=255) author = models.ForeignKey( "Author", on_delete=models.SET_NULL, null=True, blank=True, related_name="author_book", ) abstract = models.TextField() coauthor_book = models.ManyToManyField("Author", blank=True, related_name="coauthor_book") subject = ManyToManyField("Subject") forms.py class BookForm(forms.ModelForm): class Meta: model = Article fields = "__all__" views.py class BookUpdateView(UpdateView): model = Book form_class = BookForm template_name = "book/book_update.html" def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.editor = self.request.user coauthors = obj.coauthor_book subjects = obj.subject draft = Book.objects.create( title=obj.title, author=obj.author, abstract=obj.abstract, slug=obj.slug, ) draft.save() # My triying. But It doesn't work for coauthor in coauthors.all(): draft.coauthor_book.add(coauthor) for subject in subjects.all(): draft.subject.add(subject) return redirect("book", obj.slug) return self.render_to_response({"form": form}) -
Django not saving datetime from input
If I set USE_TZ = True I get an error "DateTimeField received a naive datetime while time zone support is active" . After changing it to False when I try to submit from my pc it works but submitting from other devices(my phone) doesn't work. Can anyone help? Template : <label class="form-label">Submission Ends:</label><input type="datetime-local" id="lastdate" name="lastdate" required> views : lastdate= request.POST['lastdate'] homework= Homework(code=code,title=title,description=description,lastdate=lastdate) homework.save() settings.py : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = False USE_TZ = False -
im trying to add a response with the full body of the car model but want to only adjust 1 field in the same view which is the car.collection
enter code here basically i want to add 2 functions .. add to collection, remove from collection , while having the full body of the car object in response but only adjust the collection relation field serializers class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['id', 'model', 'maker', 'release_year', 'vin', 'owner', 'collection'] def update(self, instance, validated_data): instance.collection = validated_data.get('collection', instance.collection) return instance class CarCollectionSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['id', 'collection'] class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ['id', 'name', 'created_at'] models class Collection(models.Model): name = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Car(models.Model): model = models.CharField(max_length=40) maker = models.CharField(max_length=60) release_year = models.IntegerField() vin = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE, default=None) collection = models.ManyToManyField(Collection) def __str__(self): return f"{self.model}" views class CarViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving cars. """ queryset = Car.objects.all() serializer_class = CarSerializer permission_classes = [IsAuthenticated, IsCarOwner] filter_backends = (filters.DjangoFilterBackend,) filter_class = CarFilter filter_fields = ('maker', 'release_year', 'vin') ordering_fields = 'release_year' @action(detail=True, methods=['GET', 'Put']) def update_car_collection(self, request, pk=None, format=None): car = Car.objects.get(pk=pk) collection = Collection.objects.get(pk=pk) serializer = CarCollectionSerializer(car, request.data) if serializer.is_valid(): serializer.save() car.collection = serializer.data.get(collection, car.collection) return Response(serializer.data) -
How to get the value of a form in html to django
<form action="{% url 'search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> How can I get the value of q to views.py def search(request): return render(request, "encyclopedia/search.html") Should I make it a post request instead of a get and then take the value. Help me plz -
How can I make my form page resposive design in Django?
I have a form page with Django 1.11.10. I want to desing it responsive for all screen sizes. In phones and tabletes I want to not need to zoom in. Here is my html : {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <div class="form-body"> <div class="row"> <div class="form-holder"> <div class="form-content"> <div class="form-items"> <div class="row"> <div class="col-xs-11"> <h1>WARRANTY REGISTRATION</h1> <br><br> <form class="requires-validation" method="POST" novalidate> {% csrf_token %} {{form.as_p}} <div class="form-button"> <button id="submit" type="submit" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to validate foreign key with APIView
I'm learning django rest framework at school and now I'm on a internship project, I have some doubts using API base View. I want to do a POST in a endpoint and validate if the foreign key exists or not. My models: # TABELA DOS FORNECEDORES class Fornecedor(models.Model): nome = models.CharField(max_length=100, null=False, blank=False) endereco = models.CharField(max_length=100, null=False, blank=False) codigo_postal = models.CharField(max_length=8, null=False, blank=False) cidade = models.CharField(max_length=50, null=False, blank=False) nif = models.IntegerField( null=False, blank=False, unique=True, validators=[ RegexValidator(r"[1-9]\d*"), MinLengthValidator(9), MaxLengthValidator(9), MaxValueValidator(999999999), MinValueValidator(1), ], ) email = models.EmailField(max_length=50, null=False, blank=False) data_registo = models.DateTimeField(auto_now_add=True) data_ultimo_login = models.DateTimeField(auto_now=True) ativo = models.BooleanField(default=True, null=False, blank=False) def __str__(self): return self.nome # TABELA DAS MARCAS class Marca(models.Model): nome = models.CharField(max_length=55, null=False, blank=False) fornecedor = models.ForeignKey( Fornecedor, on_delete=models.CASCADE, null=False, blank=False ) def __str__(self): return self.nome My serializers class FornecedorSerializer(serializers.ModelSerializer): class Meta: model = Fornecedor fields = "__all__" class MarcaSerializer(serializers.ModelSerializer): class Meta: model = Marca fields = "__all__" My views class FornecedorPOST(APIView): @swagger_auto_schema( operation_summary="Criar um Fornecedor", operation_description="Criar um novo Fornecedor", request_body=FornecedorSerializer, responses={ status.HTTP_201_CREATED: response_201(FornecedorSerializer), status.HTTP_400_BAD_REQUEST: response_400(FornecedorSerializer), }, ) def post(self, request, format=None): fornecedor = FornecedorSerializer(data=request.data) if fornecedor.is_valid(): fornecedor.save() return Response(fornecedor.data, status=status.HTTP_201_CREATED) return Response(fornecedor.errors, status=status.HTTP_400_BAD_REQUEST) class MarcaPOST(APIView): @swagger_auto_schema( operation_summary="Criar uma marca", operation_description="Criar uma nova marca", request_body=MarcaSerializer, responses={ status.HTTP_201_CREATED: response_201(MarcaSerializer), status.HTTP_400_BAD_REQUEST: response_400(MarcaSerializer), }, … -
Got stuck in 'grid-template-columns' in CSS
I am currently learning Django and got stuck. I have created 3 divs inside of an home container and written this CSS code for the home container -> <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> I have created 'grid-template-columns: 1fr 3fr 1fr;' but I am not getting a column for the third div(i.e. 1fr). The third div's content is coming below the second div. Here is the whole source code. -> {% extends 'main.html' %} {% block content %} <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> <div class="home-container"> <div> <h3>Browse Topics</h3> <hr> <a href="{% url 'home' %}">All</a> {% for topic in topics %} <div> <a href="{% url 'home' %}?q={{topic.name}} ">{{topic.name}}</a> </div> {% endfor %} </div> <div> {% if room_count != 0 %} <h5>{{room_count}} rooms available.</h5> {% else %} <h5>No rooms available.</h5> {% endif %} <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> {% if request.user == room.host %} <a href="{% url 'update-room' room.id %}">Edit this room</a> <a href="{% url 'delete-room' room.id %}">Delete this room</a> {% endif %} </div> <div> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> <div> … -
Django: Update a value in html page without refreshing the page
I have a Rest API which I receive data every 10 seconds. I receive the data with time information that when the data sent. So, user should see the soonest data on the page. That code would work but that also wont update the data without a refresh: def get_datas(request): data = //find the soonest data return render(request, 'page.html', {'data': data}) What is the best solution for this? -
Problem fetching an equation from Excel Django
I have an excel file with a simple math equation In cell C1 it is A1 + B1 and I want to fetch the result of C1 in Django but it returns me nan...... is there a way to solve this problem? I use the pandas library! -
Django RQ ModuleNotFoundError xxx is not a package
I'm using django rq for some long running task, which I would like to provide some feedback about its progress. I hence created a function which is enqueued as a new task and set some model's attribute and save them. Here is a simplified view: class Status(models.Model): progress_a = models.PositiveIntegerField(default=0) class MyObject(models.Model): status = models.OneToOneField(Status) @django_rq.job('low-short') def set_status(self, progress_name, progress): setattr(self.status, progress_name, progress) self.status.save() def set_status_a(self, progress): self.set_status.delay(self=self, progress_name="progress_a", progress=progress) @django_rq.job('default') def long_running_job(): my_instance.set_status_a(100) Now, executing this give me the following output : 2022-05-16 15:50:03 app-85c8459c79-mrkhg rq.worker[1] INFO low-short: api.models.MyObject.set_status(progress=0, progress_name='progress_a', self=<MyObject: MyObject object (129)>) (c13480ca-a25b-4463-af9a-a0a0dd67de61) 2022-05-16 15:50:03 app-85c8459c79-mrkhg root[41] WARNING Import error for 'api.models.MyObject' Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/rq/utils.py", line 141, in import_attribute module = importlib.import_module(module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 981, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api.models.MyObject'; 'api.models' is not a package api is a package api.models a module models.MyObject a class. I don't get why it doesn't work. What am I doing wrong ? long_running_job starts as a job flawlessly. Note: when removing self=self, it complains about missing self. -
Django cache doesn't invalidate on change
A cached page should be invalidated when something changes at the underlying resource. Django implements "site-wide" caching and I used this guide to setup my caching infrastructure (locally to test for now). CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" CACHE_TTL = 60 * 60 * 1 CACHE_MIDDLEWARE_SECONDS = CACHE_TTL When I run my tests now, it works too well, as all tests fail, which change information in the database. Do I have to manually add a flag for cache invalidation? Should this even work (or are my settings wrong)? I saw this question, but in my case I don't use any decorators, but the side wide caching. Nevertheless I tested using the vary_on_headers('Authorisation',) which didn't change the test results. -
The data/content isn't getting displayed. Can anyone please let me know any necessary changes to render the data?
Models.py class Question(models.Model): # id = models.AutoField(primary_key=True) question=models.CharField(max_length=600) option1=models.CharField(max_length=200, default=None) option2=models.CharField(max_length=200, default=None) option3=models.CharField(max_length=200, default=None) option4=models.CharField(max_length=200, default=None) views.py def Practice_all(request): practice = Question.objects.all() context={ 'question_list': practice } return render(request, 'practice.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("practice/", views.Practice_all, name="practice"), ] practice.html {% extends 'base.html' %} {% block content %} {% for data in question_list %} <li> {{ data.option1 }} </li> <li> {{ data.option2 }} </li> <li> {{ data.option3 }} </li> {% endfor %} {% endblock %} These are the Django files that I am using, the server runs perfectly but won't display anything, not even any errors, just blank. Any suggestions? -
Handling one template with multiple Django function
I have a template which contains feature to "fetch" the details and "edit" using Bootstrap Modal, from a API. I created 2 functions, one to display data and one to edit views.py def add_bom(request): ... context = {"sku_object": sku_object} return render(request, 'BOM/add-bom.html', context=context) def edit_bom_activity(request, bomNo, activity): ... context = {"filter_activity": filter_activity} return render(request, 'BOM/add-bom.html', context=context) Urls.py path('add_bom/', views.add_bom, name="add_bom"), path('edit_bom_activity/<str:bomNo>/<str:activity>/', views.edit_bom_activity, name="edit_bom_activity"), Since the template are same it is not somehow entering in edit_bom_activity function. Alternatively I tried to pass parameter in add_bom/ as path('add_bom/<str:bomNo>/<str:activity>/', views.add_bom, {'bomNo': None, 'activity': None}, name="add_bom"), But still I couldnt get the success. Is there a way on how to allow single template with multiple functions. -
How to stop Django inserting null columns for NoSql DB
I user django and mongodb for my project. I want to stop django orm from inserting null columns to DB. Here is some of my django files: # models.py from django.db import models class Ad(models.Model): user_id = models.IntegerField() title = models.CharField(max_length=100) description = models.CharField(max_length=500) fee = models.CharField(max_length=20) phone = models.CharField(max_length=10) location = models.CharField(max_length=50, default="") category = models.CharField(max_length=25) est_rooms = models.CharField(max_length=10) est_area = models.CharField(max_length=10) est_age = models.CharField(max_length=10) # views.py a = Ad.objects.create(user_id=request.user.id, title=title, description=description, fee=fee, phone=phone, location=location, category=category, est_rooms=est_rooms, est_age=None) a.save() For example, if I insert as above although I did not give anything for est_area, it inserts est_area="", but I don't want this. Instead, I want django orm not to insert est_area property. Could anyone help me? -
WordPress blog in Subdirectory of Django website on a CPanel Host
As I read articles and questions online, I believe it is possible; My main question is how to achieve this goal? I have Django Website with some urls on my domain (I use Setup Python App plugin on CPanel). I can simply achieve this using a subdomain, but I want to run my WordPress blog on a subdirectory, but every url that is not registered in urls.py will raise an error. What's the best way to reach this goal? What are the steps that I need to take to reach it? I will be more than greatful if you point me towards the right direction. Thanks in advance. -
only first row executing in the loop inside the array in python
I'm trying to loop through all the JSON inside the array, after the first row loop ends it's just iterated only the first row inside the array and then loop ends. How could I able to loop through all the rows inside the array here, what I tried views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: auditorid =ran.get('AuditorId') ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action = ran.get('Action') subfunction = ran.get('AuditSubFunction') region = ran.get('AuditRegion') Qstans = str(qid)+'|'+ answer+'&&' cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@agents=%s,@supervisor=%s,@ticketid=%s,@Qstans=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s, @Comments =%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,agents,supervisor,ticketid, Qstans,sid, TicketType, TypeSelected, Comments, action, subfunction,region)) result_st = cursor.fetchall() for row in result_st: return Response({0:row[0]}) here is the payload -
How to load data outside Django view?
If i have some Django views like 'first', 'second' and so on, and i want to load some data outside this views but use it inside views. Here is an example to understand my idea. #function execution time is long, that is why i want to laod it only once when run programm. fetched_data_from_postgres = some function which load data from postgres and return list with postgres data def first(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("first VIEW") def second(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("secondVIEW") def third(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("third VIEW") this aproach working well when i run my django project like this python manage.py runserver but when i run with gunicorn or wsgi when i can specify workers count then when worker changes then this variable is lost and need to refresh page to get this previous worker to get that data. It's ridiculous. Or maybe there is some other aproach to do this job? -
how do i icrement a filed on a model name:''order count' when an another model object is created in django
I have two models Customer and Order and I want to make 3 fields that are updating when an Order object is created. the fields are Order_Count:--, First_Order:order_date, Last_Order: order_date how do I do this? Customer model: class Customer(models.Model): GENDER_CHOICES = ( ('MALE', 'male'), ('FEMALE', 'female'), ('OTHER', 'other') ) SOURCES = ( ('android', 'Android'), ('ios', 'IOS') ) customer = models.ForeignKey(User, related_name='customer', on_delete=models.CASCADE) image = models.ImageField(upload_to='customer_images/', null=True, blank=True) social_image_url = models.TextField(null=True, blank=True) dob = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, blank=True) lati = models.CharField(max_length=100, null=True, blank=True) long = models.CharField(max_length=100, null=True, blank=True) fb_id = models.CharField(max_length=50, null=True, blank=True) google_id = models.CharField(max_length=50, null=True, blank=True) gapple_sub = models.CharField(max_length=50, null=True, blank=True) notifications = models.BooleanField(default=True) payment_token = models.CharField(max_length=200, null=True, blank=True) source = models.CharField(max_length=10, choices=SOURCES, null=True, blank=True) a_v = models.CharField(max_length=20, null=True, blank=True) def __str__(self): # return "%s" % self.customer.get_full_name() return f'{self.id} - {self.customer.get_full_name()}' and Order model: class Customer(models.Model): GENDER_CHOICES = ( ('MALE', 'male'), ('FEMALE', 'female'), ('OTHER', 'other') ) SOURCES = ( ('android', 'Android'), ('ios', 'IOS') ) customer = models.ForeignKey(User, related_name='customer', on_delete=models.CASCADE) image = models.ImageField(upload_to='customer_images/', null=True, blank=True) social_image_url = models.TextField(null=True, blank=True) dob = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, blank=True) lati = models.CharField(max_length=100, null=True, blank=True) long = models.CharField(max_length=100, null=True, blank=True) fb_id = models.CharField(max_length=50, null=True, blank=True) google_id = … -
Django: ajax not returning or sending any data in django
i am creating a simple like button with ajax, i have followed the tutorial but it seems, that i am missing something, i am not getting any error either in the console in my django terminal but when i click the button no data get sent, evrything just remains the same way, and this is not what i am expecting, i know i am missing something somewhere and i cannot really tell where this error is coming from. views.py @login_required def like(request): if request.POST.get("action") == 'post': result = "" id = int(request.POST.get('courseid')) course = get_object_or_404(Course, id=id) if course.like.filter(id=request.user.id).exists(): course.like.remove(request.user) course.like_count -= 1 result = course.like_count course.save() else: course.like.add(request.user) course.like_count += 1 result = course.like_count course.save() return JsonResponse({'result': result}) urls.py NOTE:I don't know if i need a slug in this url path path('like/', views.like, name="like"), base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> course-detail.html <li><button id="like-button" value="{{course.id}}">like</button><span id="like-count">{{course.llke_count}}</span></li> <script type="text/javascript"> $(document).on("click", '#like-button', function(e){ e.preventDefault() $.ajax({ type: 'POST', url: '{% url 'course:like' course.slug %}', data: { courseid: $('#like-button').val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), action: 'post' }, success: function(json){ document.getElementById("like-count").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) console.log(xhr) console.log(errmsg) console.log(err) }) }) </script> this is all the code i have written for the functionality, if there is any other … -
Socket connection don't work properly on Heroku
I'm trying to get some messages from a server using socket in my Django web app. This works correctly in local but don't works when i deploy it on Heroku. The problem seems to be that I cannot receive all responses from the server in an adequate time. Procfile: web: gunicorn app.wsgi --log-file - The client connection I built has this structure. def connection(self, hostname: str, port: int, messages: list) -> str: s: socket.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock: ssl.SSLSocket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1_2) sock.connect((hostname, port)) sock.settimeout(1) for message in messages: sock.sendall(message.encode()) data: str = '' while True: try: # get response from server resp = sock.recv(1024) data += resp.decode("UTF-8") if resp == b'': data = None break except socket.timeout: # expired time to receive data break # close connection sock.close() return data -
Django uploaded file validation leads to "InMemoryUploadedFile is not supported"
I have a template where the user can choose and upload a file from their computer. The file is eventually uploaded to S3, but is first validated using custom validation to check some contents of the file. For checking the contents, the script reads the lines of the file in forms.py: from io import TextIOWrapper class UploadForm(forms.ModelForm): class Meta: model = MyModel fields = ('myfilefield',) def clean_myfilefield(self): file = self.cleaned_data['myfilefield'] read_file = TextIOWrapper(self.cleaned_data.get('myfilefield'), encoding='ASCII') headerCounter = 0 for line in read_file: if ">" in line: headerCounter += 1 if headerCounter > 1: error = "Custom error message 1" raise ValidationError(error) if headerCounter == 0: error = "Custom error message 2" raise ValidationError(error) return file The validation messages are correctly displayed, but if the file passes validation I get this error message (assuming myfile.txt is the uploaded file): Input myfile.txt of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported. The validation and uploading works fine if I leave out the TextIOWrapper part and the error checks. So I guess there's something about reading the file that converts it to a InMemoryUploadedFile, which is not compatible with uploading the file? I tried finding solutions for "converting" the InMemoryUploadedFile back to a "regular" (?) file, … -
How to use order_by when using Django group_by, take out all fields
I used Django-orm,postgresql, Is it possible to query by group_by and order_by? this table | id | b_id | others | | 1 | 2 | hh | | 2 | 2 | hhh | | 3 | 6 | h | | 4 | 7 | hi | | 5 | 7 | i | I want the query result to be like this | id | b_id | others | | 1 | 2 | hh | | 3 | 6 | h | | 4 | 7 | hi | or | id | b_id | others | | 4 | 7 | hi | | 3 | 6 | h | | 1 | 2 | hh | I tried Table.objects.annotate(count=Count('b_id')).values('b_id', 'id', 'others') Table.objects.values('b_id', 'id', 'others').annotate(count=Count('b_id')) Table.objects.extra(order_by=['id']).values('b_id','id', 'others') -
how to connect to the django testing databse correctrly?
I have a problem with django testing database. I use setUp method like this: def setUp(self): super().setUp() self.obj1 = MyModel.objects.create(name="name1") self.obj2 = MyModel.objects.create(name="name2") self.obj3 = MyModel.objects.create(name="name3") But when I try to connect to testing database: import psycopg2 from psycopg2 import sql db_uri = settings.DB_URI.replace("/db_name", "/test_db_name") con = psycopg2.connect(db_uri) cur = con.cursor() and execute: query = sql.SQL( "select * from {table};" ).format( table=sql.Identifier("mymodel_table_name"), ) cur.execute(query) print('result', cur.fetchall()) In result I see the empty list. BUT! If I insert something in testing database: query = sql.SQL( "insert into {table} (id, name) values ({id}, {name});" ).format( table=sql.Identifier("mymodel_table_name"), id=sql.Literal(some_id), name=sql.Literal(some_name), ) cur.execute(query) I see it in ORM, when I execute: MyModel.objects.all() My purpose is get in test_db_name all objects, which I insert in setUp method. Thank you for any help! -
How to show different menu on sidebar for each page in django?
I have 2 navigation bar, one is in the top and the second is in the side. In my top navbar, I have 3 different menu, namely "Dashboard", "Manage" and "Report". I want it to display different items in my sidebar when clicking one the menu in my top navbar. Something like this: In my "Dashboard" (the Dashboard in the top navbar will get highlighted) and will display the following on my sidebar: - dashboard-item-no1 - dashboard-item-no2 - dashboard-item-no3 In my "Manage" (the Manage in the top navbar will get highlighted) and will display the following on my sidebar: - manage-item-no1 - manage-item-no2 - manage-item-no3 In my "Report" (the Report in the top navbar will get highlighted) and will display the following on my sidebar: - report-item-no1 - report-item-no2 - report-item-no3 Can anyone please help me? I saw similar problem but it's in php and not django so I've been stuck with this problem for almost a week by now :'(