Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django display data in a one to many relationship
I am trying to display in a one to may relationship but somehow the data doesn't display. With this current code, it can only display the district, villages, and the acknowledgment. Even though on the template, I point render the province name and confederacy but it doesn't display. class Confederacy(models.Model): confederancy_name = models.CharField(max_length=25) def __str__(self): return self.confederancy_name class Provinces(models.Model): confederancy = models.ForeignKey(Confederacy, related_name='province', null=True, default='', on_delete=models.CASCADE) province_name = models.CharField(max_length=25) def __str__(self): return self.province_name class Districts(models.Model): confederancy = models.ForeignKey(Confederacy, related_name='district',null=True, default='', on_delete=models.CASCADE) province = models.ForeignKey(Provinces,related_name='district', null=True, on_delete=models.CASCADE) district_name = models.CharField(max_length=25) def __str__(self): return self.district_name class Villages(models.Model): confederancy = models.ForeignKey(Confederacy, related_name ='village',null=True, default='', on_delete=models.CASCADE) district = models.ForeignKey(Districts, related_name='village', null=True, on_delete=models.CASCADE) village_name = models.CharField(max_length=25) acknowledgement = models.TextField(default='') def __str__(self): return self.village_name def village(request): village =Villages.objects.all() return render(request, 'villages.html', locals()) {% for data in village%} <tr> <td>{{data.confederacy.confederacy_name}}</td> <td>{{data.province.province_name}}</td> <td>{{data.district.district_name}}</td> <td>{{data.village_name}}</td> <td>{{data.acknowledgement}}</td> </tr> {% endfor%} -
How can I translate SQL query to to django ORM
I'm working on making some data consults in Django but I don't understand quite well its ORM system yet. I need to get the transactions' quantity for a particularly transaction's projections. To put it briefly, I want to translate this SQL query to Python/Django syntax: select cp.name, count(*) as total from core_transaction ct inner join core_projection cp on ct.projection_id = cp.id group by cp.name These are the models involved: class Transaction(models.Model): date = models.DateField() projection = models.ForeignKey('Projection', blank=False, null=False, related_name='transactions') class Projection(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=300, blank=True, null=True) -
Django: Why celery can't find app folder in new django, celery version?
Firstly, I referred this but couldn't solve it. Problem is that: celery command can't recognize my app module. >> celery --workdir=super_crawler/ --app=config.celery:app worker Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for "-A" / "--app": Unable to load celery application. While trying to load the module config.celery:app the following error occurred: Traceback (most recent call last): File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/bin/celery.py", line 50, in convert return find_app(value) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/app/utils.py", line 384, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/utils/imports.py", line 107, in import_from_cwd return imp(module, package=package) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' Library versions Django==3.1.2 celery==5.0.1 django-celery-beat==2.1.0 Folder Structure super_crawler_project ├── Dockerfile ├── Makefile ├── super_crawler │ ├── manage.py │ ├── config │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── celery.py │ │ ├── settings.py │ │ ├── urls.py │ │ … -
function dearmor(text) does not exist\nLINE 1: ..._on\" FROM \"users_user\" WHERE convert_from(decrypt(dearmor()
I am using a extension in django https://github.com/dcwatson/django-pgcrypto to encrpt and dcrpt data and when I am doing lookup like Employee.objects.filter(date_hired__gt="1981-01-01", salary__lt=60000) Its giving me errot error message: function dearmor(text) does not exist\nLINE 1: ..._on\" FROM \"users_user\" WHERE convert_from(decrypt(dearmor() I am using PostgreSQL 13.0 and django 3.1 -
Compare products together in django
When I select a product, the next modal displays the same product and I can not select the next product, what should be done so that the choices do not affect each other? I use models and can only make one choice To have. I show two of the following modal to the user so that he can have 2 choices, but he can only have one choice. view : def view(request, id): products = get_object_or_404(Product, id=id) ... is_select = False if request.method == 'POST': product_id = request.POST.get('select') filter = Product.objects.get(id=product_id) is_select = True return render(request, 'home/new.html', {'products': products,...}) template : <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm">Small modal</button> <div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <form method="post" action=""> <div class="row p-5"> {% csrf_token %} {% if category %} {% for img in new_1 %} <div class="col-4"> <input type="radio" {% if products.id == img.id %}checked {% endif %} name="select" value="{{ img.id }}" onchange="this.form.submit();"> </div> {% endfor %} {% else %} ... {% endif %} </div> </form> </div> </div> </div> -
python3 manage.py createsuperuser does not work
when I use python3 manage.py createsuperuser it shows: Username (leave blank to use 'user'): but when i tap enter it doesnt work it shows: Username (leave blank to use 'user'): ^M OR Username (leave blank to use 'user'): user^M the " ^M " appears when I tap Enter. -
Django model_name.item.add(item) add item to all records in the model
I am trying to achieve an order system for an e-commerce site with Django. I have Order Model and OrderItem Model as such class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null = True) def __str__(self): return self.product.name class Order(models.Model): ref_code = models.UUIDField(default=uuid.uuid4, editable=False) items = models.ManyToManyField(OrderItem) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now=True) shipping = models.ForeignKey(AddressAndInfo, on_delete=models.SET_NULL, null=True) is_shipped = models.BooleanField(default=False) price = models.FloatField(default=0.0) And My view function is such: def checkout(request): order_items = OrderItem.objects.filter( owner=request.user).filter(is_ordered=False).all() address = AddressAndInfo.objects.filter(user=request.user).get() if(order_items.count() > 0): total = 0 for item in OrderItem.objects.filter(owner=request.user).filter(is_ordered=False).all(): if item.product.discounted_price > 0: total = total + item.product.discounted_price else: total = total + item.product.price order = Order.objects.create( owner = Profile.objects.get(user= request.user.id), shipping = address, price = total ) new = Order.objects.get(items = None) print(new.ref_code) new.items.add(OrderItem.objects.get(owner=request.user, is_ordered=False)) for item in order_items: item.is_ordered = True item.save() return redirect('dash') else: messages.success(request, 'No item in Cart') return redirect('index') Now the problem here is that when I try to add the second order from the user it adds order-item from the second order to all the existing order and. The result is that all the orders have same … -
Where is /app/hello/templates/db.html located?
I'm new to Heroku and Django and am in the middle of this instruction. As suggested, I put the following URL to my browser: https://xxxx-xxxxx-12345.herokuapp.com/db/ Then, I got this error: TemplateSyntaxError at /db/ 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I googled and found a solution that staticfiles in db.html should be changed to static, so I changed: db.html: {% extends "base.html" %} {% load static %} {% block content %} <div class="container"> <h2>Page View Report</h2> <ul> {% for greeting in greetings %} <li>{{ greeting.when }}</li> {% endfor %} </ul> </div> {% endblock %} However, the error don't go away. Then, I noticed that the contents of db.html is different from mine, which is located under C:\Users\xxxxx\python-getting-started\hello\templates\. In template /app/hello/templates/db.html, error at line 2 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 {% extends "base.html" %} 2 {% load staticfiles %} 3 4 {% block content %} 5 <div class="container"> 6 7 8 <h2>Page View Report</h2> 9 10 11 <ul> 12 ... Where is this file /app/hello/templates/db.html located? I really can't find it. Please … -
Django Rest Framework - Serializer not saving Model that has an ImageField
I have a model of images, Image that have foreign keys on different types of articles. I want to expose this model via a REST interface (built with Django-Rest-Framework) and upload images to it via AJAX calls in Angular 10. Doing File Uploads in general works so far, as I was able to follow this guide here successfully. It does however somehow not work with my ImageModel and ImageSerializer. When I fire my AJAX call at the moment, currently I get a HTTP 500 response on the frontend and this error in the backend in Django: File "/home/isofruit/.virtualenvs/AldruneWiki-xa3nBChR/lib/python3.6/site-packages/rest_framework/serializers.py", line 207, in save 'create() did not return an object instance.' This is a console log of the content of the FormData object I send via AJAX call, which fails for my Image model (Console log was taken by iterating over FormData, as just logging FormData doesn't show its content). Note that bar the image, none of these values are required in the model: Find below the model, the serializer and the view from DRF, as well as my Type-Script POST method to call that API: //Typescript ImageUploadService.ts post method postImage(imageModel: Image, imageFile: File){ const url = `${Constants.wikiApiUrl}/image/upload/`; const formData: FormData = …