Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serve media files in development?
I have a problem when trying to display in a template a picture from my media file (for example a profil picture from an user). I have already looked at many topics, and everytime the answer is simply adding the line urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the urls.py file. But I already have it and it still doesn't work. Here are the relevant part of my files : urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('actualites.urls')), path('inscription/', include('inscription.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) views.py def home(request): return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()}) models.py class Plat(models.Model): titre = models.CharField(max_length = 100) date = models.DateField(default=timezone.now, verbose_name="Date de préparation") photo = models.ImageField(upload_to = "photos_plat/", blank = True) class Meta: verbose_name = "Plat" ordering = ['date'] def __str__(self): return self.titre You can see that the pictures are recorded in the photos_plat directory, which is a subdirectory of the media directory. the template : {% extends "base.html" %} {% block content %} <h2>Bienvenue !</h2> <p> Voici la liste des … -
Django formset dynamic add row to table
i have created a formset that is rendering in table and when i add a row the input box only is rendered in the first row and the second row is only the template code appearing. the table will be a form posted to a view function for Formset process to capture all the data in the added dynamic table with add row. HTML {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Dashboard - Brand</title> <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"> <link rel="stylesheet" href="{% static 'assets/css/Navigation-Clean.css' %}"> </head> <body id="page-top"> <div></div> <div> <nav class="navbar navbar-light navbar-expand-sm border rounded shadow-sm navigation-clean"> <div class="container"><a class="navbar-brand" href="#">Company Name</a><button data-toggle="collapse" data-target="#navcol-1" class="navbar-toggler"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navcol-1"> <ul class="nav navbar-nav ml-auto"> <li role="presentation" class="nav-item"><a class="nav-link active" href="#">My Startup</a></li> <li role="presentation" class="nav-item"><a class="nav-link" href="#">Campaigns</a></li> <li role="presentation" class="nav-item"><a class="nav-link" href="#">Guide</a></li> <li class="dropdown nav-item"><a data-toggle="dropdown" aria-expanded="false" class="dropdown-toggle nav-link" href="#">Account</a> <div role="menu" class="dropdown-menu"><a role="presentation" class="dropdown-item" href="#">Edit</a><a role="presentation" class="dropdown-item" href="#">Reset Password</a><a role="presentation" class="dropdown-item" href="#">Log Out</a></div> </li> </ul> </div> </div> </nav> </div> <div> <div class="container"> <div class="row"></div> </div> </div> <div> <div class="container"> <div class="row"> <div class="col-md-12" style="padding-top: 31px;"> <div class="card shadow mb-4" style="padding: 0;padding-top: 2;"> <form id="my-form" method="post"> … -
how do exclude field of method clean form's
i necessary remove one field of method clear of my form but he is already declared how required=False. but in the template it has the clean method error if i leave it empty ship = UnicodeField(max_length=61, label=_('user'), required=False) how do i do to field not show error? -
What does the class "Meta" do in this example ? And how does the Meta class work in general?
I am new to Django and would like to know, what the class "Meta" do in django and what does it do in my example below. from django import forms from django.contrib.auth.forms import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] -
Unable to set default form values in Django
I am trying to set default values for my form fields in my Django application, but nothing I do seemed to work. I am using Django 2.2.3. This is my code in views.py: def my_view(request, template_name="path/to/template"): form = MyForm(request.POST, initial={ 'field_one': field_one_default, 'field_two': field_two_default, }) try: if request.method == 'POST': if form.is_valid(): field_one = form.cleaned_data['field_one'] field_two = form.cleaned_data['field_two'] my_model.field_one = field_one my_model.field_two = field_two my_model.save() return redirect('redirected_page') return render(request, template_name, {'form': form}) return render(request, template_name, {'form': form}) except Http404 as e: return Http404("An error occurred.") This is my code in forms.py: class MyForm(forms.Form): field_one_choices = [ ('Choice One', 'Choice One'), ('Choice Two', 'Choice Two'), ('Choice Three', 'Choice Three'), ] field_one = forms.ChoiceField(choices=field_one_choices, required=True) field_two = forms.IntegerField( validators=[MaxValueValidator(100), MinValueValidator(1)], required=True ) And this is my code in the template: {% load fontawesome_5 %} {% load bootstrap4 %} <div class="container spacing-top"> <form method="post">{% csrf_token %} {% bootstrap_form form %} <input class="btn btn-info" type="submit" value="Save"> <a class="btn btn-secondary" href="{% url 'another_page_url' %}">Cancel</a> </form> </div> Though the default values does not show up when rendering the page, printing form.fields['field_one'].initial in the forms.py shows the default value that I am trying to set. I have also tried setting the default values in the forms.py, but … -
Shared test DB across Django TestCase
Intro I'm writing unit tests for a Django project where some DB entries are loaded from a file. It's expensive to parse the file and create all the entries. The application has different modules to tests, so I'm implementing one TestCase per module. Issue The modules rely on the data parsed from the file (ie. they need the same DB), but I can't afford re-setting up the DB for all the different TestCase, like here: class TestBehavior_A(TestCase): @classmethod def setUpClass(cls): super().setUpClass() expensive_db_init() class TestBehavior_B(TestCase): @classmethod def setUpClass(cls): super().setUpClass() expensive_db_init() class TestBehavior_C(TestCase): @classmethod def setUpClass(cls): super().setUpClass() expensive_db_init() Nor I can merge all my test cases in the the same class, otherwise it would be a mess. Ideally I would like to have one setup shared across all my tests cases (ie. call setUpClass only once) -
How do I implement bootstrap modal forms with django-crispy-forms, without page refresh
I have been trying to implement a form in a bootstrap modal, using django-crispy forms. I am using class based views. I know that I would require some Ajax, but I didn't understand all the examples I have been seeing. I tried django-bootstrap-modal-forms - this works with the modal, but sadly, it dosen't support bootstrap styling, and I couldn't find any way to add it. When I tried to add bootstrap sytling to django-bootstrap-modal-forms using bootstraps form class, form-control, the form dosen't submit, and gives no errors. So now, I want to fall back to django-crispy-forms. So my question is: How do I implement a bootstrap modal form with django-crispy-forms How do I implement validation with ajax, to avoid page reload - The errors should also have the same error styling as django-crispy-forms Also, how to I also implement a success message using an alert, when the object has been successfully added into the database. My code is shown below: my_template.html This currently contains the CSS classes for django-bootstrap-modal-forms. Check out https://pypi.org/project/django-bootstrap-modal-forms/ You can replace the text in the modal-body with {{ form | crispy }} to use django-crispy-forms <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create new … -
How to repeat django event occurrence period?
I have a model that gets the day and time of week when an event should always occur. Also, the number of days before the event that people will be able to attend. def validate_only_one(obj): model = obj.__class__ if model.objects.count() > 0 and obj.id != model.objects.get().id: raise ValidationError("Você só pode adicionar um evento") # You can add only one schedule class ModelPresenca(models.Model): DIAS = ( # The days are in Portuguese ('Domingo', 'Domingo'), ('Segunda', 'Segunda'), ('Terça', 'Terça'), ('Quarta', 'Quarta'), ('Quinta', 'Quinta'), ('Sexta', 'Sexta'), ('Sábado', 'Sábado'), ) dia = models.CharField('Dia da Pelada', max_length=10, help_text='Escolha o dia da pelada', choices=DIAS) # day of the event hora_pelada = models.TimeField('Horário da pelada (ex: 19:30)', help_text='Hora em que sua pelada é realizada') # hour of the event dias_antecedencia = models.PositiveIntegerField('Dias antecedência', default=1, validators=[MinValueValidator(1), MaxValueValidator(6)], help_text='Em quantos dias de antecência os peladeiros devem ' 'marcar presença') # numbers of days before event However, I don't know how to make this event repeat without requiring the user to add the same information every week. I'm thinking of the following algorithm: def period(request): event_data = ModelPresenca.objects.all() # I have always only one object hour_timefield = datetime.strptime(h.hora_pelada, '%H:%M') # TimeField to string day = event_data.dia # Day of the … -
Is there a way to disable Django Admin removing trailing spaces in TextField strings?
I am currently using Django 2.2.7 that runs with PostgreSQL 9.5.17. In my Django Admin I am filling some content of strings that are stored there to be accessible in an app. Some strings contain trailing spaces, ie, strings like Are you happy with us? (note the space at the end). I know it is not something desirable, but frontenders delivered it like this. In any case, the thing is that I sometimes try to store this data in a TextField: Are you happy with us? # ^ one space here But Django automagically converts it into: Are you happy with us? # ^ the space has disappeared! This makes strings useless, since we are looking for strings that are exactly the same, and a difference of space is enough to differ. To overcome this problem, I have to go to postgres and update manually with something like: UPDATE api_mymodelwithstrings SET text_en='Are you happy with us? ' where ... # ^ I have gone through Django documentation and could not find any reference to this being automatic. In fact, I found references to clean(), that can be used for this matter. In any case, my model does not have any … -
One object only in GET method in Dajngo Rest Framework
I have a list of all my objects when I use get method by api/movies in my api, and this is ok. I want also to get only one, specyfic object when use get method by api/movies/1 but now I still have a list of all my objects... What to change in my MoviesView or in urls? My views.py: class MoviesView(APIView): def get(self, request): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data) My appurls.py: urlpatterns = [ url('movies', MoviesView.as_view(), name="MoviesView"), ] And my project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("api.urls")), ] When I use routers everythig crushes... Could you help me? -
Matplotlib - 24h charts, how to add specific points at a point in time
The problem is that I need to get 2 charts, with 2 specific "workers", each worker has a specific time which it has started (time), and a specific duration where it has worked. I've gotten it to this point: But what I need is that both Charts at the time has full 24hours starting from 00:00:00 untill 23:59:59, and I need to be able to add a point to a specific time, and for it not to look as clustered at the time as it is, like maybe add it in groups? This is the code for my chart making func.: def makeChart(worker, titler): plt.figure(figsize=(18,5)) for worker in worker: plt.plot([worker.started.time().strftime("%H:%M:%S").__str__()], [worker.duration], 'r.') plt.annotate(worker.duration.__str__(), (worker.started.time().strftime("%H:%M:%S").__str__(), worker.duration + 2.5)) #plot([cipars pk.], [value]) #Laiks, Ilgums plt.gcf().autofmt_xdate() ylabel('length(sec)') xlabel('time') title(titler) buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type="Image/png" buffercontent=buffer.getvalue() buffercontent = base64.b64encode(buffercontent) #uri = 'data:image/png;base64,' + urllib.parse.quote(string) graphic = (buffercontent) pylab.close() return graphic -
Apache with Wsgi Module changes in source file does not get affected immediately
Apache with Wsgi Module changes in django app source file does not get affected immediately -
how can i save all the rows as dynamically to the database if i do like this all records are filled with same data
Blockquote it is my model codehere i am write to save all the rows in the form saved dynamically to the database but it stored into database with same data how can i store correct data to the database please help me.... def sales(request): global prod global hsn1 global c1 global e1 global d1 TOTAL_FORM_COUNT='TOTAL_FORM' INITIAL_FORM_COUNT='INITIAL_FORM' MIN_NUM_FORM_COUNT='MIN_NUM_COUNT' MAX_NUM_FORM_COUNT='MAX_NUM-FORMS' ORDERING_FIELD_NAME='ORDER' DELETION_FIELD_NAME='DELETE' DEFAULT_MIN_NUM=0 DEFAULT_MAX_NUM=100 saleformset=modelformset_factory(productsale,form=productsaleForm,can_delete=True) if request.method=="POST": data={ 'form-TOTAL_FORMS':'1', 'form-INITIAL_FORMS':'0', 'form-MAX_FORMS':'', } formset=saleformset(request.POST,request.FILES,data,productsale.objects.none()) if formset.is_valid(): pn = pname for f in formset: cd=f.cleaned_data sno=cd.get("s_no") p=cd.get("product") ptype=cd.get("product_type") a=cd.get("price") b=cd.get("quantity") date=cd.get("date") prods = product.objects.all() for pro in prods.filter(productname=p): produc = pro.productname hsn = pro.hsn c = pro.sgst d = pro.cgst e = pro.igst Blockquote it is my model codehere i am write to save all the rows in the form saved dynamically to the database but it stored into database with same data how can i store correct data to the database please help me.... Blockquote total = int(a)*int(b) f = int(c)+int(d)+int(e) g = (total)*(f/100) #tsgst = (total)*(c/100) #tcgst = (total)*(d/100) #tigst = (total)*(e/100) full_total = (total)+int(g) try: for sal in formset: #for s in sal: #z = request.POST.get('form-0-s_no') #y = request.POST.get('form-0-price') #q = request.POST.get('form-0-product') #k = request.POST.get('form-0-product_type') #r = request.POST.get('form-0-quantity') #l = request.POST.get('form-0-date') … -
Python static directory for apache deployment
My apache root directory is /Users/whitebear/CodingWorks/httproot/ and there are some projects not only django, laravel etc.. my apache setting is this. LoadFile "/Users/whitebear/anaconda3/lib/libpython3.7m.dylib" LoadModule wsgi_module "/Users/whitebear/anaconda3/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-darwin.so" WSGIScriptAlias /mypythonapp /Users/whitebear/CodingWorks/httproot/mypythonapp/mypythonapp/wsgi.py WSGIPythonHome /Users/whitebear/anaconda3 WSGIPythonPath /Users/whitebear/CodingWorks/httproot/mypythonapp <Directory /Users/whitebear/CodingWorks/httproot/mypythonapp> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /Users/whitebear/CodingWorks/httproot/mypythonapp/satic/ <Directory /Users/whitebear/CodingWorks/httproot/mypythonapp/static> Require all granted </Directory> then in this case I want to put the static file for mypythonapp here. httproot - mypythonapp - mypythonapp polls template static //here So, I do like this in settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "mypythonapp/static") and then, python manage.py collectstatic fils are gatheres under static directory. but when accessing localhost/mypythonapp/admin/ in html these link doesn't work <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css"> <link rel="stylesheet" type="text/css" href="/static/admin/css/dashboard.css"> There are files in /Users/whitebear/CodingWorks/httproot/mypythonapp/static/admin/css/base.css /Users/whitebear/CodingWorks/httproot/mypythonapp/static/admin/css/dashboard.css -
How to connect a simple externel html file with django channels 2.0.Getting error Invalid token or unexpected token
I am learning django channels, I have implemented simple chat app using django channels,I have html file in which I have implemented websocket methods and from that I was connecting it with django consumers.Everything is working properly. Now I want to send the same connection from other html file not present in django project to consumers in django,when I send the request from outer html file,it gives me an error Invalid token or unexpected token. How can I authenticate the user by using token,static way can also work for at this time? Any easy way? HTML FILE <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> </head> <body> <form id="form" method="POST"> <input type="text" id="id_messages"> <input type="submit" class="btn btn-primary"> </form> </body> <script> var roomName = "lobby"; var formdata=$("#form"); var input_val=$("#id_messages"); loc=window.location; // get the addresses console.log(window.location); var wsStart='ws://'; // check if it is secured then assign wss:// if (loc.protocol==='https:'){ wsStart="wss://" } console.log("host",loc.pathname); var endpoint=wsStart+loc.host+loc.pathname; var chatSocket = new WebSocket('ws://127.0.0.1:8000/' + '/ws/chating/' + "my22 + '/'); console.log("chat",chatSocket) // client side receives the message chatSocket.onmessage = function(e) { console.log("message",e) }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; chatSocket.onopen = function(e){ console.log("open",e); formdata.submit(function (event) { event.preventDefault(); var … -
How to write tests for django multi tenant applications?
I have multi-tenant applications in django with postgresql schemas. I tried to write test code inside a tenant folder "t002" as: from django.test import TestCase from path.customers.models import Client # TestClass to test tenant setup class TestTenantSetup(TestCase): def setUp(self): Client.objects.create( name='t002', schema_name='t002', domain_url='t002.cmpny.com' ) def test_tenant_exists(self): client = Client.objects.get(name='t002') self.assertEquals(client.schema_name, "t002") But when I ran the test with python manage.py test path/t002/tests it was creating a test database for my actual database. So let's say I would follow this SO answer (django unit tests without a db) and avoid creating database, but I am not sure if I'm following the right path to test a multi-tenant django project. When I looked into the django-tenant-schemas docs (https://django-tenant-schemas.readthedocs.io/en/latest/test.html) I couldn't get my hands on it easily. Can anybody tell how start doing test for django multi-tenant applications ? And please do review the above code too whether it is right or wrong. Specs - python==2.7, django==1.11, postgres==9.6 -
Generating non-database fields in admin form in Django
I am pretty new to Django and I have been following this great tutorial for getting started. Soon after that, I was encouraged to try and create my own booking app, which consists in: A postgreSQL database storing a simple table, where I want to keep a row for each day that a person is booked into a specific room. For certain reasons I am not following the typical booking model, where every row should have Start and End date covering all the booking period. For example, I have: John Doe - Room 401 - 01/01/2020 John Doe - Room 401 - 02/01/2020 ... Of course, my idea is that actually booking a reservation should be easier that introducing every day individually, so I would like the Django admin page to provide with a form including start and end dates, and by means of application logic generate the number of rows necessary in the database for covering every date in the range. Is there any way to present a non-database field in Django admin interface, and transform this input to the database model? -
ValueError: Cannot assign error in Django foreign key
I have three different Django apps in my project: questions, answers, and students. I created demo data for both Question and Student, and I want their objects to be foreign keys of Answer. Below is the migration file of Answer. from django.db import migrations from django.apps import apps questions = apps.get_model('questions', 'Question') students = apps.get_model('students', 'Student') def create_data(apps, schema_editor): Answer = apps.get_model('answers', 'Answer') Answer(question=questions.objects.get(pk="1"), student=students.objects.get(pk="2"), answer="Main function").save() class Migration(migrations.Migration): dependencies = [ ('answers', '0001_initial'), ] operations = [ migrations.RunPython(create_data) ] When I run python manage.py migrate, I get the error below. ValueError: Cannot assign "<Question: What is this?>": "Answer.question" must be a "Question" instance. Can please someone help me with this? -
django-admin.py startproject Inventory . is not working?
I am facing an error after installing Django, I tried (venv) C:\Users\Pallavai\DJANGO PROJECTS\Inventory>django-admin.py startproject inventory . Whenever I try this command, suddenly my sublime editor will open with code as given below. Any idea what is wrong? #!c:\users\pallavai\django~1\invent~1\venv\scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line() -
Why is the xmlHttpRequest readyState value stuck at 1?
So Im trying to send a FormData from an Word addin to a simple django server and returning a response.Below is the javascript function xyz() { Word.run(function (context) { var reqd_table_cell = context.document.getSelection().parentTableCell; reqd_table_cell.load("value"); return context.sync().then(function () { var texttable = reqd_table_cell.value; var data = new FormData(); data.append('key1', 'value1'); data.append('key2', 'value2'); data.append('key3', texttable); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 1) { context.document.body.insertText("1", Word.InsertLocation.end); } else if (xhr.readyState == 2) { context.document.body.insertText("2", Word.InsertLocation.end); } else if (xhr.readyState == 3) { context.document.body.insertText("3", Word.InsertLocation.end); } else if (xhr.readyState == 4) { context.document.body.insertText("4", Word.InsertLocation.end); } if (xhr.readyState == 4 && xhr.status == 200) { context.document.body.insertText(xhr.responseText, Word.InsertLocation.end); } }; xhr.open("POST", "http://127.0.0.1:8000/polls/", true); xhr.send(data); }); }).catch(errorHandler); } and below is the django server side python code @csrf_exempt def index(request): if request.method == "POST": login = request.POST.dict() req_file_name = login.get("key1"); email = login.get("key2"); text = login.get("key3"); print(req_file_name); print(email); print(text); #print("Done"); return HttpResponse("decoded"); and after running code I get the following in the Server console : value1 value2 "POST /polls/ HTTP/1.1" 200 7 and in the Word it prints only 1 and its stuck....Can anyone help me out? -
Number of records with a specific value
I need your advice with one sql request. I have two tables in django models: class Game(models.Model): name = models.CharField(max_length=100, unique=True) finish_date = models.DateField(blank=True, null=True) class Code(models.Model): code_text = models.CharField(max_length=200) correct = models.BooleanField() game = models.ManyToManyField(Game) One game can include a few code with same code_text. I want to get total count of game which include every correct code (something like 'code_text' - 'total count of game which include this code and this code was correct') but can only total number every correct code per game. My code below SELECT backend_code.code_text, COUNT(backend_game.name) FROM backend_code JOIN backend_code_game ON backend_code.id=backend_code_game.code_id JOIN backend_game ON backend_game.id=backend_code_game.game_id WHERE backend_code.correct=true AND backend_code.code_text IN ( SELECT DISTINCT backend_code.code_text FROM backend_code JOIN backend_code_game ON backend_code.id=backend_code_game.code_id JOIN backend_game ON backend_game.id=backend_code_game.game_id WHERE backend_code.correct=true) GROUP BY backend_code.code_text ORDER BY COUNT(backend_game.name) DESC; How i can do this? Thanks -
How to insert new record with nested many-to-many serializers in Django REST Framework?
I want to insert new Market using the browsable API but 'Lists are not currently supported in HTML input'. A Market may have 1 or more Countries and Languages. Here's the image attachment for my case. All Countries and Languages fields are shown here: Here's my serializers.py: class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ['id', 'name', 'icon', 'xml', 'abbreviation'] class RegionSerializer(serializers.ModelSerializer): class Meta: model = Country fields = ['id', 'geo_location', 'name'] class MarketSerializer(serializers.ModelSerializer): countries = RegionSerializer(many=True) languages = LanguageSerializer(many=True) class Meta: model = Market fields = ['id', 'countries', 'languages', 'name', 'status'] Here's my views.py: class MarketView(viewsets.ModelViewSet): queryset = Market.objects.all() serializer_class = MarketSerializer Countries and Languages data are already pre-populated. Is there any way to just select them like this when inserting new Market: I don't want to lose all Countries and Languages fields in the view list (it just showed the representative Id). I removed the nested serializer codes in serializers.py: class MarketSerializer(serializers.ModelSerializer): class Meta: model = Market fields = ['id', 'countries', 'languages', 'name', 'status'] -
ORM to the distinct values from a model based on the latest datetime field in Django
Consider I have a model named History and it has data like this. name comment date ---------------------------------- Jake some comment 2017-06-20 John some comment 2017-08-20 Jake some comment 2017-06-21 Albert some comment 2017-06-21 and from the above sample data, I want to get distinct data based on the datetime field. For example, it would be name comment date ---------------------------------- John some comment 2017-08-20 Jake some comment 2017-06-21 Albert some comment 2017-06-21 How can I write ORM for this? can anyone please help me! -
How can I make sure users do not stay logged in in django?
I programmed a small web application using django (version 3.0) and python (version 3.7.1). I am using the authentification tool, that comes with django. It works perfectly fine, but the problem I am facing is, that after I closed the browser and reopen it (sometimes several hours later) I am still logged in. That is something I want to avoid under all circumstances. I had the idea of making a check when the last login with that user was and if it was longer ago than for example 5 minutes you will get logged out, but I think there is and should be a more effective and elegant way to do it. -
FileNotFoundError at /success/ [Errno 2] No such file or directory: '/media/users/2019-10-25-200701_g2suiIo.jpg'
I am not being able to solve this problem for my Django project. I am making a realtime attendance system using face_recognition library. This is my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import StreamingHttpResponse from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm from django.contrib.auth.models import User from django.core.files.storage import FileSystemStorage import face_recognition import cv2 def facerec(request): video_capture = cv2.VideoCapture(0) # loc = "../media/users/" # Load a sample picture and learn how to recognize it. images = [] encodings = [] names = [] employees = User.objects.all() for e in employees: images.append(e.employee.image.url) encodings.append(e.username+'_face_encoding') names.append("Name: "+e.username) for i in range(len(images)): images[i] = face_recognition.load_image_file(images[i]) encodings[i] = face_recognition.face_encodings(images[i]) # my_image = face_recognition.load_image_file(input_file) # my_image_encoding = face_recognition.face_encodings(my_image)[0] # Create arrays of known face encodings and their names known_face_encodings = encodings known_face_names = names # Initialize some variables face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: # Grab a single frame of video ret, frame = video_capture.read() frame = cv2.flip(frame, 1) # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color …