Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR "grpc_status": 14. from client when trying to make request to server inside Docker
i use django grpc framework for the server and fastapi for the client. It all work well in local by starting it one by one. But when i try to use Docker somehow (i think) the client can't establish a connection. Here is the code for the client: from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import grpc from blog_proto import post_pb2, post_pb2_grpc channel = grpc.insecure_channel('grpc_service:5000') stub = post_pb2_grpc.PostControllerStub(channel) class Delivery(BaseModel): id: int title: str content: str app = FastAPI() origins = [ "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") async def init_grpc(): channel = grpc.insecure_channel('grpc_service:5000') stub = post_pb2_grpc.PostControllerStub(channel) @app.post("/delivery/") async def create_item(delivery: Delivery): return delivery @app.get("/delivery/{id}") async def get_item(id: int): response = stub.Retrieve(post_pb2.PostRetrieveRequest(id=id)) return { "id": response.id, "title": response.title, "content": response.content } code for docker-compose: --- version: '3.9' services: db: image: postgres ports: - "8888:5432" environment: POSTGRES_DB: grpc POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - postgres:/var/lib/postgresql/data pgadmin: image: dpage/pgadmin4:latest environment: PGADMIN_DEFAULT_EMAIL: lawteam@gmail.com PGADMIN_DEFAULT_PASSWORD: lawteam PGADMIN_LISTEN_PORT: 80 ports: - 15432:80 volumes: - pgadmin:/var/lib/pgadmin depends_on: - db grpc_service: container_name: grpc_service build: context: ./tutorial dockerfile: Dockerfile command: > bash -c "python /code/manage.py makemigrations && python /code/manage.py migrate && python /code/manage.py grpcrunserver 0.0.0.0:5000" # volumes: # … -
Django: how to make simple calculation using django python?
i am building a LMS using django and i want students to keep track of thier progress while learning, in that case i want users to mark a lesson as done. Now, the problem is how to calculate the total lesson, despite the number of lessons, them get a result of 100%, even if the lesson count is 4 or even 10, i just want to arrive at 100% when the whole lesson is marked as complete i have tried this views.py def trackProgress(request): progress = 100 - round(((total_unanswered_questions - 1) / total_questions) * 100) where i would display the progress <div role="progressbar" data-aos="slide-right" data-aos-delay="200" data-aos-duration="1000" data-aos-easing="ease-in-out" style="width: 15%" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"> this is the model for the lesssons class Video(models.Model): title = models.CharField(max_length = 100 , null = False) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="videos") serial_number = models.IntegerField(null=False) hour = models.IntegerField(null=True, help_text="Enter course hours e.g: 3h") minutes = models.IntegerField(null=True, help_text="Enter course minutes e.g: 23m") video_id = models.CharField(max_length = 100 , null = False) is_preview = models.BooleanField(default = False) NOTE: i also have a model Course where the Video Model is a foreignKey to I also have this model that stores the courses a user have … -
How to count download hit in Django admin
I am newbie for Django admin. I have made little site where I am giving option to user to upload some mp3 files.for that I am using Django file upload. I have html page for showing all those files where I have option to download it by clicking on download symbol. I want to count on every download. I have added filed in my table to keep it's record. My html file where I want to count hit. <th scope="row" style="vertical-align: middle;"> <a href="{{radio_file.audio_file.url}}" download > <i class="fas fa-download mr-2 text-danger"></i></a>&nbsp; </th> <td>{{ radio_file.download_count }} </td> models.py class RadioFile(models.Model): audio_file = models.FileField( upload_to='radio/', validators=[validate_file_extension], max_length=255, help_text="Only wav,mp1,mp2,mp3,m4p,.m5p,wma and voc files are allowed.", ) category = models.ForeignKey( Category, related_name='radio_files', on_delete=models.SET_NULL, null=True, ) trending = models.BooleanField( default=False, help_text="Tick if you want to show it on Home Page",verbose_name="Feature" ) download_count = models.PositiveIntegerField(default=0, blank=False,null=False) uploaded_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='radio_files', on_delete=models.CASCADE, ) uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Django base template didn't work when delete one 'include'
When i delete one of includes (Marked in code) my application didn't work properly. I have side bar and when i delete my nav bar, side bar stops scrolling. I have this code (base template) why this happens? When i don't touch 'include' all is good and working but when i delete som of includes imidiatelly something brokes :( <!DOCTYPE html> <html lang="en"> <head> <title> <!-- title bla bla bla --> </title> <!-- meta and links bla bla bla --> </head> <body class=""> <!-- [ Pre-loader ] start --> <div class="loader-bg"> <div class="loader-track"> <div class="loader-fill"></div> </div> </div> <!-- [ Pre-loader ] End --> {% include 'includes/sidebar.html' %} {% include 'includes/navigation.html' %} <!-- DELETE THIS LINE --> {% include 'includes/header-user-list.html' %} {% include 'includes/header-chat.html' %} {% block content %}{% endblock content %} {% include 'includes/scripts.html' %} <!-- Specific Page JS goes HERE --> {% block javascripts %}{% endblock javascripts %} <script src="{{ ASSETS_ROOT }}/js/menu-setting.js"></script> </body> </html> -
AJAX only picks first element id in a DJANGO loop
AJAX only picks first element id in a DJANGO loop. Wherever I click the "edit" button it brings the first post content. I've just similar metholodogy in other functions (for example a like button) but in this one I don't really see what it only picks the top element of the loop in every template. Please help. This is what I came up with so far: //Edit $('.editfunction').click(function(){ event.preventDefault() var post_pk; var content = $('.textarea_edit').val(); post_pk = $(this).data("post_pk"); $.ajax({ type: "POST", url: `/post/${post_pk}/edit`, data: { csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, post_id: post_pk, textarea: content }, success: function(data) { $('.modal-edit').modal('hide') var content = $('.textarea_edit').val() $(`.post-object-content${post_pk}`).html(content) } }) }) -
When is necessary to create a new app (with startapp) in Django?
Ive found this question, but the answer was from 2008, and I couldnt find any current answer, so I wanted to know if there is a good place to find current information about it, or if you have any advice about it I would be very grateful. -
Why IntegrityError, UNIQUE constraint failed when updating django model?
I'm using Django 4.0.5 and I'm trying to save a youtube video model and then download its thumbnail. When I update the model with the thumbnail it gives me IntegrityError but I can't understand why. models.py class YoutubeVideo(models.Model): title = models.CharField(max_length=255) description = models.TextField() json_info = models.TextField(default='{}') slug = models.SlugField() thumbnail_url = models.CharField(max_length=255) video_url = models.CharField(max_length=255) thumbnail = models.ImageField(upload_to=get_path_yt, null=True, blank=True) video = models.FileField(upload_to=get_path_yt, null=True, blank=True) added_at = models.DateTimeField(auto_now=True) added_from = models.ForeignKey(User, on_delete=models.CASCADE) def download_thumbnail(self) -> None: request = requests.get(self.thumbnail_url, stream=True) if request.status_code != 200: raise ValueError('Invalid thumbnail url') img_temp = NamedTemporaryFile() img_temp.write(request.content) img_temp.flush() file_name = self.thumbnail_url.split('/')[-1] self.thumbnail.save(file_name, File(img_temp.file)) img_temp.close() @staticmethod def create_from_url(url: str, request: Any) -> Any: youtube_video = YoutubeVideo(**get_video_info(url)) youtube_video.added_from = request.user youtube_video.save() youtube_video.download_thumbnail() return youtube_video Error UNIQUE constraint failed: youtube_archive_youtubevideo.id If I save the model only once after downloading the thumbnail it works but I need to do it at two different times. -
SUBMIT button for Django Modal Forms not working, no url to direct to
So, I am trying to add data into a db with the usage of a modal, for this, I am using django-bootstrap-modal-forms. I followed the steps on the manual, step by step and I finally made it work. Well, everything except the buttons on the modal. First, to dismiss data, it had to be data-ds-dismiss instead of the data-dismiss appearing on the code, but that's fine. The only thing that I cannot get to work is the CREATE button, to add data to the database. Here is my code (which is pretty much what appears on the site previously mentioned): #contform.html <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create new contract</h5> <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Create</button> </div> </form> What appears on my console is django.core.exceptions.ImproperlyConfigured: No url to direct to and yes, it makes sense bc Im not adding any … -
Django CRUD functionality after changed model
I was building the CRUD-functionality with create_project_old, update_project, update_project. Then I slightly switched my models.py and create_project_new view but I unfortenatly do not really know how I have to change my update_project and delete_project views now. I have also posted my new models.py and forms.py. Thanks! views.py def create_project_new(request): form = ProjectForm() form2 = ProjectImageForm() if request.method == 'POST': form = ProjectForm(request.POST) form2 = ProjectImageForm(request.POST, request.FILES) images = request.FILES.getlist('image') if form.is_valid() and form2.is_valid(): title = form.cleaned_data['title'] describ = form.cleaned_data['describtion'] price = form.cleaned_data['price'] project_instance = Project.objects.create( title=title, describtion=describ, price=price) print(project_instance) for i in images: ProjectImage.objects.create(project=project_instance, image=i) return redirect('projects') context = {'form': form, 'form2': form2} return render(request, 'projects/project_form.html', context) def create_project_old(request): profile = request.user.profile form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() return redirect('account') context = {'form':form} return render(request, 'projects/project_form.html', context) @login_required(login_url='login') def update_project(request, pk): profile = request.user.profile project = profile.project_set.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST': form = ProjectForm(request.POST, request.FILES, instance=project) if form.is_valid(): form.save() return redirect('projects') context = {'form':form} return render(request, 'projects/project_form.html', context) @login_required(login_url='login') def deleteProject(request, pk): profile = request.user.profile project = profile.project_set.get(id=pk) if request.method == "POST": project.delete() return redirect('account') context = {'object':project} return render(request, 'delete_template.html', context) models.py … -
Avoid duplication in Django for loop with a many to many relationship
My goal is to list the tag_titles for each note created. I am having issues because the tag_title and note are linked through a Many to Many relationship. How I would normally do this is: {% for note_tag in note_tags %} {% if note_tag.note == note %} {{note_tag.tag_title}} {% endif %} {% endfor %} However, because tag_title has a many to many relationship with NoteModel, note_tag.note gives out notes.NoteModel.None My models.py are as follows: class NoteModel(models.Model): note = models.CharField( max_length = 5000, ) note_title = models.CharField( max_length = 500, blank = False, null = True, ) project = models.ForeignKey( IndividualProject, on_delete=models.CASCADE, related_name = "note_projects", blank = False, null = True, ) tag = models.ManyToManyField( 'NoteTagModel', related_name="tags", blank= False, through = "TaggedModel" ) def __str__(self): return f"{self.note_title}" class NoteTagModel(models.Model): note = models.ManyToManyField( 'NoteModel', related_name="tag_notes", blank= False, through = "TaggedModel" ) tag_title = models.CharField( max_length = 200, default = "General", ) def __str__(self): return f"{self.tag_title}" class TaggedModel(models.Model): note = models.ForeignKey(NoteModel, on_delete = models.CASCADE) tag = models.ForeignKey(NoteTagModel, on_delete = models.CASCADE) def __str__(self): return f"{self.note} | {self.tag}" class TagCommentaryModel(models.Model): tag_title = models.ForeignKey( NoteTagModel, on_delete=models.CASCADE, related_name="tag", blank = False, null = True, ) tag_commentary = models.CharField( max_length = 5000 ) def __str__(self): return f"Tag: {self.tag_title} … -
Querying a Django model and comparing its fields for similarities or near duplicates
I have a model that records changes to other models in my database. I would like to query for changes that only add a newline character -- \n. My changes model looks like this: class Change(models.Model): object_type = models.ForeignKey( ContentType, related_name="object_change_set", on_delete=models.CASCADE, ) object_id = models.CharField(max_length=255, db_index=True) object = GenericForeignKey("object_type", "object_id") old_fields = models.JSONField(encoder=JSONEncoder, null=True, blank=True) new_fields = models.JSONField(encoder=JSONEncoder, null=True, blank=True) Essentially, I want to find instances of Change where the difference between a value for a key in old_fields and new_fields is \n. Here's what new_fields look like: { "body": "Had a great time on Wednesday.", "created": "2022-06-15T19:49:06.784Z", } And similarly, old_fields: { "body": "Had a great time on Wednesday.\n", "created": "2022-06-15T19:49:06.784Z", } Note that new_fields and old_fields are both JSONFields. Ultimately, I want to remove the Change instances that only add \n to the body. I realize that I could do this by iterating over the queryset and looking for these discrepancies, but I'm wondering if there's a more elegant solution. -
While, not looping in Python
I'm trying to make a rock paper scissors game with rounds. I'm using a while loop but it doesn't go back to the beginning. I've tried declaring the variables inside of the while, outside, and many other things, but it just doesn't work. I'll leave the code here. Thanks for the help! import random computer_win = 0 user_win = 0 jugadas = 0 def play(computer_win, user_win, jugadas): while (jugadas < 3): user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: ") computer = random.choice(['r','p','s']) if user == computer: jugadas = jugadas + 1 return( f'It\'s a tie. Round {jugadas}/3') if is_win(user, computer): user_win +=1 jugadas = jugadas + 1 return( f'You won! Round {jugadas}/3') else: computer_win +=1 jugadas = jugadas + 1 return( f'You lost! Round {jugadas}/3') if computer_win >2 or user_win>2: if computer_win > user_win: "The computer won" elif user_win > computer_win: return "You won!" else: return "It's a tie ...." def is_win(player, opponent): if(player == 'r' and opponent == 's') or (player =='s' and opponent =='p') \ or (player =='p' and opponent == 'r'): return True print(play(computer_win, user_win, jugadas)) -
TypeError: get() takes 1 positional argument but 2 were given
I am building and Inventory Web App and I am facing this error. I am trying to get Username from token to show a custom hello message and show that the user is logged in as someone. Here is my Views.py that gets Token from localStorage as logged in user: class UserDetails(APIView): def post(self, request): serializer = UserAccountTokenSendSerializer(data=request.data) global token if serializer.is_valid(): token = serializer.validated_data['token'] return Response(serializer.data) def get(self): user_id = Token.objects.get(key=token).user_id details = User.objects.get(id=user_id) serializer = UserDetails(details, many=False) return Response(serializer.data) class UserDetails(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', ) Here is my Urls.py: urlpatterns = [ path('get-user-token/', views.UserDetails.as_view()), path('get-user-details/', views.UserDetails.as_view()), ] And this is the error that I get: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) TypeError: get() takes 1 positional argument but 2 were given [15/Jun/2022 19:34:59] "GET /api/v1/get-user-details/ HTTP/1.1" 500 82239 -
Is there a way to set a Django model IntegerField default to the ID of the newly created record?
Lets say we have the following model: class MyModel(models.Model): some_int = models.IntegerField() I would like the value of MyModel.some_int to default to the value of MyModel.id. For example, immediately after creating a new record in an empty version of MyModel, I could call MyModel.objects.get(id=1) and receive an object with id=1 and some_int=1. Is there a way to do this? Edit: My current workaround is to set the default to 0, then go back and populate the value with the id of the created record, but that is messy. For context: On an existing model similar to MyModel, I am being asked to add a new column that will render using the MyModel index obsolete as the reference point for the records in that model. Instead, I am adding a new, secondary column, that should store the values of the old IDs for previous records, and new values for future records. To do that though, I need to populate the column first. -
Django - how to get data from relationships?
I try to get data over a many-to-many and a one-to-many relationship. view.py class PublisherDetailView(generic.DetailView): model = Publisher template_name = 'store/publisher_detail_view.html' models.py class Publisher(models.Model): name = models.CharField(null=False, max_length=30) image = models.ImageField(upload_to='publisher_images/') class Book(models.Model): title = models.CharField(null=False, max_length=30) description = models.CharField(max_length=1000) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) class reader(models.Model): name = models.CharField(max_length=40) book = models.ManyToManyField(Book) publisher_detail_view.html {% for reader in publisher.book_set.readers.all %} <p>{{ reader.name }} </p> {% endfor %} I just want to get all readers from a specfic publisher. What is the right code in the template? publisher.book_set.readers.all makes sense to me (early beginner), but doesn't work -
How To get Dynamic Data Detail Information on another page
[enter image description here][1] [1]: https://i.stack.imgur.com/T5sjy.jpg**strong text****strong text** On One Page It Shows all destionation Images and name But I want To Get Details about specfic place when ever i click on image How To Do It workin on a tourism website -
chat app problem can't click on the target twice - javascript
I am making a chatting app using django, a user when click to make a conversation with someone, if clicked another person, he can't come back to the previous one function getConversation(recipient) { $.getJSON(`/chat/api/v1/message/?target=${recipient}`, function (data) { messageList.children('.message').remove(); for (let i = data['results'].length - 1; i >= 0; i--) { drawMessage(data['results'][i]); } messageList.animate({scrollTop: messageList.prop('scrollHeight')}); }); } please help this made me crazy! -
Delete Heroku migrations
I read advices how to delete migrations but I don't understand what I'm doing and it's not working for me. History. One day I had an issue when I added or renamed a model fields locally. So I was tired with that issue and I deleted all migrations and migrate again. And all was OK. But I remember that I will have a big problem when I will deploy on Heroku. So the days are gone. And now it happened. :((( I make migrations, migrate to a server database. Pushed my code, but.. it wrote me: relation "accounts_goal" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_goal" I understand it happened because locally I have 0001 and 0002 migrations, but on the server there are 0012 and etc. migrations. I think I need to delete all old migrations on the server. But I don't know how to do that. Help me please! Thank you) -
Update all object below deleted object in django models?
I created a class which store data for a chapter in book as shown below class Chapters(models.Model): id = models.AutoField(primary_key=True) chapter_number = models.IntegerField(blank=True) name = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.chapter_number: last_chapter = Chapters.objects.latest('chapter_number') self.chapter_number = last_chapter.chapter_number + 1 self.slug = slugify(self.name) same_occurrence = Chapters.objects.filter(chapter_number=self.chapter_number).first() if same_occurrence: same_occurrence.chapter_number = self.chapter_number + 1 same_occurrence.save() super(Chapters, self).save(*args, **kwargs) now, according to the save function the chapter when add between other chapters ( id name chapter_number 1 ABC 1 2 BCD 2 3 CDE 3 ) then all the below chapters get updated as their chapter number increases by one. add name=XYZ at chapter_number=2 id name chapter_number 1 ABC 1 4 XYZ 2 2 BCD 3 3 CDE 4 but now if I delete 1 or 4 or 5 chapters then the sequence of chapter_number will not change. id name chapter_number 1 ABC 1 4 BCD 2 2 CDE 3 3 XYZ 4 5 FGH 5 7 IJK 6 6 PQR 7 I delete chapter_number 2, 3, 4 then the updated table should be like id name chapter_number 1 ABC 1 5 FGH 2 7 IJK 3 6 PQR 4 not like this id … -
Django : cart = self.session[settings.CART_SESSION_ID] = {} giving me unsupported operand type(s) for +: 'float' and 'str' error
Hi im trying to create a cart with django, i created a class: class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart and it raises to me unsupported operand type(s) for +: 'float' and 'str' error My settings.py CART_SESSION_ID = 'cart' My cart.py from django.conf import settings from Products.models import Product class Cart(object): def init(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): for p in self.cart.keys(): self.cart[str(p)]['product'] = Product.objects.get(pk=p) def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def add(self, product_id, quantity=1, update_quantity=False): product_id = str(product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 1, 'id': product_id} if update_quantity: self.cart[product_id]['quantity'] += int(quantity) if self.cart[product_id]['quantity'] == 0: self.remove(product_id) self.save() def remove(self, product_id): if product_id in self.cart: del self.cart[product_id] self.save() My Views.py : def add_to_cart(request,product_id): cart = Cart(request) cart.add(product_id) return render(request,'menu_cart.html') i dont know what is wrong with the code please help, thank you. Edit: Full Traceback: TypeError at / unsupported operand type(s) for +: 'float' and 'str' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.4 Exception Type: … -
How to fix error "The view app.views.uploadform didn't return an HttpResponse object. It returned None instead."?
So I have a form in a html document and I'm trying to use it to add a new item to my django database. Here is the HTML form : <form method="POST" action="{% url 'uploadform' %}" enctype="multipart/form-data"> {% csrf_token %} <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="details">Details:</label><br> <input type="text" id="details" name="details"><br> <label for="littype">Type of Literature:</label><br> <input type="text" id="littype" name="littype"><br> <label for="image">Cover:</label><br> <input type="file" id="image" name="image"><br> <input type="submit" value="Submit"> </form> Here is my views.py handling the function : def uploadform(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('details') and request.POST.get('littype') and request.POST.get('image'): post = PostForm() post.name = request.POST.get('name') post.details = request.POST.get('details') post.littype = request.POST.get('littype') post.image = request.POST.get('image') if PostForm.is_valid(): PostForm.save() return render(request, 'uploadform.html') else: return render(request, 'uploadform.html') Here is my models.py even though i think the issue is in views.py : class PostForm(models.Model): name = models.CharField(max_length=200) details = models.TextField() littype = models.TextField() image = models.FileField(upload_to='app/files/') And finally for the issue, im getting an error saying "The view app.views.uploadform didn't return an HttpResponse object. It returned None instead.". I'm not sure what is causing the error and in addition,if there are any changes I have to make thats stopping the form from being turned into a new item in my database, … -
When reversing a Django migration with AddField, can the newly column renamed undeleted by Django?
As a proof of concept, I made these two migrations in the simplest possible Django app, polls. Here is migration 0001. # Generated by Django 4.0.5 on 2022-06-15 18:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Question', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)), ], ), ] Here is migration 0002 # Generated by Django 4.0.5 on 2022-06-15 18:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0001_initial'), ] operations = [ migrations.AddField( model_name='question', name='question_type', field=models.CharField(max_length=200, null=True), ), ] And here is the model. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) question_type = models.CharField(max_length=200, null=True) Let's say I've migrated the database, and now want to revert 0002. I run the following command python manage.py sqlmigrate polls 0002 --backwards and get this SQL BEGIN; -- -- Add field question_type to question -- CREATE TABLE "new__polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL); INSERT INTO "new__polls_question" ("id", "question_text") SELECT "id", "question_text" FROM "polls_question"; DROP TABLE "polls_question"; ALTER TABLE "new__polls_question" RENAME TO "polls_question"; COMMIT; Clearly, it's dropping the entire column (by dropping and recreating the table), but I'm curious, could Django be … -
Nested for loop in html using django to display information from 2 different models
I have a model called Section and a model called SectionInfo. Section has one field and that's name. A user will create a section by giving it a name. SectionInfo has a foreign key section_name which links it to the Section model. I have a few other fields inside SectionInfo such as things like detail, date_created, etc. What I am trying to accomplish here is using a for loop to display section names that have already been created inside or above some cards that I have set up in an html template. Then I want to use a nested loop to gather the data that is tied to that section name which is what the user inputs in for the SectionInfo model. I am able to display the section names correctly, but the issue im having is in the loop inside that loop. The same detail link is being displayed in every section that was made. Information should only be displayed in the chosen section for which it was made. Here is a bit of code to help you understand what I am trying to accomplish. {% load bootstrap5 %} {% load crispy_forms_tags %} {% load static %} {% block … -
Why will only the top form (in order in Django view) work while the one under it will not?
I have a Django view with two Django forms. Both of them were previously working. Now whichever comes first in the order of code (on top) works. I have tried placing both of the forms on top of the other and whichever one is first works, but the second does not do anything when it is submitted. Does anyone know what is the problem and how to fix this? forms in the views.py #checks if bid form is valid if bid_form.is_valid(): print('!!!!!form is valid') #print("bid form is valid") print(listing.bid) new_bid = float(bid_form.cleaned_data.get("bid")) if (new_bid >= listing_price) and (new_bid > max_bid): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() print("bid form is saving") else: print(bid_form.errors) print("bid form is not saving") return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids." }) else: print(bid_form.errors, bid_form.non_field_errors) print(bid_form.errors) return redirect('listing', id=id) #checks if comment form is valid if comment_form.is_valid(): print("comment is valid") comment = comment_form.save(commit=False) comment.listing = listing comment.user = request.user comment.save() else: return redirect('listing', id=id) -
Djnago rest framework getting json error for fontend api
I am using nextjs in my fontend. When I am adding media url static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my api not working and throwing error FetchError: invalid json response body at http://127.0.0.1:8000/blog-api reason: Unexpected token < in JSON at position 0 but when I remove it's working. here is my code: urls.py urlpatterns = [ path('', include('api.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer my nextjs code for calling api: const url = "http://127.0.0.1:8000/blog-api"; const headers = { method: "GET", "Content-Type": "application/json", Accept: "application/json", "User-Agent": "*", Authorization: "Token 8736be9dba6ccb11208a536f3531bccc686cf88d", }; const res = await fetch(url, { headers: headers }); const data = await res.json(); console.log(data);