Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to display plotly graph on form submit in django
I have a form in django template as follows <div class="container"> <div class="bar_graph_container"> <form id="bar_graph_form" method="post" action="display_bar_graph"> {% csrf_token %} <select class="form-select bar_dropdown" aria-label="Default select example" name="bar_graph_dropdown"> <option selected>Select data to visualise</option> <option value="1">By category</option> <option value="2">By language</option> </select> </form> <div class="bar_graph_container"> </div> </div> </div> When the dropdown value changes, I want the form to submit and display the graph in the bar_graph_container div. To achieve this I tried the following js file $(document).ready(function () { $('.bar_dropdown').change(function (event) { event.preventDefault(); var data = new FormData($('#bar_graph_form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { console.log('form submitted successfully') console.log(data) } }) }) }) views.py def display_bar_graph(request): if request.method == 'POST': user_select = request.POST['bar_graph_dropdown'] if int(user_select) == 1: graph = plotly_helper.make_bar_graph('category', 'count', 'category', 'count', None) if int(user_select) == 2: graph = plotly_helper.make_bar_graph('language', 'count', 'language', 'count', None) # context = {'graph': graph} print('the form was submitted using ajax') return JsonResponse(graph, safe=False) While something is happening, this is just returning the entire HTML content for the page in the data variable. The print in the views.py is not printing which makes me think the view is not even running. I am not sure what I am … -
How to revert a deleted (but applied) migration in Django (MariaDB)?
The Problem (Short Description) I have a migration file deleted, but it was previously applied in the database. I want to revert the changes it has made. The Problem (Long Description) I had forked a python package and had made some changes on one of their models. I used the fork instead of the official package in my project and had my new migration applied in my database. A couple of days ago, I replaced the fork with the official version of the package and did what I wanted to do in another way without changing the model anymore. This means, that for the same app, now one migration is missing (the migration that I created). However, the changes that this migration made on the database are still present and the migration name is still listed on the django_migrations table. This has occurred weird problems, since the code and the database are not synchronized. What I have tried I tried running python manage.py migrate <appname> <previous_migration> where the appname is the app I have problem with migrations and the previous_migration is the last migration the app had before I added mine. I tried modifying the database directly by manually reverting … -
Is it possible to replace a string in a model instance field based on field original value
I need to replace a field value based on current value such that: Current:Replacement S:D D:S s:d d:s I can do it using multiple queries: myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('S'), Value('D'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('D'), Value('S'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('s'), Value('d'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('d'), Value('s'))) However, that would require multiple database hits and only one query will match. I tried to use a hash table in the update query but I got error: nr = {'S':'D', 's':'d', 'D':'S', 'd':'s'} myModel.objects.filter(child = ID).update(rel = Replace('rel', F('rel'), nr[F('rel')])) KeyError: F(rel) I recoded my answer to solve the double replacement issue but still the database gets hit four times: myModel.objects.filter(child = ID, rel = 'D').update(rel = Value('S')) myModel.objects.filter(child = ID, rel = 'd').update(rel = Value('s')) myModel.objects.filter(child = ID, rel = 'S').update(rel = Value('D')) myModel.objects.filter(child = ID, rel = 's').update(rel = Value('d')) -
Module 'sklearn' not found when running program in VSCode
I installed sklearn using pip install sklearn. When I run scripts in Jupyter Notebook then everything works fine. I write Django app and I try to run same scripts in VSCode but Module 'sklearn' not found comes up. I guess I need to somehow install sklearn but don't know how and where. I selected Python Interpreter in VS. I also tried to install through pip3 install sklearn (my version - Python 3.10.1). I also installed this library through VS terminal (in virtual environment). Still get the same error. I also tried to install updated version pip install -U scikit-learn but in no vain. However, when I run some other Django apps (no sklearn) then it goes smoothly, I run them in my virtual environment and it works fine. -
How to make ModelSerializer field optional in Django rest framework
I have this model Reaction with code and comment fields. I have both of them null=True, blank=True in my models.py file. I want one of them to filled and other to be empty, for this I created clean method in models and validate method in serializers. But when I try to create a reaction without code/comment it says code/comment is required. models.py class Reaction(models.Model): code = models.ForeignKey(Code, null=True, blank=True, related_name="code_reactions", on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, blank=True, related_name="comment_reactions", on_delete=models.CASCADE) user = models.ForeignKey(User, related_name="reations", on_delete=models.CASCADE) REACTION_CHOICES = [ ("like", "Like"), ("dislike", "Dislike"), ("wow", "Wow"), ("love", "Love"), ("sad", "Sad"), ("haha", "Haha"), ("rocket", "Rocket"), ("angry", "Angry"), ] name = models.CharField(choices=REACTION_CHOICES, max_length=10) class Meta: unique_together = [["code", "user"], ["comment", "user"]] def clean(self): if self.code and self.comment: raise ValidationError(_('One reaction cannot be assigned to a code and a comment')) if not self.code and not self.comment: raise ValidationError(_("Please enter a code or a comment")) serializers.py class ReactionCreateSerializer(serializers.ModelSerializer): code = serializers.IntegerField(required=False) comment = serializers.IntegerField(required=False) class Meta: model = Reaction fields = ["id", "user", "code", "comment", "name"] def validate(self, data): if data["code"] and data["comment"]: raise serializers.ValidationError(_('One reaction cannot be assigned to a code and a comment')) if not data["code"] and not data["comment"]: raise serializers.ValidationError(_("Please enter a code or a … -
Django View that shows related views.py
i wanna get single product in my product list it shows error error line is 20 in views.py if i['_id'] == pk i cant solve this here are my views.py and errorenter image description here [enter image description here][2] -
Is there any methods to create charts based on exported excel files data using Django?
I am using the xlwt library to export Django data to Excel and ran into such a problem that this library does not support charting. What solutions can there be in such a situation? What other libraries would be suitable? Here is example of my simple Excel file export function using xlwt in Django views.py: def export_excel_av_items(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="available-items.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Available Items') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Name', 'Qty'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Stock.objects.all().values_list( 'name', 'quantity') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) return response I will be grateful for good advice! -
Error showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I am new to python and try to make recommendation engine when I click on recommendation button it throws error showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I have paste my code below: def recommend(request): user_id = request.user.id url = "http://127.0.0.1:5000/recommend/" payload = {'user_id':user_id} headers = { 'content-type': "multipart/form-data", 'cache-control': "no-cache", } responses = requests.request("POST",url,data=payload) response = json.loads(responses.text) responses_tuple = make_tuple(response) context = list() for user_id in responses_tuple: try: recommended = Product.objects.get(id=user_id) context.append(recommended) except: pass return render(request,"recommend/recommend.html",{'context': context}) -
DRF : Question about filtering with manytomany
I have two models with a many to many relationship. I have 3 tags model to categorize all the info objects. class Tag(models.Model): name= models.CharField(unique=True, max_length=100) class Info(models.Model): title = models.CharField(max_length=120) tag = models.ManyToManyField(Tag, blank = True) I want to have a list where it list all relevant Info objects base on Tag, requested by the user. I would like to know if what I'm doing is the right approach since its my 1st time building API and I havent build any frontend using backend API before so unsure if my understanding/approach is right. Question Do I : Make a Tag.objects.all() list API endpoint to expose all tags and let the frontend sort the list requested by the user with something like --> requested_relevant_tags.info_set.all() . Reverse lookup. in the frontend. In this case all I do for the backenbd API is just Tag.objects.all(). Make 3 list endpoint Info.objects.filter(tag = whatever_number1,2,3) to list info based on the tags. And when the client request, say Info.objects.filter(tag =1) then I just get grab that endpoint? I'm having a hard time imagining the actual application of this with the frontend. Do the user get to "click" the tag -> frontend do the thing with … -
Creating object on different model with logic to another model
Say I have 2 models, One is Order and the other is Item. STATUS_CHOICES = ( ('Un Finished', 'Un Finished'), ('In Progress', 'In Progress'), ('Assigned', 'Assigned For PickUp'), ('Picked Up', 'Picked Up'), ('Completed', 'Completed'), ) class Order(models.Model): product = models.CharField(max_length=100) # ... status = models.CharField( max_length=150, choices=STATUS_CHOICES, default='Un Finished') #item class Item(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ["updated"] If any of the object status in the Order model changes to Completed I want to automatically create the object in the Item models. Let's say Model Order contains and object: {id: 12 , product : "Product Name", status : "Completed"} Then here I want to update the Item with an object containing that information. How I can do this in a simpler way? I found some articles that suggest using Django signals but I'm new to Django and need little help to reproduce the solution. -
Django Reverse for 'product_page' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<object_id>[0-9]+)\\Z'] error
I need to click on the card to the main page in django, but an error occurs Reverse for 'product_page' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<object_id>[0-9]+)\Z'], how to fix, what can be done I've already seen the answer to this question, but it didn't help... HTML home page: {% extends 'food/base_main.html' %} {% load static %} {% block title%}Рецепты{% endblock title%} {% block nav %} {% if request.user.is_authenticated %} <a href = "{% url 'main' %}"><li><button class = "nav_btn">Рецепты</button></li></a> <li><button class = "nav_btn">Избранное</button></li> <a href = "{% url 'create' %}"><li><button class = "nav_btn_">Создать</button></li></a> <a href = "{% url 'profile' %}"><li class = "enter"><button class = 'enter_btn'>{{user.first_name}}</button></li></a> <a href="{% url 'logout' %}"><li class = "reg"><button class = 'reg_btn'>Выход</button></li></a> {% else %} <a href = "{% url 'main' %}"><li><button class = "nav_btn">Рецепты</button></li></a> <li><button class = "nav_btn">Избранное</button></li> <a href = "{% url 'create' %}"><li><button class = "nav_btn_">Создать</button></li></a> <a href = "{% url 'authentication' %}"><li class = "enter"><button class = 'enter_btn'>Вход</button></li></a> <a href="{% url 'registration' %}"><li class = "reg"><button class = 'reg_btn'>Регистрация</button></li></a> {% endif %} {% endblock %} {% block recept %}Рецепты{% endblock %} {% block liked %}Избранные{% endblock %} {% block crate %}Cоздать{% endblock %} {% block content %} {% … -
Checking conditions with a function django views
I am trying to make my code more readable and less verbose. I have this long view, where I have some if and elif statement to check some conditions. What I am trying to do is to write this function into another file (utils.py) and use this function in the views. The view is something like that: views.py if float(ata_tacho) <= float(etd_tacho): messages.error(request, "ATA Tachometer cannot be greater or equal to ETD Tachometer") return HttpResponseRedirect(reverse('flight:add_new_flight')) elif ata <= etd: messages.error(request, "ATA cannot be greater or equal to ETD!") return HttpResponseRedirect(reverse('flight:add_new_flight')) elif function_type_obj.name == 'Dual Command' and not instructor: messages.error(request, "Instructor must be on Board!") return HttpResponseRedirect(reverse('flight:add_new_flight')) More code to run only if conditions above are satisfied These are some conditions I need to check to continue running the code. So far, so good. If I try to write this function in a more general one in utils.py file like below: utils.py def flight_validator(request, ata_tacho, etd_tacho, ata, etd, function_type, instructor): if float(ata_tacho) <= float(etd_tacho): messages.error(request, "ATA Tachometer cannot be greater or equal to ETD Tachometer") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif ata <= etd: messages.error(request, "ATA cannot be greater or equal to ETD!") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif function_type == 'Dual Command' and not instructor: messages.error(request, … -
who viewed my profile - list ( python - Django) Algorithm
Am currently working on Matrimonial site using django framework. In that site,I want to show the list of users who viewed my profile.Let's say I am user 'x' , if user 'y' and user 'z' viewed my profile . I want to show user 'y' and user 'z' viewed your profile in the my visitors page of user'x'. How to find out who viewed my profile?. -
Django i try to use reverse function and i got NoReverseMatch
i am a new at Django framework. and i follow of some guide on udemy and do step by step but something go wrong. i open startapp call 'accounts', and then i have file call urls.py here is what i have. from django.urls import path from . import views urlpatterns = [ path("<int:month>", views.monthly_num), path("<str:month>", views.monthly_str, name='monthly-acc'), ] and in views.py file i want to do reverse and to do redirect. from django.shortcuts import render from django.http import HttpResponseNotFound from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse # Create your views here. months = { "january": "Hello january", "febuary": "Hello febuary", "march": "Hello march", "april": "Hello april", } def monthly_str(request, month): try: text_month = months[month] return HttpResponse("<h1>"+text_month+"</h1>") except: return HttpResponseNotFound("THIS NOT A MONTH!") def monthly_num(request, month): monthly = list(months.keys()) if month > len(monthly) or month <= 0: return HttpResponseNotFound("<h1>NO GOOD</h1>") redirect_month = monthly[month-1] redirect_path = reverse('monthly-acc', args=[redirect_month]) # HERE I GOT THE ERROR. return HttpResponseRedirect(redirect_path) so what i try to do i have the local url for example: http://mypro:9000/acc/1 i want to redirect to http://mypro:9000/acc/january and i got this page error. -
Django migrating to new database, should I apply migrations before moving data?
My Django app uses an encrypted Amazon AWS RDS database. The encryption causes some annoyances/complexities and costs a small amount of extra money, so I'd like to do away with it. Encryption can't be removed so I've created a new RDS instance with new database. The old database also use PostGres 12.8 whereas the new one uses 14.2. Should I apply migrations to the new database and then move the data into the tables created by the migrations? Or can I just use a data migration service such as AWS DMS or DBeaver which will create the tables for me? I ask because I wonder if there are any intricate differences in how migrations provision the database vs how a data migration tool might do it, causing me issues down the line. -
Deployment of a React app with Django backend
As in the title I use React.js at the frontend and Django at the backend. I basically remade a website for my father's enterprise and we got cPanel on our hosting service (prevoius website was made in Django alone). The problem is I use cross origin in the new app. It is easy for me to just open up 2 command prompts and start 2 different localhosts for Django and React, but I have no idea how to do it on the server side. I had some ideas before like: "Should I buy a second server and host just React there?" or "Should I somehow merge backend and frontend together?", but still I have no idea which solution would fit the most. I would be grateful for any advice, tutorials, links that would help me solve this problem. If needed I can paste a github link to a project aswell.