Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how can I acccess request.meta in a class-based view like UpdateView?
Well, actually the question is in the title :) I want to have an UpdateView with different redirects depending on the referer from which the update is called. -
How to get value from html to django class based view?
What's the simpliest way to do this? I'd like to get this html input value: <form method="post" action=""> {% csrf_token %} <input name="pagination" type="search"> <button type="submit">save</button> </form> To views.py class CategoryListView(ListView): login_url = '/category/' model = Category pagination = <<--here def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list return super().get_context_data( object_list=queryset, **kwargs) url.py path('expense/categories/', CategoryListView.as_view(), name='category-list'), -
How to get response in template while process is not completed in django?
I am building a bot using django and selenium which require live results in template view to update the user with current figures. -
Convert postgres sql query to Django
I want to convert the following query to Django select file.id, array_agg(fileregion.defect_ids) from file left outer join (select file_id, jsonb_object_keys(defects) as defect_ids from ai_fileregion ) as fileregion on fileregion.file_id=file.id group by file.id Following are my Django models class File(Base): class Meta: db_table = "file" class FileRegion(Base): file = models.ForeignKey(File, on_delete=models.PROTECT, related_name='file_regions') # defects is of the form {'<defectid1>': {}, <defectid2>: {}} defects = JSONField(default=dict) class Meta: db_table = "ai_fileregion" Aim is to basically get a list of records in which one field is the file_id and another field has an array of aggregated keys from defects json field for that file_id. Note: Each file may have more than one entry in the ai_fileregion table. Note: There will be more chaining added to this queryset. So, getting results in a different format to server and modifying it at the application level is not an option. -
upload file from client android to sever django
I'm trying to upload my file not only image file but any file from android to django directory I specified. I tried some methods in online, but failed. Any advice is welcome. My Reference https://docs.djangoproject.com/en/3.1/topics/http/file-uploads/ =====Android Files===== MainActivity.java public class MainActivity extends AppCompatActivity { TextView contentView2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentView2=findViewById(R.id.content2); HashMap<String, String> recordMap=new HashMap<>(); recordMap.put("name","GetUserFile"); RecordSender recordSender = new RecordSender(); recordSender.request("http://my_server_ip_address/recommender/GetUserFile/".concat("100"), recordMap, httpCallbackSend,"/data/data/com.example.servertest/databases/recommend.jpg"); } HttpCallback httpCallbackSend=new HttpCallback() { @Override public void onResult(String result) { try{ contentView2.setText(result); }catch (Exception e){ e.printStackTrace(); } } }; } RecordSender.java public class RecordSender { private static final String TAG = "RECORDSENDER"; RecordTask http; public void request(String url, HashMap<String, String> param, HttpCallback callback, String filePath) { http = new RecordTask(url, param, callback, filePath); http.execute(); } private class RecordTask extends AsyncTask<Void, Void, String> { String url; HashMap<String, String> param; HttpCallback callback; String filePath; public RecordTask(String url, HashMap<String, String> param, HttpCallback callback, String filePath) { this.url = url; this.param = param; this.callback = callback; this.filePath = filePath; } @Override protected String doInBackground(Void... voids) { try { URL text = new URL(url); HttpURLConnection http = (HttpURLConnection) text.openConnection(); http.setRequestProperty("enctype", "multipart/form-data"); http.setRequestProperty("Content-Type", "multipart/form-data;"); http.setRequestProperty("Connection", "Keep-Alive"); http.setConnectTimeout(10000); http.setReadTimeout(10000); http.setRequestMethod("POST"); http.setDoInput(true); http.setDoOutput(true); http.setUseCaches(false); http.connect(); File file = new … -
Django is installed but raises importError: Could not import django on running python3 manage.py runserver?
I have correctly installed django. When I run the below commands the following errors are thrown. I have tried out the answers for this similarly asked questions, but nothing solves my issue. sibasisnayak@MacBook-Air backend % python3 manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? sibasisnayak@MacBook-Air backend % django-admin --version 3.1.2 I don't have pip installed, but I have pip3 installed. sibasisnayak@MacBook-Air backend % which python /usr/bin/python sibasisnayak@MacBook-Air backend % which python3 /usr/local/bin/python3 sibasisnayak@MacBook-Air backend % which pip3 /usr/local/bin/pip3 sibasisnayak@MacBook-Air backend % which pip pip not found -
Django data via ajax is empty on view
I'm trying to pass a data to django view via ajax like I used to do with php but I get on print empty value but my console log show that there is a data value on javascript but on view return None Quit the server with CONTROL-C. None my html file code {% for image in images %} <table style="width:100%;" id="tab-{{image.image_cid}}"> <tr> <td style="width:70%;vertical-align:middle"> <img src="/medias/{{ image.image_value }}" alt="" width="100" > </td> <td style="width:30%;vertical-align:middle"> <a href="#/" id="{{ image.image_cid }}" class="cl-img-del"> DELETE </a> </td> </tr> </table> {% endfor %} <script> $(document).ready(function(){ $(".cl-img-del").click(function(e){ var imgID = e.target.id console.log(imgID); $.ajax({ headers: {'X-CSRFToken': '{{ csrf_token }}'}, url: "{% url 'delete-image-ajax' %}", type: "POST", data: { imageid: imgID }, contentType: false, cache: false, processData:false, success: function(data){ if(data == 'done') { $('#tab-'+imgID).remove(); } }, error: function(){} }); }); }); </script> and my view file code is def deleteImageAjxFn(request): if request.method == "POST": imgid = request.POST.get('imageid') print(imgid) try: image = Images.objects.filter(image_shw = int(0), image_cid=imgid).delete() except Images.DoesNotExist: image = None if(image): return HttpResponse('done') else: print(form_add_data.errors) -
'csrf_tokan', expected 'endblock'. Did you forget to register or load this tag?
{%extends 'base.html'%} {% block content%} hellow {{name}} {% csrf_tokan %} Enter 1st number : <input type="text" name="num1"><br> Enter 2nd number : <input type="text" name="num2"><br> <input type="submit"> {% endblock%} -
How to render data from multiple models django
I want to render data to my webpage from my django app however only two of the required slots are being rendered my models are: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True , blank=True) description = models.TextField(max_length=5000, null=True) points = models.DecimalField(max_digits=5,decimal_places=0, null=True) and my views are def admin_dashboard (request): order_list = Order.objects.all() context = {'order':ordersinfo} template = "admin_dashboard.html" return render(request, 'store/admin_dashboard.html', context) my HTML is: {% extends 'store/admin_main.html' %} {% load static %} {% block content %} {% for order in order %} <h6>{{ order.transaction_id }}</h6> <p>{{ order.customer }}</p> <p>{{ order.shippingaddress }}</p> <p>{{ order.orderitem }}</p> {% endfor%} {% endblock content %} 1598061443.212917 userNew which is just the transaction id and user. how can I have all the rest of fields filled -
Update a post in django with unique values in class based views
I am working on blog site and getting this error -->Post with this Post_slug already exists. How can we update the model field with unique=True using class based view. This is my models.py file class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) body = models.TextField() published_date = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField(verbose_name="thumbnail", upload_to='images/') slug_post_url = models.SlugField(verbose_name="Post_slug", unique=True) class Meta: ordering = ['-published_date'] def __str__(self): return self.author.username + ' | ' + self.title_tag def get_absolute_url(self): return reverse('post', kwargs={'slug_for_post': self.slug_post_url}) urls.py file from .views import home, post, PostCreateView, PostUpdateView from django.urls import path urlpatterns = [ path('', home, name="home"), path('post/<slug:slug_for_post>',post,name="post"), path('add-post/', PostCreateView.as_view(), name="addpost"), path('update-post/<slug:slug_for_post>', PostUpdateView.as_view(), name="updatepost"), ] views.py file class PostUpdateView(LoginRequiredMixin, UpdateView): form_class = UpdatePostForm model = Post slug_url_kwarg = 'slug_for_post' query_pk_and_slug = True slug_field = 'slug_post_url' template_name = 'main/create-post.html' # fields = ['title', 'title_tag', 'body', 'thumbnail', 'slug_post_url'] def post(self,request, *args, **kwargs): post = Post.objects.get(slug_post_url=self.slug_url_kwarg) form = self.form_class(request.POST, instance=post) return form def form_valid(self, form): form.instance.author = self.request.user form.instance.published_date = timezone.now() # form.instance.slug_post_url = self.request.POST.get('slug_post_url')3 return super().form_valid(form) -
Auto calculated column based on current & previous row data, that will be used for upcoming rows SQL, Django
Background: An ERP tool that will hold all transaction information like opening balance & amount of transaction and closing balance of a user. The Opening Balance of the current row depends on the previous row's closing balance. The closing balance is calculated based on the addition or subtraction of the opening balance & amount of transaction. This calculated closing balance will be used as the next row's opening balance & further so on. Note: The transaction information like the amount of transaction comes from product purchases that are there in the stock Problem: Consider I have 100 entries. The administrator wants to change the 1st entry's amount of transaction for some reason. Due to this my closing balance of the first row will change. But the problem is all the other 99 rows depend on the first row's closing balance. How to create an SQL table that solves this depending column data problem. PS: I'm using Django as the framework, but Raw SQL query & explanation will also solve my problem to some extent. -
Django Celery schedule task
I am learning Django celery and I trying to run a scheduled task with Django celery. For this, i have written a task to create multiple user that are below: @shared_task def create_random_user(total): for i in range(total): username = 'user_{}'.format(get_random_string(10, string.ascii_letters)) email = '{}@example.com'.format(username) password = get_random_string(50) User.objects.create_user(username=username, email=email, password=password) return '{} random users created with success!'.format(total) and currently the task is running on once i hit a page of a django views that are below: def create(request): create_random_user.delay(10) return render(request, 'test.html') All above these are working very well but i don't like this way to hit a page and create user. I want it should create multiple user on every 12 hours and delete all the user in every 15 hours. I am not getting how can i do it. Can anyone help me in this? Note: My celery setup is working very well, but i am not getting the proccess of schedule task with celery. Can anyone help me in this case? -
Show related data inside foreign key object in django admin
I am creating a school management system. Multiple users/school_owners will create multiple classes according to the number of classes in their school. I am the superuser [i.e. Super Admin] that can access classes in every school. So, I want to link classes of a particular school [i.e. Foreign Key] in particular link. And I'll press that link and the class linked with the foreign key will be display in the list. It should be like this inside admin: School Name 1 ---- Class 1 ---- Class 2 ---- Class 3 ---- Class 4 School Name 2 ---- Class 1 ---- Class 2 ---- Class 3 ---- Class 4 Here school name 1 and school name 2 are the foreign keys value. Inside models.py from django.db import models from accounts.models import school_details class student_class(models.Model): connect_school = models.ForeignKey(school_details, on_delete=models.CASCADE, null=True) class_list = models.CharField(max_length=95) def __str__(self): return self.class_list So, connect_school [i.e. school name] should be display first in the admin and when we click in school name the classes of that particular school should be displayed. Inside admin.py from django.contrib import admin from school.models import student_class # Register your models here. admin.site.register(student_class) This photo denotes how that data is being displayed in an … -
Error while creating virtual environment in Python3.8
virtualenv myvirtualenv I am new to the virtual environment in Python. I was following this tutorial https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/ But got stuck in step 3 The Error I got: Traceback (most recent call last): File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 58, in _install installer.install(creator.interpreter.version_info) File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 116, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 103, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\Vivek\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\setuptools-50.3.1-py3-none-any, has distutils-precedence.pth, easy_install.py, pkg_resources, setuptools, _distutils_hack Traceback (most recent call last): File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 58, in _install installer.install(creator.interpreter.version_info) File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 116, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\vivek\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 103, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\Vivek\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\pip-20.2.3-py2.py3-none-any, has pip``` Thanks in advance -
How Django login and logout functions works under the hood
I want to understand how the login and logout function works, what happens behind the scenes, such as, are database queries performed? This is because I have seen that there is a table called "django_sessions". I've been using django for a year now, but I haven't been able to understand the difference between the terms session, authentication and login. Because, with DRF I've implemented the use of JWT to query my API, then I'd like to know if JWT is an alternative to django's login function and if it's more optimal and I know redis is an option for handling sessions and black listing tokens. -
How to Change Django Homepage with Your Custom Design?
I am trying to change django default homepage with my custom design, but it's not working. I Try a lot but still the same issue, I am not Understanding what is the issue, it's working perfect on my local server, But I am implementing Django app on Live server, Please let me know where I am mistaking. here is my django default urls.py file... from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf import settings from django.urls import path, include from django.conf.urls.static import static from . import views urlpatterns = [ path('mainadmin/admin/', admin.site.urls), url(r'ckeditor/', include('ckeditor_uploader.urls')), url(r'^myadmin/', include('myadmin.urls')), url('', include('homepanel.urls')), path('', views.index, name='index'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Recover user of creation and last modification
I have a model using TimeStampedModel where created and updated is already integrated class Universo(TimeStampedModel): nombre = models.CharField('Universo', max_length=10) class Meta: verbose_name = 'Universo' verbose_name_plural = 'Universos' ordering = ['nombre'] def __str__(self): return self.nombre In the administrator view indicate the user who created and modified it Image Admin In template I can call its attributes with {{u}} {{u.created}} {{u.modified}} But I can't find how to bring the user I think I have made the modification to the template -
Django: Accessing queryset in ModelMultipleChoiceField from template
I'm creating a panel where a user can assign an assignment to other users. I'm attempting to build this with the ModelMultipleChoiceField and a form called AssignedUsersForm forms.py class AssignedUsersForm(ModelForm): class Meta: model = Assignment fields = ['users'] custom_users = CustomUser.objects.all() users = forms.ModelMultipleChoiceField(queryset=custom_users, widget=forms.CheckboxSelectMultiple()) template <form method="post" id="assigned_users_form"> {% csrf_token %} {{ assigned_users_form.errors }} {{ assigned_users_form.non_field_errors }} <div class="fieldWrapper"> {{ assigned_users_form.content.errors }} {% for user in assigned_users_form.users %} <div class="myradio"> {{ user }} </div> {% endfor %} <br> <div style="text-align:center;"> <input class="input-btn" type="submit" value="Save" name='submit_assigned_users_form'> </div> </form> I've successfully rendered each of the options for CheckboxSelectMultiple individually in my HTML. Unfortunately, each iteration of 'user' renders CustomUser object (#) - the default name for the object. From what I understand, the Checkbox widget does not pass the original queryset to the template. Thus, I'm unable to access the model attributes of each user and render information such as name, profile picture, etc. Is there a method of accessing the actual object that's represented in the checklist, instead of the _ str _ value? I've considered running a parallel iteration of queryset in the template, but I'm not sure if that's possible in Django. I've also considered creating custom template … -
Django Rest Framework select_related() error ignored in View
class City(models.Model): pass class Person(models.Model): name = models.CharField(max_length=30) hometown = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True) class Book(models.Model): author = models.ForeignKey(Person, on_delete=models.CASCADE) As I know, __ in selected_related() is only allowed with foreign keys. ex.Book.objects.select_related('author__hometown') I've tried Book.objects.selected_related('auther__name') in django shells and it raises django.core.exceptions.FieldError: Non-relational field given in select_related But same code in DRF View don't raise any errors. It seems like ignored. Is this done by DRF on purpose or did I miss something? -
object is not iterable (Python and Django)
I try to put a html in pdf (I did, but there´s a problem). I get the error on the tittle ('Boletas' object is not iterable), someone know what's the problem here? I really would appreciate the help. Views.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ListaBoletasListView(ListView): model = Boletas template_name = "home/boletas.html" context_object_name = "boletas" class ListaBoletasPdf(View): def get(self, request, *args, **kwargs): boletas = Boletas.objects.all() data = { 'boletas' : Boletas } pdf = render_to_pdf('home/listaBoletas.html', data) return HttpResponse(pdf, content_type='application/pdf') Models class Boletas(models.Model): id_boleta = models.AutoField(primary_key=True) fecha_boleta = models.TextField() # This field type is a guess. precio_total = models.BigIntegerField() rut_persona = models.ForeignKey('Personas', models.DO_NOTHING, db_column='rut_persona') id_pedido = models.ForeignKey('Pedidos', models.DO_NOTHING, db_column='id_pedido') class Meta: managed = False db_table = 'boletas' html file <h1>Boleta</h1> <table border="1"> <thead> <th>Id boleta</th> <th>Fecha boleta</th> <th>precio</th> <th>rut</th> <th>id</th> </thead> <tbody> {% for Boletas in boletas %} <-------- "ERROR" <tr> <td> {{Boletas.id_boleta}}</td> <td> {{Boletas.fecha_boleta}}</td> <td> {{Boletas.precio_total}}</td> <td> {{Boletas.rut_persona}}</td> <td> {{Boletas.id_pedido}}</td> </tr> {% endfor %} </tbody> </table> If I don´t use the for and endfor, there´s no error... sorry if I don´t explain very good to myself -
Problems with paypal server integration
i have some problems with a web im creating. The paid is made and thats work fine, my problem is with only one line of code XD. Im trying to "save" the names of products purchased (in this case is for courses), in a billing and then pass that course to a user-profile so he can gain access to the course. Im very new in python and django, and i know how to do this. first a big resume of my organization in the project: myApp _ apps ______content | | | |_____shopping_cart | | |_ paypal | |_ user ok so my model in content is: class Course(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) thumbnail = models.ImageField(upload_to="courseThumbnails/") publish_date = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) description = models.TextField() price = models.FloatField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #agregar despues un field de recursos para descargar material nose si aca o en video mejor def __str__(self): return self.name def get_absolute_url(self): return reverse("content_app:course-detail", kwargs={"slug":self.slug}) In shopping_ cart model is: from django.conf import settings from django.db.models import Sum from django.db import models from apps.content.models import Course # Create your models here. class OrderItem(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.course.name class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, … -
Django: Convert a QuerySet to a Context dict
I'd like to use a QuerySet within a html email template. How can I convert the Queryset below into a Context? My current solution looks like this: Using Ajax to send a list of pk ('ids') into a Django View to be used to filter a queryset. Convert this queryset into a context Use the context in a html email template (render_to_string) in views.py (I'm using class based ListView). class ProductListSendView(ListView): model = Product template = 'product/email.html' def get(self, request): _req_list = json.loads(request.GET.get('ids', None)) _res = [int(i) for i in _req_list] queryset = super(ProductListSendView, self).get_queryset() qs = queryset.filter(id__in=_res) context = dict(qs.values()) emailSubject = "Subject" emailOfSender = "nnnnnn" emailOfRecipient = 'nnnnnn' text_content = render_to_string('product/email.txt', context, request=request) html_content = render_to_string('product/email.html', context, request=request) try: emailMessage = EmailMultiAlternatives(subject=emailSubject, body=text_content, from_email=emailOfSender, to=[emailOfRecipient,], reply_to=[emailOfSender,]) emailMessage.attach_alternative(html_content, "text/html") emailMessage.send(fail_silently=False) except smtplib.SMTPException as e: print('There was an error sending an email: ', e) error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'} raise serializers.ValidationError(error) return HttpResponse('success') Above results in an error saying context must be a dict rather than QuerySet. -
Large nested hierarchy in Django / Wagtail: parenting or categorizing?
I'm new to Wagtail & Django, and enjoy them much so far. I have a database with 5 columns containing metadata on drugs (medications). 50,000 rows in total. Drugs are ordered hierarchically, with subcategories. For example Insulin is in category A10, where A is the main category and 10 depicts subcategory. Some drugs have two or three subcategories. Example with an insulin follows: A -- A10 ---- Insulin degludec I need to generate one separate page for each drug and present the metadata for that drug on it's specific page. What would be the most effcient way of doing this in wagtail/django? (Ideally I would love to be able to present the tree in a hierarchy taht can be filtered using AJAX, but thats a later problem.) My considerations: Should I create several classes (models) where each class represents a level in the hierarchy. Should they inherit from Page or models.Model, and should the inherent tree structure of wagtail be used or should I define foreignkeys? Should I instead only create posts with the lowest level data (e.g Insulin degludec) and create categories and subcategories that represent the higher order hierarchy? I use Wagtail 2.10, Postgresql and plan to use … -
Django DB migration adds new columns, but do not edit the values already in the table
I have a python script for creating the tables and specifying the values that should be added to it. I use the following two commands to do the migration. python manage.py makemigrations python manage.py migrate This is what happens: When I use the above commands initially (when no tables are there), all the tables are created with correct values in it. After doing the first migration (creating the tables and adding values), if I add a new column to the table in the script, and then run the above commands, the new column is added successfully to the table. However, after doing the first migration (creating the tables and adding values), if I change the values to be added to the table (in the script), and then run the above commands, I get the output "no changes detected". How can I achieve third step mentioned above. I am a newbie to Django so please help me out. -
TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: home.html
Ive been trying to create a new project. The technologies that i am using for the project is python3 and django. Ive just stuck with an error and i can not move forward. The error that i`ve received when i run the server (python3 manage.py runserver) raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: home.html [25/Oct/2020 00:15:56] "GET / HTTP/1.1" 500 73916 I believe this means i am not able access to the template that i`ve been created. I created a "templates" folder under my "users app". The root of the templates folder is in the same root with my project app. I updated my project setting templates as like, 'DIRS': [os.path.join(BASE_DIR, 'templates')], My urls to the path in my project folder urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls')), path('users/',include('django.contrib.auth.urls')), path('',TemplateView.as_view(template_name='home.html'),name='home'), ] My `user app urls.py from django.urls import path from .views import SignUpView urlpatterns=[ path('signup/', SignUpView.as_view(),name='signup'), ] home.html is as like {% extends 'base.html' %} {% block title %} Home {% endblock title %} {% block content %} {% if %} {% if user.is_authenticated %} Welcome {{user.username}}! <p><a href="{% url 'logout' %}">Exit</a></p> {% else %} <p>You are not logged in!!!</p> <p><a href="{% url 'login' %}">Log in</a></p> <p><a href="{% url 'signup' %}">Register</a></p> {% endif …