Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why leads deletion of UUIDField to Django SystemCheckError
I've been building a Django website and included a UUID field "customer_id" in my initial "Customer" model. Finally, I decided to drop it. But when I try to delete it from my models.py, Django throws SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'. Here is the code of models.py from django.db import models import uuid # Create a base model to make sure we keep track of creation and edits class ModelBaseClass(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) date_modified = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True # Create your models here. class Customer(ModelBaseClass): customer_id = models.UUIDField(default=uuid.uuid4, #this is the field i try to drop editable=False, unique=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name What I tried so far: I suspect that this could be related to existing data or some other dependencies. So... I deleted the sqlite database, deleted all migration files and ran "python manage.py makemigrations" and "python manage.py migrate". I ran python manage.py flush. I also tried to change the editable=False to editable=True and migrate before dropping, but it didn't change anything. It's perhaps also … -
django query set how to get last n records
class Message(models.Model): host = models.ForeignKey(NewUser, on_delete=models.CASCADE) body = models.TextField(max_length=1000) created = models.DateTimeField(auto_now_add=True) class Comments(models.Model): message = models.ForeignKey(Message, on_delete=models.CASCADE) publisher = models.ForeignKey(NewUser, on_delete=models.CASCADE) body = models.TextField(max_length=300) created = models.DateTimeField(auto_now_add=True) I have this app where i want to display in template last 5 comments for every message. How can i get last n comments that matches to specific message? I've tried: comments_all = Comments.objects.all().order_by('-id')[:5] but it just returns 5 last comments regardless of message. -
How can I undo this (accidental) table inheritance in Django?
I've got a django app library in production, and have found a major flaw. The library declares AbstractMyModel from which a concrete MyModel inherits. Users of the library can choose to install the app and use MyModel directly, or just import the abstract models to do their own thing with. The problem is that AbstractMyModel isn't abstract. I forgot to include a class Meta() declaring abstract=True. So I basically have a table inheritance in production: class AbstractMyModel(models.Model): """Abstract model... EXCEPT IT'S NOT!!!""" name = models.SlugField( help_text="name", unique=True, ) class MyModel(AbstractMyModel): """ARGH - the abstract one isn't actually abstract But I've got this in production - there are two actual tables from AbstractMyModel and MyModel. How can I sort this mess out?""" QUESTION: How would I migrate my way out of this, to collapse the inheritance and end up with the MyModel table as concrete and AbstractMyModel as truly abstract? TIA! -
Django - Register m2m in admin
Facing some troubles with m2m in inline. class Task(models.Model): title = models.CharField(...) performer = models.ForeignKey(User, ...) for_control = models.ManyToMany('self', ...) class TasksForControlInline(admin.TabularInline): model = Task.for_control.through fk_name = 'from_task' show_change_link = True # not displayed because m2m is not registered in admin I cannot add task for control in inline. Is it possible to register m2m in admin? -
How to pass parameters delete method? (django)
I have model Like and want to delete this object with parameters. it's code -> Like.objects.filter(user=self.request.user, question=self.get_object()).delete() and also I have signal @receiver(post_delete, sender=Like) def delete_like(sender, instance, using, **kwargs): instance.question.point -= 1 instance.question.save() I want something like that Like.objects.filter(user=self.request.user, question=self.get_object()).delete(status="Testing") and after using this status while deleting -
Password reset django-allauth and django-rest-auth
I cannot wrap my head around this problem. Read a lot of solutions but cannot seem to find the correct combination that works for me. I want to initiate a users password reset flow from within my (android/iOS) app. I think I need django-rest-auth for this to expose an API endpoint something like this: from rest_auth.views import PasswordResetView urlpatterns = [ path('password/reset/', PasswordResetView.as_view(), name='rest_password_reset'), ] Now posting to http://127.0.0.1:8000/password/reset/ with a JSON payload of { "email": "test1@test.com" } gives an error: django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. Now, I'm strugeling with the next part. I found that password_reset_confirm is defined in django.contrib.auth but I do not want to expose the admin-like interface to the user. I'd like to use the allauth PasswordResetFromKeyView. So, defining password_reset_confirm as: path('password/reset/<uidb64>/<token>/', PasswordResetFromKeyView.as_view(), name='password_reset_confirm' ), Works. An email is send containing a reset URL. But now, following that URL I'm getting another error: PasswordResetFromKeyView.dispatch() missing 2 required positional arguments: 'uidb36' and 'key' Ok, obvious, changed the password_reset_confirm path arguments from <uidb64> and <token> to <uidb36> and <key>. Than the error moves to password_reset_email.html because of the arguments in {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Ok, also changed that to uidb32=uid and … -
Django - Update database value on drag and drop
I am creating TODO app, and I am trying to implemnt drag and drop using JavaScript. I managed to create drag and drop feature but I don't know how to change and save tasks "category" (for example backlog to done) on drop. Do I need to use JavaScript or is there some Django library that can help me? If JS is necessary, what should I do? -
how to give parameters when connecting to different webpages in django framework
I'm trying to link two webpages in django framework, using anchor tags in template. One of my view takes an argument and I can't figure out how to pass a parameter in template. This is a url pattern that takes argument. path("<str:entry>",views.display_entry,name="entry") corresponding view is: def display_entry(request,entry): text = str(util.get_entry(entry)) markdown = Markdown() html = markdown.convert(text) html_file = open(f"encyclopedia/templates/encyclopedia/{entry}.html",'w') html_file.write(html) html_file.close() return render(request, f"encyclopedia/{entry}.html") and template where I'm trying to access this view is - <ul> {% for entry in entries %} <li><a href="{% url 'encyclopedia/entry' %}">{{ entry }}</a></li> {% endfor %} </ul> -
js spread operator syntax error django compressor
Im trying to configure the ifs.js library in my project, it uses rollups, and I found django compressor to bundle files, but I got an error of syntax, not really sure whats wrong, everything is configured ok, and I got this error CommandError: An error occurred during rendering b_proy/prueba_ifc.html: SyntaxError: /home/fcr/anaconda3/envs/gda/a_viurb/a_viurb/static/ifc/bundle.js: Unexpected token (87230:6) 87228 | throw new Error(nullIfcManagerErrorMessage); 87229 | const modelConfig = { > 87230 | ...config, | ^ 87231 | modelID: this.modelID 87232 | }; 87233 | return this.ifcManager.createSubset(modelConfig); it is the spread operator, it seems the compressor doesnt recognize it, I saw other similar questions and the answer was to not minify the js code, but in my case is a 2mb js file, so I really hope there's another way to solve this, thanks -
django_tables2 mixins, display non-joinable models with concatenated rows
For some contrived reason I have two QuerySets which match up in row-order, but don't have a shared foreign key, so a join is not possible. I don't have the ability to add a key here, so I'd like to do a "hstack" of the two results and display as a table. This is easy with jinja templating, but I'd like to use the convenience functions of tables2 (e.g. sorting, etc) and I would like to still retain the ability to do foreign key traversal on each queryset. Equivalently, consider providing a QuerySet and a list of external data that is the result of an operation on that QuerySet. qs = ModelA.objects.filter( ... ) # queryset ext_data = get_metadata_from_elsewhere(qs) # returns a list of dict # len(qs) == len(ext_data) For example, with two models I can create a Mixin: class ModelATable(tables.Table): class Meta: model = ModelA class ModelBTable(ModelATable, tables.Table): class Meta: model = ModelB Which produces a rendered table with the fields from both models. If I supply ModelBTable(query_model_b) then only those fields are displayed as expected, and similarly for ModelBTable(query_model_a). How do I provide both query_model_a and query_model_b? Also if there's an easy way to do hstack(query_a, query_b) then … -
Conflict on Python Django API Deployment
Please, i'm very new to Python and Django, a friend (non developer) reached out to me on deploying django on digitalocean. I've tried troubleshooting some of my issues but dont understand how to solve the latest one: The conflict is caused by: The user requested Django==2.2.16 django-cors-headers 3.2.1 depends on Django>=1.11 django-filter 2.0.0 depends on Django>=1.11 django-phonenumber-field 4.0.0 depends on Django>=1.11.3 django-rest-knox 3.0.3 depends on django django-rq 2.3.2 depends on django>=2.0 djangorestframework 3.11.1 depends on django>=1.11 drf-yasg 1.20.0 depends on Django>=2.2.16 django-rest-logger 1.0.4 depends on Django<=2.2 and >=1.11 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies ERROR: failed to build: exit status 1 I've tried visiting the address but dont know what to do with the information given. Please, help me out -
Create Dockerfile , docker-compose.yml , and nginx-setup.conf file for a Django and Next.js project
I want to create a Dockerfile , docker-compose.yml and a nginx-setup.conf file for my Django GraphQL and Next.js project in order to make it run on localhost on my machine then to make it ready to deploy it on DigitalOcean. I'd also like to add PostgreSQL too. How can I do all of that ? Here is what I've tried by now : Dockerfile for Django : FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /backend COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . Dockerfile for Next.js : FROM node:16.14-alpine WORKDIR /frontend COPY . . RUN npm install CMD [ "npm", "run", "dev" ] Nginx setup file : server { listen 8080; location / { root /var/www/frontend } } docker-compose.yml file : version: "3.9" services: backend: build: context: ./backend command: gunicorn app.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" depends_on: - frontend frontend: build: context: ./frontend dockerfile: Dockerfile volumes: - .:/frontend - /frontend/node_modules ports: - "3000:3000" nginx: image: nginx:latest ports: - 80:8080 volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - nextjs_build:/var/www/frontend depends_on: - backend - frontend Now I know that something is off or missing , but I don't really know what is it , plus I haven't added yet the image for postgresql. -
Is there any alternative to force_bytes by django.utils.encoding?
I've been using force_bytes in one of my projects, and it is causing errors since I am using Django 3+. Question: Is there any alternative to it? What Force Bytes Does? Gives bytestring version of string with lazy instances resolved to strings -
Questions about inclusion_tag
I was follow to a old courses Udemy and I try create a project had 2 app( group & posts) and just found out that you can use: from django import template register = template.Library() To allow link models app to another app. In the old courses it just add in models.py and create tag in post_list.html to show what group you join and all group but don't create templatetags folder and how it work. Even when I check the sample it don't had any thing. So I was search gg try build it by myself, but it doesn't show anything Can you check it. Thank App groups models.py class Group(models.Model): name = models.CharField(max_length=235, unique=True) slug = models.SlugField(allow_unicode=True,unique=True) descripsion = models.TextField(blank=True,default='') descripsion_html = models.TextField(editable=False,default='',blank=True) member = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args, **kwargs): self.slug =slugify(self.name) self.descripsion_html = misaka.html(self.descripsion) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username In templatetags group_tags.py from django import template from ..models import Group,GroupMember register = template.Library() @register.inclusion_tag('clonemedia/posts/templates/posts/post_list.html') def get_other_group(): group_members = GroupMember.objects.all() other_groups = Group.objects.all() return {'other_group':other_groups, 'group_member':group_members } In template post_list.html {% load group_tags %} <h5 class='title'> Your Groups</h5> <ul class='list-unstyled'> … -
Django KeyError and MultiValueDictKeyError when trying to POST
I am trying to do a POST request to Django through Vue JS, this POST request is a review to a city, When I try to POST through Vue JS I get no response so I tried using the Django API directly and each time I get the same error MultiValueDictKeyError The way I'm trying to POST this request is that each Review is connected to a specific City so I have to attach the city ID to it so I can pass to that City through the API. This is my views.py file: from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import City, Review from .serializers import CitySerializer, ReviewSerializer from rest_framework.parsers import FormParser, MultiPartParser, JSONParser from django.http import HttpResponse class LatestCityList(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, request, format=None): cities = City.objects.all() serializer = CitySerializer(cities, many=True) return Response(serializer.data) def post(self, request, format=None): Name = request.data['Name'] Picture = request.data['Picture'] Description = request.data['Description'] slug = Name.lower().replace(' ', '_') City.objects.create(Name=Name, Picture=Picture, Description=Description, slug=slug) return HttpResponse({'message': 'City created successfully'}, status=201) class CityDetail(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, request, slug, format=None): city = City.objects.get(slug=slug) serializer = CitySerializer(city) return Response(serializer.data) class CityReviewList(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, … -
Django Change boolean field with click
I am working on a To-do app. The individual to-dos reference a to-do list via a foreign key and the to-do lists reference a project via a foreign key. I want the to-do's status to be set to true when clicked. I have seen some tutorials where this is done but I haven't been able to get this to work yet. Here are the models: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse ('project_detail', args=[str(self.id)]) class ProjectTodoGroup(models.Model): title = models.CharField(max_length=250) description = tinymce_models.HTMLField() project = models.ForeignKey(Project, blank=True, on_delete=models.CASCADE, related_name='todo_group') date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title class ProjectTodo(models.Model): title = models.CharField(max_length= 250) notes = tinymce_models.HTMLField() status = models.BooleanField(default=False) projectgroup = models.ForeignKey(ProjectTodoGroup, blank=True, null=True, on_delete=models.CASCADE, related_name='todo_set') date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title The view: model = ProjectTodo fields = ['status'] def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context def get_success_url(self): return reverse('company_project:todo_group_detail', args=[self.kwargs.get('pk'), (self.object.id)]) Everything I have tried to far with the view hasn't worked. The template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% … -
How to deal with unsaved nested models in serializer?
My input is a JSON object that represents a video channel. It has some simple fields and fields that contain an array e.g. tags. What I want to accomplish is parse the JSON, turn it into a Channel model object that a tags property with a list of Tag model objects. I set it up as a many to many relationship. Tag has only 1 field: title, but the JSON input is an anonymous array like "tags": ["tag1", "tag2",...]. On channelSerializer.is_valid(), it fails. Hacking around, I converted the input from "tags": ["tag1"] to "tags": ["title": "tag"] which worked but I don't like hacky solutions. I'm at a point of making a service, pull out tags, create a channel objects, convert tags independently and add it to channel...but I feel I'm missing a better, standard method. What is the recommended approach for this situation in Django? Code that definitely has some issues: class Tag(models.Model): title = models.CharField(unique=True, null=True, blank=True, max_length=255) class Meta: db_table = "tag" class Channel(models.Model): tags = models.ManyToManyField(Tag) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['title'] def create(self, validated_data): return Tag.objects.create(title=validated_data) class ChannelSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, read_only=False, required=False) class Meta: model = Channel fields = '__all__' -
Wrong name format. Got uploads\385757.jpg ; should be <app>.<model>/<content_field>/<mimetype_field>/<filename_field>/<filename>
I have a problem with my django project I have a form where I need load the next fields: Driver Carnet Number Driver Name Driver photo But when i load the image I have the problem, and watched the django documentation and I couldn't solve it. My model class is the next class Conductor(models.Model): ci = models.CharField(max_length=30, null=False) nombre_apellido = models.CharField(max_length=50,null=False) #para la imagen imagen = models.ImageField(upload_to='uploads') My form class class CrearConductorForm(forms.ModelForm): def __init__(self, *args, **kwargs): #user = kwargs.pop('alloweduser', None) super(CrearConductorForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['autocomplete'] = 'off' self.helper = FormHelper() self.helper.form_tag = False self.helper.form_class = 'form-horizontal' self.helper.label_class = 'm-1 col-md-3 create-label' self.helper.field_class = 'm-1 col-md-6' class Meta: model = Conductor fields = ['ci', 'nombre_apellido', 'imagen'] labels = { 'ci': ('Cédula de Identidad '), 'nombre_apellido': ('Nombre y Apellido '), 'imagen' : ('Foto del conductor'), } My view function def crear_conductor(request): if request.method == 'POST': form = CrearConductorForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse_lazy('mantenimiento:ListaConductores')) else: form = CrearConductorForm() return render(request, 'mantenimiento/CrearConductor.html', {'form' : form}) My HTML in the form tag <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <div class="row"> <div class="col-sm-6"> <button type="submit" class="btn btn-sm btn-success">Guardar</button> </div> <div class="col-sm-2 offset-sm-4"> <a class="btn btn-sm btn-danger" … -
is there a way for me to connect my html form to my Modelform
so I have a pre-built HTML form and I will like to connect the HTML form to my Model form in such a way that I will have my normal styling and don't have to render the Django form on the frontend this is the model.py class Property(models.Model): home_types = ( ('BG', 'Bungalow'), ('DP','Duplex'), ('AP','Apartment'), ('MN','Mansion'), ('VA','Villa'), ('CO','Condo'), ) list_types = ( ('FS', 'For Sale'), ('FR','For Rent'), ) property_name = models.CharField(max_length=250, default='e.g 19 Queens Ave, Encino') property_location = models.CharField(max_length=250, default='e.g 19 Queens Ave, Encino') list_type = models.CharField(max_length=2, choices=list_types, default= 'For Sale') price= models.DecimalField(max_digits=13, decimal_places=2) home_type = models.CharField(max_length=2, choices=home_types, default= 'Bungalow') property_id = models.UUIDField(primary_key=True, default=uuid.uuid4) bedrooms = models.IntegerField(default=0) bathrooms = models.IntegerField(default=0) garage = models.IntegerField(default=0) lot_size = models.IntegerField(default=0) images = models.ImageField(upload_to='property_images') description = models.TextField(max_length=600) built_on = models.DateTimeField(null=True) listed_on =models.DateTimeField(auto_now_add=True, auto_now=False, null=True) property_link = models.URLField(max_length=150, null=TRUE) def __str__(self): return self.property_location I need to find a way to submit data to the model database without changing the frontend design here is the add listing frontend link http://realtinic.com/add-listing -
Group results of queryset
I have a function that returns projectName, QuestionnaireTitle, and finalScore The function loops through every project and every questionnaire. I’m trying to format the data so that I end up with a list or a dict that contains the projectName and the scores for each questionnaire so that i can pass this into a JSChart. The format of the chart is: name: 'Project Name', data: [5,8,4,7,2,5,5,7] My current queryset is returning: {'q_rounded': 100, 'title': 'Product Evaluation', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 100, 'title': 'Community', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 100, 'title': 'Marketing', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 0, 'title': 'Product Evaluation', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Community', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Marketing', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Product Evaluation', 'project': <Project: E>} {'q_rounded': 0, 'title': 'Community', 'project': <Project: E>} {'q_rounded': 0, 'title': 'Marketing', 'project': <Project: E>} Is there a way to group the results so that I have: ProjectC,5,5,5 ProjectD ... ProjectE ... for project in all_projects: for q in questionnaires: print("getting ", q.title, "responses for", project.name, project.id) if ProjectQuestionnaireResponse.objects.filter(project_name_id=project.id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project.id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / … -
What is the better way to do a join query with related in Django
I have these three tables, Food, Template and CustomUser: class Food(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, default=1, on_delete=models.CASCADE, related_name="%(class)s_food", ) The template model class Template(models.Model): template_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) The user model class CustomUser(AbstractUser): first_name = models.CharField(max_length=191, null=False, unique=True) To get user's templates, I do this: self.request.user.templates.all() What I want to do is get the templates alongside the Food instances using a given template. I don't mind restructuring the models for a better way to achieve this. -
Created Field(DateTimeField) auto_now_add=True is not working in Abstract Class in Django
class TimeStampMixin(models.Model): id = models.CharField(max_length=60,editable=False,primary_key=True,default=generate_unique_id) created = models.DateTimeField(editable=False) modified = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.id: print("SAVING WHILE CREATE") self.created = timezone.now() print("MODIFY WHILE UPDATE") self.modified = timezone.now() return super().save(*args, **kwargs) class Meta: abstract = True class Sport(TimeStampMixin): name = models.CharField(max_length=100, unique=True) image = models.ImageField(upload_to=path_and_rename,null=True,blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.name = self.name.upper() return super(Sport, self).save(*args, **kwargs) Explaination I have created an abstract model TimeStampMixin with custom save method. Then i have inherited from TimeStampMixin model to Sport Model. Now whenever i'm creating Sport object it raising django.db.utils.IntegrityError: null value in column "created" of relation "events_sport" violates not-null constraint DETAIL: Failing row contains (id, Test, image,2022-04-10 13:30:00+00, 2022-04-10 14:30:00+00, 2022-04-10 12:00:00+00). Also Custom save method from timestampmixin not called. (Not print Anything). Solution I need: While updating an object created field is also get updated. auto_now_add=True in datetimeField attribute is not working!!. How to prevent this? -
How to center form fields with bootstrap and django
<form class="text-center mt-5" action="{% url 'add' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="row col-md-3 mx-auto mb-3"> {{field}} {% if not field.field.required %}<span class="text-light w-25">(optional)</span> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Add</button></form> So what happens is that the button is centered but the fields are a little to the left. how do I make it so that the fields are centered and the (optional) span goes next to the ones that it has to go next to. -
Multiple update using RAW SQL in Django
I have a situation in Django where I need to update multiple rows in a database using RAW SQL, because it is a table created on another system and not managed by the ORM. Since there are multiple rows to be updated, is it possible to run a single command that updates all things at once without having to include a cursor.execute(SQL,params) inside a for loop? At the moment, I was only able to get this update to work correctly by including each update line inside a for loop, but I don't think it's a good practice. It's working something like this: person_list=[[john,33,50],[mary,20,41],[peter,12,93]] with connection.cursor() as cursor: for item in person_list: SQL="UPDATE PERSON SET NAME = %s, AGE = %s WHERE PERSON_ID = %s" params.extend([item[0], item[1], item[2]]) cursor.execute(SQL,params) I would like Django to run a single SQL command like this: SQL+=""" update person name='john', age='33' where person_id=50; update person name='mary', age='20' where person_id=41; update person name='John', age='12' where person_id=93; """ cursor.execute(SQL) I tried to do as follows, but without success, with error message "ORA-00933:SQL command not properly ended": for item in person_list: SQL+="UPDATE PERSON SET NAME = %s, AGE = %s WHERE PERSON_ID = %s; " params.extend([item[0], item[1], item[2]]) with … -
Why I can't save values in database? Django
I want to save my form in database, but save() doesn't work. When I do this, error wasn't showing. At the start, I think problem was in database, but it isn't views.py def comments(request): comments = Comment.objects.all() form = CommentForm() context = {"comments": comments, "form": form} if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.avtor = request.user comment.save() return HttpResponseRedirect(reverse('comment')) else: context["form"] = form return render(request, "home/comments.html", context) else: return render(request, "home/comments.html", context) And models. So, I think problem yet in views.py. I bad know how function save() is working. models.py class Comment(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE) def __str__(self): return 'Comment {} at {}'.format(self.avtor, self.date) class Meta: ordering = ["-id"] forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ("Text",) At the last, I want to save avtor, text and Date. Help me please.