Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ck-editor can't add extra plugin
I am trying to add an extra plugin but I can't. When I am inspecting my console it's saying can't load the javascript file. Here is my code: error which I am getting in my console but I have youtube plugin in my plugins folder: Loading failed for the <script> with source “http://127.0.0.1:8000/static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=LAHF”. settings.py STATIC_ROOT = 'var/static' CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join([ 'youtube', ]), }, } urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py class Blog(models.Model): blog_title = models.CharField(max_length=255) blog_body = RichTextUploadingField(blank=True, null=True,) I also tried this but didn't work: blog_body = RichTextUploadingField( config_name='default', # CKEDITOR.config.extraPlugins: extra_plugins=['youtube'], # CKEDITOR.plugins.addExternal(...) external_plugin_resources=[( 'youtube', 'var/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )], ) -
KeyError '\ufeffMaterial VN #'
I'm running into an issue where my form data seems to be encoded (not sure which encoding), but when I try to use pandas to locate my column name it searches for '\ufeffMaterial #' instead of 'Material #'. I've tried using pd.read_csv(file, encoding='utf-8-sig') and tried (unsuccessfully) to encode/decode the column name. Any suggestions? The line that's throwing the error is in functions.py: custColData = oldDF.loc[:,string]. functions.py def mapData(company, hierarchy): oldDF = pd.read_csv(company.file, encoding='utf-8-sig') newDF = pd.DataFrame() if (company.needsMapping == "False"): pass else: columnMappings = RawDataColumnMapping.objects.filter(companyName = company) attributesDict = {} for columnMap in columnMappings: string = str(columnMap.custColumn).encode('utf-8').decode() custColData = oldDF.loc[:,string] if columnMap.columnMapping != COLUMNS.attributes: newDF[columnMap.get_columnMapping_display()] = custColData else: custCol = columnMap.custColumn.split('~') columnDict = dict(zip(custCol, custColData)) attributesDict.update(columnDict) newDF['attributes'] = (json.dumps(attributesDict)) models.py class RawDataColumnMapping(models.Model): companyName = models.ForeignKey(RawData, on_delete=models.CASCADE) custColumn = models.TextField() columnMapping = models.PositiveSmallIntegerField(choices=COLUMNS) def __str__(self): return f"{self.companyName.companyName}_{self.custColumn}_{self.get_columnMapping_display()}" views.py def applyPPTMapping(request, companyName): if (request.method == "POST"): form = ApplyPPTMappingForm(request.POST, companyName=companyName) if form.is_valid(): rawData = form.cleaned_data['companyRawData'] rawDataCompany = rawData.split('_', maxsplit=2)[-1] rawDataObj = RawData.objects.get(slugField=rawDataCompany) hierarchy = form.cleaned_data['companyHierarchy'] hierarchyCompany = hierarchy.split('_', maxsplit=2)[-1] hierarchyObj = RawData.objects.get(slugField=hierarchyCompany) df = mapData(rawDataObj, hierarchyObj) -
how to get non selected values from multiselectfield
I use multiselectfield for a model. with this model I show the user which choices they have made. but I also want to show (filter) the unselected (null) values below. is there someone who can point me to a function that works with multiselectfield to extract the null values ? thank you. -
Video streaming in react-native using custom API
I'm working on a react-native app using expo-av to show videos, and whne I put in source the uri: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4', from google samples, it acutally works, but if I try to put a uri for a video contained in my django media folder, the following error occur: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I solve? Thank you -
Data is not submitting through Ajax is not Submitting
here is ajax code $('#form').on('submit', function(e){ $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ type : 'POST', url: "{% url 'HealthTest' %}", data: { first_name : $('#first_name').val(), deparment : $('#deparment').val(), Reg_No : $('#Reg_No').val(), Health_status : $('#Health_status').val(), dataType: "json", }, success: function(data){ $('#output').html(data.msg) /* response message */ }, failure: function() { } }); }); This form code {% csrf_token %}{{form.as_p}} when i press submit in my pages this error message pop up in console window enter image description here I Tried different solution but it is not working for me. I am new to this Thank in advance. -
Is there an efficient way to add a csv file with many columns to a Django model?
I have a data frame with over 150 columns that I want to add to my Django database. Everything I have seen online gives an example only using a couple columns and requires that you list each field that you want to use. Is there a way to create a model that inherits from the data frame columns and does this process more efficiently? -
How to dynamically construct a hyperlink using Django named url
In my Django application I am using an ajax function to send some field values, do some processing (in views.py) and in the event of some exception (data mismatch etc), trying to construct a url for the user to use and navigate to the intended page (for further activities). Now, in the event of the exception (as described above), I am sending a pre-configured exception message (var_err) and a url (var_err_url) that would be constructed into a hyperlink for the user to make use of. Presently I am using the following scenario: Passing the two variables as json data bits (to display message text and dynamically creating a hyperlink, respectively) to the template and using jQuery to display the message along with the hyperlink (as shown hereunder): $('#id_err_message').html(var_err + ' <a href=" ' + var_err_url + '">Check</a>'); My set up works if I pass the url (variable var_err_url) as shown below: '/movement/planning/tpt_tenders/create/' i.e. the complete path. What I am trying to find out is: Is there a way to, instead, pass (Django) url name and dynamically create the hyperlink to have the same effect as shown under (as is done in Django templates), i.e.: <a href="{% url 'tpt_tender_add' %}">Add Tpt … -
Django JWT auth without migration
I have 2 projects written by Django : 1- Authentication(P1) and my_API(P2). in P1 I use DRF-simplejwt and 'dj-rest-auth' to register,login,logout,reset password ,... for P2 I need authentication. My opinion is that JWT does not use database for checking access token so It does not need to connect my users db to P2. But now I have error saying that I should migrate auth_user for rest_framework_simplejwt. What should I do now for checking permissions of P2 end points? Thanks for your attention :) -
Using Django's cache to store a model property
I have an image model with a foreign key back to the parent model. class MyImage(models.Model): parent = models.ForeignKey(ParentModel, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='images') I am also using django-s3-storage to have these images served from a private S3 bucket. When I ask for the image url in a template using (this is a class based detail view, I also get the images in a class based list view): {% for image in object.images.all %} <img src="{{image.image.url}}" alt=""> {% endfor %} the value returned from url is a signed url and that's fine. I'd prefer not to make my bucket public. The problem is that this signed url is generated every time I get the url from the image model, which prevents the image from being cached in the browser as the signature changes on every request. This isn't ideal since these images will rarely change and I'd like them browser cached to reduce S3 costs. I am currently also using Django's built-in caching (in my case, I'm using database caching for the time being). The built-in caching will let me cache template fragments like so: {% for image in object.images.all %} {% cache 1440 object_image object %} <img src="{{image.image.url}}" alt=""> … -
Charfield with select2 input not populated in update view
I'm working on a form that gets the "Education" information from the user. The institute name is one of the fields in the model. The initial configuration for the model: class Education(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) institute = models.CharField(max_length=50, null=True, blank=True) program = models.CharField(max_length=50, null=True, blank=True) level = models.CharField(max_length=1, choices=StudyLevel.choices, default=StudyLevel.UNSPECIFIED) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I don't want to grant the users ability to give meaningless input. That's why I decided to let users "select" their university from an external API. Sample search: http://universities.hipolabs.com/search?name=johannes I used jQuery Select2 with Ajax to fetch data from the API whenever user types a character in the field. Ajax code: $(document).ready(function () { $('#id_institute').select2({ ajax: { url: 'http://universities.hipolabs.com/search?', data: function (params) { return { name: params.term }; }, dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.name, text: item.name}; }) }; } }, width: '50%', minimumInputLength: 1 }); And I had to overwrite the widget for the 'institute' field at the ModelForm as following: class EducationForm(ModelForm): class Meta: model = Education fields = '__all__' exclude = ['owner'] widgets = { 'institute': forms.Select(), } It works as expected: create view However, when I go … -
Celery django with supervisor dont give use the Django database scheduler
I got apache server with django, all work. And celery with redis. Worker work,all right, but when on celery beat through supervisor, i get an error. My think was about database(postgress), but 'django' all granted. Here error. Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/polski-urody-back/venv/bin/celery", line 8, in <module> sys.exit(main()) File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/__main__.py", line 16, in main _main() _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/polski-urody-back/venv/bin/celery", line 8, in <module> sys.exit(main()) value = obj.__dict__[self.__name__] = self.__get(obj) File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/worker/state.py", line 266, in db return self.open() File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/worker/state.py", line 192, in open return self.storage.open( File "/usr/lib/python3.8/shelve.py", line 243, in open … -
Override django-filters Django models PointField
I am trying to filter data using django-filters. I am using a PointField for location and I want to override this field from filters.py. How can I override the models PointField from filters.py? import django_filters from .models import Apartment class ApartmentFilter(django_filters.FilterSet): ADKT = 'Addis Ketema' AKLT = 'Akaki-Kality' ARDA = 'Arada' BOLE = 'Bole' GLLE = 'Gulele' KLFE = 'Kolfe-Keranio' KIRK = 'Kirkos' LDTA = 'Lideta' YEKA = 'Yeka' NFSL = 'Nefas Silk-Lafto' SUBCITY_CHOICES = [ (ADKT, 'Addis Ketema'), (AKLT, 'Akaki-Kality'), (ARDA, 'Arada'), (BOLE, 'Bole'), (GLLE, 'Gulele'), (KLFE, 'Kolfe-Keranio'), (KIRK, 'Kirkos'), (LDTA, 'Lideta'), (NFSL, 'Nefas Silk-Lafto'), (YEKA, 'Yeka')] class Meta: model = Apartment fields = ['apt_subcity', 'apt_cost'] filter_overrides = { models.PointField: { 'filter_class': django_filters.CharField, } } -
How to integrate Blastplus in a Django environment
Django newbie here! I have downloaded via git clone this package: https://github.com/michal-stuglik/django-blastplus I have installed all the dependencies required in the requirement.txt I already have my really basic site working and now what I want to achieve is to add the BLAST tool in it. What I miss is basically what I have to do to integrate this app with my website. Actually, I am able to call the .html templates, but I am not able to call the forms.py that contains all the instructions to make the BLAST alignments. I know that what I am asking will require a pretty long answer, but any hint will help. If I have to share some of my file in order to let the community makes a better idea of my situation, do not refrain to ask. Thank you so much. -
Input boxes styling weirdly when using Django & Tailwind.css
I am creating a simple login page using Django & Tailwind.css. My form was styling fine until I inherited a <nav> from base.html. When I did so, gray borders started appearing around my input boxes and the input boxes got slightly bigger. The original layout: https://ibb.co/vXxgrH0 The new layout (with base.html being inherited): https://ibb.co/QCsvKmz I'm not sure why this is occurring, because all of the code remains the same, I am just {% extends "base.html" %} at the top of my login.html Here is my base.html code (contains the navar & responsive navbar): <!DOCTYPE html> <html class="screen-top"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://shuffle.dev/vendor/icons/css/fontello.css?v=h7b" id="bs-base-css"> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="css2?family=Poppins:wght@400;500;600;700&display=swap"></style> <link rel="stylesheet" href="https://shuffle.dev/static/build/css/shuffle-preview.3a553ecf.css"> <link rel="stylesheet" href="https://unpkg.com/flowbite@latest/dist/flowbite.min.css" /> <script src="https://shuffle.dev/vendor/tailwind-flex/js/main.js"></script> <script src="https://cdn.tailwindcss.com"></script> {% block css %} {% endblock %} </head> <body id="page" class="antialiased font-body bg-body text-body bg-[rgb(248,250,251)]"> <!-- NAVBAR --> <div class="" id="content"> <section class="relative overflow-hidden"> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2a3342;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> … -
Get a queryset of objects where a field is distinct
I have a model like the following: class Reports(models.Model): reportid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=100) description = models.CharField(max_length=300, default='', blank=True) value = models.FloatField(default=0) I need to search the model by matching a search term in the name field. Then I need to return a queryset containing objects each of which have unique names which match the search term. See the example: testsearchterm = 'bs' initreports = Reports.objects.filter(name__lower__contains=testsearchterm) print("initreports:", initreports) Result: initreports: <QuerySet [<Reports: FBS>, <Reports: PPBS>, <Reports: FBS>, <Reports: FBS>, <Reports: PPBS>, <Reports: FBS>, <Reports: FBS>, <Reports: PPBS>, <Reports: Random Blood Sugar (RBS)>, Now I get distinct names reports = Reports.objects.filter(name__lower__contains=testsearchterm).values_list('name', flat=True).distinct() print("Unique values:", reports) Result: Unique values: <QuerySet ['FBS', 'PPBS', 'Random Blood Sugar (RBS)', 'Sleep study to r/o Obstructive sleep apnea', 'Serum HBsAg']> Now I need the full queryset not just the names, so that I can serialize the results and return the other fields too. for name in tests: res = Reports.objects.filter(name=name).first() print(res, type(res)) Results: FBS <class 'appointments.models.Reports'> PPBS <class 'appointments.models.Reports'> Random Blood Sugar (RBS) <class 'appointments.models.Reports'> Sleep study to r/o Obstructive sleep apnea <class 'appointments.models.Reports'> Serum HBsAg <class 'appointments.models.Reports'> I need a queryset of the above, like the following: <QuerySet [<Reports: FBS>, <Reports: PPBS>, <Reports: RBS>, … -
Django Server Error whenever i run my server how to resolve this error
this error occurs again and again anyone have solution please tell me -
Django for loop in html<script>
I've created a menu where there was originally a hardcoded choice .Im trying to pass some models names into it but it doesnt work . Any ideas what I am doing wrong? view def map(request): field_list = models.Field.objects.all() context = { "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) map.html {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name")); //friendly name {% endfor %} -
Compare Day of the Week with ManyToMany Relationship
I'm new to Django and learning, and i'm trying to do the following: The user registers the days of the week and the time period he is available. class DiasDaSemana(models.Model): diasdasemana = models.CharField(max_length=20) def __str__(self): return self.diasdasemana class RelacaoHorarioSemana(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE) relacao_dia_semana = models.ManyToManyField(DiasDaSemana) start_horario = models.TimeField(auto_now=False, verbose_name='Horário Inicial',blank=False, null=False) end_horario = models.TimeField(auto_now=False, verbose_name='Horário Final',blank=False, null=False) obs = models.TextField(max_length=200, null=True) class Meta: verbose_name = "Usuário e Horário" verbose_name_plural = "Usuários e Horários" def dias_da_semana(self): return ", ".join([str(p) for p in self.relacao_dia_semana.all()]) def __str__(self): return str('Cadastre o Horário de Trabalho do Usuário:') I want to add a logic that checks if the user is available on the present time and day, so i can filter the results to display in a template. I'm trying to compare the timezone.isoweekday IDs with the user inputted IDs (Which are the same, Monday = 1 and Segunda-feira(Monday in Portuguese) is = 1) but i'm clueless as how to do it... I've thought about querying the ManyToMany field but i'm clueless as how to do it. So far, i've got to this: @property def checar_disponibilidade_horario_dia(self): data_comeco = timezone.localtime(self.start_horario) data_fim = timezone.localtime(self.end_horario) data_agora = timezone.localtime(timezone.now()) # Segunda é 1 e Domingo é 7 diasemana_hoje = … -
AttributeError: 'NoneType' object has no attribute '_meta' while updating data using nested serializers via PATCH call in Django Rest Framework
I want to update the Model data using nested serializers via PATCH call in DRF. I have custom User Model, Country, City, Detail Model. I have MainUserSerializer, CountrySerializer, CitySerializer and UserSerializer, and I have UserAPI view. Below is my models.py: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class Country(models.Model): name = models.CharField(max_length=100, default='c') def __str__(self): return ("{}".format(self.name)) class City(models.Model): name = models.CharField(max_length=100 ,default='c') country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return ("{} ({})".format(self.name, self.country.name)) class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=20, default='g') age = models.IntegerField(default=0) country = models.IntegerField(default=1) city = models.IntegerField(default=1) def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) my serializers.py: class MainUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email') class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('name',) class CountrySerializer(serializers.ModelSerializer): city = CitySerializer() class Meta: model = Country fields = ('name', 'city') class UserSerializer(serializers.ModelSerializer): usr = MainUserSerializer() country = CountrySerializer() city = CitySerializer() … -
Create link to specific blog article by primary key in Django and slugify url
I am following some basic tutorials to learn the basics of building websites in Django. I have a "news template" working, but I am struggling to (understand) create the links to a specific database article and use the slug in the url. I have only managed to find examples where a list of all posts are shown with links but this is not what I am looking for. I have this: models.py class Post(models.Model): title = models.CharField(max_length=200) slug=models.SlugField(max_length=250, null=True, blank=True) category=models.CharField(max_length=40) text=RichTextField(blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug=slugify(self.title) super().save(*args, **kwargs) # def get_absolute_url(self): # return reverse('post_detail', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('post_detail', kwargs={"id":self.id, "slug":self.slug}) views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) urls.py urlpatterns = [ path('',views.index,name='index'), path('articles/<int:pk>/', views.post_detail, name='post_detail'), # path('articles/<slug>/', views.post_detail, name='post_detail') ] html: <a href="{% url 'post_detail' pk=1 %}">'*article headline from post.title (somehow)*'</a> This works when I hardcode the primary key of the article but of course the url shows with the pk and fails if I try using slug (NoReverseMatch). What can I do in the html line to be able to point to a specific article but get the slugfield to be shown … -
Django Import-Export
Im using Django import-export to add a large spreadsheet into a model. The import itself works just fine, but I am looking to add two additional columns to the dataset that identify the name of the excel file, and the date it was uploaded. Here is my Model from django.db import models class DataImport(models.Model): Column1 = models.CharField(max_length=15, null=True) Column2 = models.CharField(max_length=50, null=True) Column3 = models.CharField(max_length=25, null=True) Column4 = models.CharField(max_length=150, null=True) FileName = models.CharField(max_length=150, null=True) UploadDate = models.CharField(max_length=150, null=True) def __str__(self): return str(self.Column1) My Resource Class from dashboard.models import DataImport from import_export import resources, fields from import_export.fields import Field class DataImportResource(resources.ModelResource): Column1 = Field(attribute='Column1', column_name="Column_1") Column2 = Field(attribute="Column2", column_name="Column_2") Column3 = Field(attribute='Column3', column_name="Column_3") Column4 = Field(attribute='Column4', column_name="Column_4") def skip_row(self, instance, original): if instance.Column1.strip() != 'value': return True if instance.Column2.strip() not in {'value1, 'value2', 'value3', 'value4'}: return True else: return False class Meta: model = DataImport and my admin class class DataImportAdmin(ImportExportModelAdmin): resource_class = DataImportResource admin.site.register(DataImport, DataImportAdmin) ideally, I would like to have the user select the excel, and then select the month from a select list that will then go into the "UploadDate" field in the database. due to the duplicative (but needed) nature of the data, I need to do … -
Slice a list with for loop range function in Django templates
I am developing a Django application about statistics calculations. But now I have faced a problem that I can't solve. I have two lists in my views.py list1 = [5, 6, 7, 8] list2 = [5, 6, 7, 8]. I sent this to Django templates and I also sent 'n' : range(7) as context. In my html code, there have a code <table> <thead> <tr> <th>list1</th> <th>list2</th> </tr> <tr> <td></td> <td></td> </tr> </thead> </table> Now I want to print first value of each list in first row, then second value of each list in second row and so on. So I have made a code something like this <table> <thead> <tr> <th>list1</th> <th>list2</th> </tr> {% for i in n %} <tr> <td> {{ list1.i }} </td> <td>{{ list2.i }}</td> </tr> {% endfor %} </thead> </table> After writting this code, I am not getting any error but the values are not showing. Instead a blank row and columns are being made. Please help me to print the values that I want to print. -
Django rest framework user earn points
How do I make dot scheme in django? Like, every time I send a post and the answer is true, the user gets a point, and whenever he sends a post with the id of the answer and the answer is True, the user gets more point -
Django: error trying to access detail view with re_path
To elaborate, I went down a bit of a rabbit hole just trying to make a trailing "/" optional in the URL. got it to sorta work with the project directory, but when on the blog app, I tried to use re_path in order to use regex to allow for an optional trailing "/" in the url, but I seem to get an error in the template website urls.py (directory with settings.py) from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('blog/', include('blog.urls')), path('blog', include('blog.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blog urls.py from django.urls import path, include, re_path from .views import BlogView, ArticleView urlpatterns = [ path('', BlogView.as_view(), name="blog"), re_path(r'titles/(?P<slug_url>\d+)/metadata/localized/$', ArticleView, name="article"), ] blog.html template error appears at the href {% extends 'base.html' %} {% block content %} <h1>Articles</h1> {% for post in object_list %} <h2><a href="{% url 'article' post.url_slug %}">{{ post.title }}</a></h2> {% endfor %} {% endblock %} blog views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Post from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect # Create your views here. class BlogView(ListView): model … -
MultiValueDictKeyError at / 'name'
enter image description here i just want to fetch the data from my website and record it to my django databae this my views.py code : def index(request): feature1 = Feature.objects.all() Appnt = Appointment.objects.all() if request.method == 'GET': Appnt.name = request.GET['name'] Appnt.email = request.GET['email'] Appnt.phone = request.GET['phone'] Appnt.Adate = request.GET['date'] Appnt.Dept = request.GET['department'] Appnt.Doc = request.GET['doctor'] Appnt.message = request.GET['message'] contaxt = { 'feature1' : feature1, 'Appointment' : Appnt } return render(request, 'index.html', contaxt)