Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send large table data using AJAX using GET/POST method in Django
I want to send my table data to the server using javascript(or ajax). How can I do this? There will be around 2k rows. The data is in a list of lists. How to send the data in lists? Here is what I did: JavaScript: $.ajax({ contentType: 'application/json; charset=utf-8', url:'/ccd/ajax/update-database', type: 'POST', data :{'headings':headings,'data_list':data_list,'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(data) { if(data.success) { console.log("success!"); } else { console.log("error!"); } } }); I'm not able to access this data in my views.py file. I'm getting None type of data. Views.py def ajax_update_database(request): data = dict() data['success']=False if request.is_ajax() and request.method=='POST': headings = request.POST.get('headings') print(headings) datalist = request.GET.get('data_list') print(headings) data['success']=True return JsonResponse(data) Any alternative will also be appreciated. -
DRF - Could not resolve URL for hyperlinked relationship using view name "matchteam-detail"
I know there are a lot of similar questions here, but I tried most of the answers and none worked so far... The error I get is: ImproperlyConfigured at /matches/1/ Could not resolve URL for hyperlinked relationship using view name "matchteam-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. However, matchteam-detail is in my urlpatterns: <URLPattern '^matchteams/(?P<pk>[^/.]+)/$' [name='matchteam-detail']>, <URLPattern '^matchteams/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='matchteam-detail']>, This error happens on a many-to-many relationships with a "through" model on Django REST Framework, when accessing a "Match" object on the API: models.py class MatchTeam(models.Model): team = models.ForeignKey("teams.Team", on_delete=models.CASCADE) match = models.ForeignKey("matches.Match", on_delete=models.CASCADE) score = models.PositiveSmallIntegerField(default=0) class Match(models.Model): teams = models.ManyToManyField("teams.Team", through='matches.MatchTeam') class Team(models.Model): matches = models.ManyToManyField("matches.Match", through='matches.MatchTeam') serializers.py class MatchTeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MatchTeam fields = ['id', 'team', 'match', 'score'] class MatchSerializer(serializers.HyperlinkedModelSerializer): teams = serializers.HyperlinkedRelatedField( read_only=True, view_name='matchteam-detail', ) class Meta: model = Match fields = ['id', 'teams'] class TeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Team fields = ['id', 'name'] urls.py router = DefaultRouter() router.register(r'teams', TeamViewSet) router.register(r'matches', MatchViewSet) router.register(r'matchteams', MatchTeamViewSet) urlpatterns = router.urls The views are defined with ModelViewSets. Any ideas why this might be happening? Thanks! -
load picture from static file django
Django is not loading my static files. I'm trying to load an image from the static folder, but it doesn't work. file.html <body> {% load static %} <img src="{% static "products/logo.jpg" %}" alt="My image"> </body> structure app |_______products |_________templates |_________file.html |_________models.py |_________ ... |______static |_________products |_________logo.jpg settings ... INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] ... STATIC_URL = '/static/' -
Django - DeleteView is missing a QuerySet
I have a model called Order. I want to delete a specific order with Class Based View (DeleteView) but is it is not working. Exception Type: ImproperlyConfigured Exception Value: DeleteView is missing a QuerySet. Define DeleteView.model, DeleteView.queryset, or override DeleteView.get_queryset(). model.py class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='orders') product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=200, null=True) view.py class OrderDeleteView(UserPassesTestMixin, DeleteView): model = Order template_name = 'accounts/delete.html' @method_decorator(login_required(login_url='login')) @method_decorator(allowed_users(allowed_roles=['admin'])) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def test_func(self): order = self.get_object() if order.customer.id == self.request.user.id: return True else: return False urls.py path('delete_order/<str:pk>', DeleteView.as_view(), name='delete_order'), What is the reason of this error -
how to use a forloop for my blog post to stand next to each other in django
actually my title might not be clear but let me explain,i have list of blogpost i want to use forloop to make each post stand next to each other,instead they all stood straight which i dont want here is the post this is how it is in picture , {this is how i want them to look like in a picture} blog.html <section class="ftco-section bg-light" id="blog-section"> <div class="container"> <div class="row justify-content-center mb-5 pb-5"> <div class="col-md-10 heading-section text-center ftco-animate"> <h2 class="mb-4">Gets Every Single Updates Here</h2> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p> </div> </div> <div class="row justify-content-center mb-5 pb-5"> <div class="col-md-4 ftco-animate"> {% for blog in blog_post %} <div class="blog-entry "> {% if not forloop.first and not forloop.last %} {% endif %} <a href="blog-single.html" class="block-20" style="background-image: url({{ blog.thumbnail.url }})"> </a> <div class="text d-block"> <div class="meta mb-3"> <div><a href="#">{{ blog.timestamp|timesince }} ago</a></div> <div><a href="#">{{ blog.user }}</a></div> <div><a href="#" class="meta-chat"><span class="icon-eye"></span>{{ blog.view_count }}</a></div> </div> <h3 class="heading"><a href="#">{{ blog.title }}</a></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="blog-single.html" class="btn btn-primary py-2 px-3">Read more</a></p> </div> {% endfor %} </div> </div> </div> </div> </section> -
Cannot run gunicorn with django-configurations raising ImproperlyConfigured
Building simple django application using django-configurations and gunicorn. If I run it with python manage.py runserver, it's ok. No errors, everybody's happy. But running gunicorn just by executing gunicorn config.wsgi:application raises an error with message: django.core.exceptions.ImproperlyConfigured: django-configurations settings importer wasn't correctly installed. HELP ME TO FIND THE MISTAKE, PLEASE! config/settings.py import os import dj_database_url from configurations import Configuration class BaseConfiguration(Configuration): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
Convert date string received through websockets using django channels to default django date display
So I am using django channels to send some updated field to my front end and update them when the underlying model changes. One of the field is a DateTimeField. Below is my signals.py: @receiver(post_save, sender=Job) def announce_new_user(sender, instance, created, **kwargs): channel_layer = get_channel_layer() group_name = 'job_%s' % instance.job_id message = { 'status': instance.status, 'job_completed_date': instance.job_completed_date.isoformat(), } async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_job_update', 'text': message } ) Initially when some one opens the page, the field will be displayed like "June 3, 2020, 9:40 a.m.". But since datetime.datetime is not serizable I am using the "isoformat()" to convert it. Now the this field is received in the front end like "2020-06-03T09:15:28+05:30". How can I can update my front end in the correct format. Should I use something other that "isoformat()" or can I do something using javascript to convert the date again? -
Django Admin: How to filter by custom list display field?
In the admin class, I have defined a custom list display as follows list_display = ('custom_display_method_name',) def custom_display_method_name(self, instance): #perform custom operation for list display which uses property of the model How do I write a filter which allows filtering by the custom display, or alternatively filtering by property of a model? I have trued writing a custom filter, but it comes down to queryset. Is there a way to simply filter by the custom display that I have written? -
How to delete a file on django
I am trying to add a view that deletes files(videos) but it seems that there is something wrong with my form because I am getting a ValueError("The view startup_home.views.delete_video didn't return an HttpResponse object. It returned None instead"). views.py def delete_video(request, pk): if request.method == 'POST': if form.is_valid: delete_v = Post.objects.get(pk=pk) delete_v.delete() return HttpResponseRedirect('/') else: return redirect('home') models.py class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) def delete(self, *args, **kwargs): self.text.delete() self.video.delete() super().delete(*args, **kwargs) urls.py urlpatterns = [ path('', views.home, name='home'), path('upload', views.upload, name='upload'), path('video/<int:pk>/', views.delete_video, name='delete_video'), ] home.html {% if content.video %} <div class="float-right"> <form action="{% url 'delete_video' content.pk %}" action="post"> <button type="submit">Delete</button> </form> </div> {% endif %} -
How to access objects created from Django Model Factory
I have populated a test database using Django Model Factory. Here is the model: class RecordType(factory.DjangoModelFactory): class Meta: model = models.RecordType class UserRecord(factory.DjangoModelFactory): user = factory.SubFactory(AccountUser) record_type = factory.SubFactory(RecordType) class Meta: model = models.UserRecord and here is the relevant part of the test: # Create record types for category in enums.Category: factory.RecordType( code=category.value, internal_code=internal_codes[category.value], ) # Add record to the user blind_record_type = factory.RecordType.objects.get(code="08") factory.UserRecord(user=user, record_type=blind_record_type) However, when running the test I am met with the error: E AttributeError: type object 'RecordType' has no attribute 'objects' Is it possible to access these objects? -
Django WritingYourFirstDjangoApp Part5
I was using the following tutorial website and although I had followed every instruction on the website, this error showed up... docs.djangoproject.com/en/3.0/intro/tutorial05/ (python shell) In [16]: response = Client.get(reverse('polls:index')) Internal Server Error: /polls/ Traceback (most recent call last): File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'ls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/****/Desktop/Programming1/hello_django/django/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/****/Desktop/Programming1/hello_django/django/django/core/handlers/base.py", line 202, in _get_response response = response.render() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/loader.py", line 42, in select_template return engine.get_template(template_name) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/****u/Desktop/Programming1/hello_django/django/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/loaders/base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 155, in init self.nodelist = self.compile_nodelist() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 193, in compile_nodelist return parser.parse() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 472, in parse self.invalid_block_tag(token, command, parse_until) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 534, in invalid_block_tag "or load this tag?" % (token.lineno, command) django.template.exceptions.TemplateSyntaxError: Invalid block tag on line … -
how to add group field in django admin using custom user model
django custom user model i created a custom user model but if i open a user in the django admin, i cannot see the field to add the user to a group. what will i need to add to my custom user model code so i can see the field to mannually add a user to a group in the django admin? for example i know if i want to see permission fields, i will add to my class UserAdmin: fieldsets = ( ('Permissions', {'fields': ('admin', 'staff')}), ) -
Storing answers to questionnaire in Django model
I have a django model that should store users's answers to a questionnaire. There are many types of questionnaires, but one could be simple like this (many are more complicated though): What is your name? What is your age? What is your height? What is your age? I want to know how I could create a model to store the data that was submitted in the form. Right now, I am using a simple JSON field like this: from django.contrib.postgres.fields import JSONField data = JSONField(default=dict) This gets difficult however when the questionnaire get much longer. What would be the best way to do this? If a JSON field is the best way, how should I structure the json assuming there could be different types of questions (input field, multiple choice, etc.)? Thanks!! -
javascript для backend разработчика [closed]
Всех приветствую, сразу прошу прощения за расплывчатый вопрос. Хочу стать бекенд разработчиком, доучился до уровня кривого сайта на Django/Bootstrap. Перехожу к изучению Django Rest Framework ибо углубляться в стоковый Django можно очень долго, а на работу хочется скорее(DFR очень часто указан в требованиях). Вопрос: Какой уровень понимания javascript мне нужен? В коммерческой разработке каким будет мое взаимодействие с AJAX? По плану: DRF -> Docker -> идти собеседоваться Заранее благодарен, если кто-то поможет прояснить.Естественно понимаю, что в вакууме среди современных технологий нет тех, которые не стоит изучать, вопрос стоит в условиях сжатых сроков. -
Vue js downloaded excel file is corrupted
I have problem with excel file download in Vue. The url in the backend seeems to be ok: "file" parameter stores my url in the object this.scenario.file = "http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" downloadFile() { axios({ url: this.scenario.file, method: "GET", headers: {"Accept": "application/vnd.ms-excel"}, responseType: "blob" }).then(response => { const fileURL = window.URL.createObjectURL(new Blob([response.data])); const fileLink = document.createElement("a"); fileLink.href = fileURL; fileLink.setAttribute("download", "file.xlsx"); document.body.appendChild(fileLink); fileLink.click(); }); }, -
Django Admin has no style sheet
Good day everyone, I'enter image description herem new to Python and Django I started of with online tutorials and some books I just tried getting through and my Django admin page has no styling...... what really did miss? -
Django Filter Queryset Model
How can I filter my table to only show the quotes from a project. In order to display all quotes, I am using {% for quote in quotes.all %} Now, I would like to display quote relative to a site. Which means when selecting my site_id, I`ll be able to only see the quote relative to this site_id. I could write something like {% for quote in quotes.all %} {% if quote chantier.id %} {% endif %} {% endfor %} but this is wrong. Here is my model for quote: models.py class Quote(models.Model): name = models.CharField(max_length=30) site = models.ForeignKey(Site, on_delete=models.CASCADE) How can I display all quotes from this site? Many Thanks, -
Hosting Django with Apache2 on an Docker
Friday I spent 5 hours on my work setting up Django. Django works perfectly fine, but i can't acess the test environment. My Docker got an web adress where I can acess it and i want to open the Django Environment over web. I My Problem is I can't seem to get it right. What I do it does'nt work I can't acess it over web. Here is a Link of an example Guide I used where I tried linking up Django with Apache2. https://www.metaltoad.com/blog/hosting-django-sites-apache Maybe someone of you can help me to get it right. -
Django TemplateDoesNotExist at / Help! I feel I tryed everything =´ (
Im a new self taught programmer (I started a few months agos with java) from Cordoba Argentina and this is my first post here. Im stuck on this problem for the last two days, I was working on my firts project and I reinstall windows on my computer, after I install Python 3.8.3 and Django 3.0.7, anaconda, visual studio code, and a lot of shit. When I continue with my project, I follow my tutorial made some changes and after running the server I found with this error. After going back to what I think what I was the last time It works, I reinstall everything again thinking that maybe was some mistake on the installation. I tried with the templates DIRS too and I got the same error. The place where my templates are is F:\Programacion\Python\Django\ProyectoWeb\ProyectoWebApp\templates\ProyetoWebApp TemplateDoesNotExist at / ProyectoWebApp/Inicio.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.7 Exception Type: TemplateDoesNotExist Exception Value: ProyectoWebApp/Inicio.html Exception Location: D:\Python\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: D:\Python\python.exe Python Version: 3.8.3 Python Path: ['F:\\Programacion\\Python\\Django\\ProyectoWeb', 'D:\\Python\\python38.zip', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python', 'C:\\Users\\frua\\AppData\\Roaming\\Python\\Python38\\site-packages', 'D:\\Python\\lib\\site-packages'] Server time: Sun, 7 Jun 2020 19:23:51 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: … -
How to get a full path of web page to my views.py?
How to get a full path of web page to my views.py? http://192.168.0.178:8000/customers-orders/37/customers-orders-date/?datefilter=06%2F14%2F2020+-+06%2F26%2F2020 How to get this path to my views.py for to work with it? -
inlineformset factory only save last form
i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form , my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] inlineformset_author = inlineformset_factory = (Author,Book,form=AuthorForm,extra=1) this is my template class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = inlineformset_author(self.request.POST) context['book'] = inlineformset_author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"> <h5 class="modal-title" id="my-modal-title">BOOK</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <div class="modal-body"> <button type="submit" class="btn btn-success">save</button></dic> </div> <div class='modal-footer'></form> <script> $(document).ready(function(){ $('#BOOKBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#count').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="BOOK'+justforName+'"').val()); … -
How to get a count of all instances of a foreign key in a different model?
I have model A and model B. Model B has a member foreign key of model A. I wish to keep try of the number of B's attached to model A. I would also like In model A we are trying to use and update the number off instances of B to A and hold that in model A num_B = models.IntegerField(default=0) In model B we have the member ForeignKey modelAInstance = models.ForeignKey(ModelA, on_delete=models.CASCADE) -
How to make custom error pages django 2.2
I am creating a blog using Django 2.2, and I have recently finished almost all of it. All that is left is making custom error pages. I have a book that shows how to do it, but it doesn't work. I have checked all over online, but nothing works. Please help? Here is the code: settings.py: """ Django settings for boy_talks_about_coding project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8rk31cd@y065q)l9z2x@4j#a*gz6g3lw_$$g3e7#@de4xyj#xg' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost''boytalksaboutcoding.com''boytalksaboutcoding.herokuapp.com'] # Application definition INSTALLED_APPS = [ # My apps 'blog_posts', # Third party apps 'bootstrap4', # Default Django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'boy_talks_about_coding.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
What's the best way to authenticate user with a Django API?
I want to create a web application with Django as backend and react or angular as frontend, but I don't understand what's the best way to manage authentication. I heard a lot about JWT but I also read that it's insecure, so is there a way to auth with react and Django api for example ? -
Django dynamics colums forloop
I would like to know how you would solve my issue. I've managed a solution but aesthetically I don't like it I have a fix width box that I have to fill with a table (9 cols and 6 rows minimum). Some fields are fixed some others are dynamic. The results should be something similar to the following: | Order | <order_nr> | Qty | Desc | Price | Qty | Desc | Price | |----------------|--------------------|-----|------|-------|-----|------|-------| | Customer | | | | | | | | Address | | | | | | | | City | Zip code | | | | | | | | Shipping terms | Total order amount | | | | | | | | Note | <notes> | | | | | | | Qty Desc Price are dynamically generated based on the order that the customer has submitted, and potentially the order could have more than 10 lines (which my design is capable to handle) So here are my main problems and solutions: I have placed 2 tables together but I don't get the same line-height for both tables. I cannot add via CSS a fixed height since I don't know how …