Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django related models also need a generic relation: how to work around unresolved reference?
Here is the two models: class Circuit(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) service_order_item = models.ForeignKey(ServiceOrderItem, on_delete=models.RESTRICT) location_a = models.ForeignKey(Location, on_delete=models.SET_NULL, blank=True, null=True) location_z = models.ForeignKey(Location, on_delete=models.SET_NULL, blank=True, null=True) class CircuitItem(models.Model): circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) index = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() CircuitItems are list of things in a circuit the problem is CircuitItems can be Circuits themselves (as well as some other models) Is it possible to do something like: circuit_link = GenericRelation("CircuitItem") to avoid the unresolved reference, or is there no way to do this with only two tables and a third will be required? -
Cant save image to "media" folder when the ImageField UPDATES
I am using ajax to send image file through formdata() Javascript code: $("#change-default-img").change(function () { let category = $($("#category-buttons-row").find('button[aria-label="ACTIVE"]')).attr("id") // Change preview in the UI if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#imagePreviewDefault").css('background-image', 'url(' + e.target.result + ')'); } reader.readAsDataURL(this.files[0]); } var fileData = new FormData(); fileData.append("file", this.files[0]) fileData.append("csrfmiddlewaretoken", "{{ csrf_token }}") fileData.append("category", category) $.ajax({ method: "POST", url: "{% url 'set-default-image' %}", processData: false, contentType: false, mimeType: "multipart/form-data", data: fileData, success: function (response) { data = $.parseJSON(response); if (data.status == "Done") { console.log("Default image updated for " + category); } } }) }) This is my view for updating the ImageField if request.method == 'POST': category = request.POST['category'] image = request.FILES.get('file') image = f'default_images/{image}' if category == 'category-logo': DefaultImages.objects.filter(app_name='payup').update(app_logo=image) elif category == 'category-property': DefaultImages.objects.filter(app_name='payup').update(property_card=image) elif category == 'category-owner': DefaultImages.objects.filter(app_name='payup').update(owner_profile=image) elif category == 'category-renter': DefaultImages.objects.filter(app_name='payup').update(renter_profile=image) return JsonResponse({'status': 'Done'}) This is my models.py class DefaultImages(models.Model): app_name = models.CharField(max_length=5, default='payup') app_logo = models.ImageField(upload_to="default_images/", null=True) property_card = models.ImageField(upload_to="default_images/", null=True) owner_profile = models.ImageField(upload_to="default_images/", null=True) renter_profile = models.ImageField(upload_to="default_images/", null=True) def __str__(self): return self.app_name This is how the directory looks like : media ---- backup_images ---- profile_images ---- prop_images When I am changing the image from the UI, the … -
Tripple Join with sum in django fails
How can I fetch such a query especially Mark is not attached to stream but the child's ClassInformation is the one that has the stream has_all_marks = Mark.objects.filter(marks_class=marks_class, year=year, term=term, exam_set=exam_set, child__classinformation__stream__id=stream).values('child').annotate( mtotal=Sum('marks')).order_by('-mtotal') Right now the result I get is wrong. I get multiples for some mtotal -
Next.js or Django for a small website with dynamic content with a firebase backend?
I am to develop a website for a design firm to showcase their work. The website only has a few pages, with text and images that can be dynamically changed from a firebase backend. The priority is on a neat UI that loads fast, and the timeline for development is short. Should I use Next.js as the framework or would Django be a better option? Please let me know why I should pick one framework over the other. -
How to serialize abstract base models and sub-models in Django REST framework
I have a model Complaint which can have many Evidences. An Evidence can be an Attachment or a Link. Evidence is an abstract base model. from django.db import models class Complaint(models.Model): text = models.TextField() class Evidence(models.Model): complaint = models.ForeignKey( Complaint, related_name='%(class)s_evidences', on_delete=models.CASCADE ) is_attached = models.BooleanField() class Meta: abstract = True class Attachment(Evidence): file = models.FileField(upload_to='attachments') class Link(Evidence): url = models.URLField() I want to be able take input of a Complaint and and all its Evidences from a single view like so: { "text": "Lorem ipsum", "evidences": [ { "description": "dolor sit amet", "is_attached": false, "url": "https://example.com" }, { "description": "consectetur adipisicing elit", "is_attached": true, "file": "http://localhost:8000/media/attachments/filename" } ] } This is what I have in my serializers.py thus far: from rest_framework import serializers from .models import Complaint, Evidence, Attachment, Link class EvidenceSerializer(serializers.Serializer): class Meta: abstract = True model = Evidence fields = ['id', 'is_attached'] class AttachmentSerializer(EvidenceSerializer, serializers.ModelSerializer): class Meta: model = Attachment fields = EvidenceSerializer.Meta.fields + ['file'] class LinkSerializer(EvidenceSerializer, serializers.ModelSerializer): class Meta: model = Link fields = EvidenceSerializer.Meta.fields + ['url'] class ComplaintSerializer(serializers.ModelSerializer): evidences = EvidenceSerializer(many=True) class Meta: model = Complaint fields = ['id', 'text', 'evidences'] This gives the following error when requesting to the complaint POST view (/lodge): TypeError … -
Can't get model in template through related_name
I 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 from post to group through related_name. Now I want to show group member in and all group. But when I try to show GroupMember in template post_list through related_name = user_groups it doesn't show data (same with all group). Seem like I miss something, can u check it for me. Thank! App groups models.py from django import template register = template.Library() 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 template post_list.html <h5 class='title'> Your Groups</h5> <ul class='list-unstyled'> {% for member_group in get_user_groups %} <li class='group li-with-bullet'> <a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name }}</a> </li> {% endfor %} <h5 class='title'> All groups</h5> <ul class='list-unstyled'> {% for other_group in get_other_groups %} <li class='group li-with-bullet'> <a href="{% url 'groups:single' slug=other_group.slug %}"></a> </li> {% endfor %} -
Django Html - make dropdown menu from navigation bar [duplicate]
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains more options such as account, myorder, and logout. So I can save space in the navigation bar by avoiding having too many buttons. Some desired examples like below: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will conflict/mess up my current page. CSS <style> .block [for=s1]{ width: 400px; display: block; margin:5px 0; } .block [for=s2]{ width: 800px; display: block; margin:5px 0; } .center [for=s1]{ text-align: center; } .center [for=s2]{ text-align: center; } label[for=s1]{ display: inline-block; width: 100px; text-align: right; } label[for=s2]{ display: inline-block; width: 70px; text-align: left; } input,textarea [for=s1]{ vertical-align: top; } input,textarea [for=s2]{ vertical-align: left; } .page-header { //background-color: #5E5A80; background-color: #454545; margin-top: 0; //padding: 20px 20px 20px 40px; padding: 5px 5px 5px 5px; } .page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } input:focus{ border-color: #66afe9; outline: 0; … -
Django website fails to load after request
I have two Django websites on the same server using Apache (windows 10) with mod_wsgi. My first Django website runs fine, it is a lot simpler, my second one, however, does not. Once I connect to it, it loads very slowly, however, I can't connect to it again (it just remains in the connecting phase with no errors). I've had this problem for quite a while, here are my other posts for context. Only the first Django site to be loaded works Django infinite loading after multiple requests on apache using mod_wsgi Django websites not loading Only quite recently have I pinpointed the problem to this specific Django project, I will provide most of my code below. Hopefully, someone can show me what I have done wrong. Contact me if this isn't enough information, thank you. Base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path('', include('mainfront.urls')), path('about/', include('mainfront.urls')), path('contact/', include('mainfront.urls')), path('home/', include('mainfront.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] Base WSGI import os from django.core.wsgi import get_wsgi_application import sys sys.path.append('C:/xampp/htdocs/neostorm') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'neostorm.settings') application = get_wsgi_application() Mainfront (front app) views.py from django.shortcuts import render import threading from mcstatus import JavaServer from .models import Article #Query … -
Import multiple models with only one csv file django import export
I'm using django import export package. I have two models called Vineyard and VineyardUser. I also have a csv file that contains all the data for both the Vineyard and VineyardUser models (separated by one blank column). Here is my model (which has been simplified): class Vineyard(models.Model): name = models.CharField(max_length=255, blank=True) text = RichTextUploadingField(blank=True) class VineyardUser(models.Model): vineyard = models.OneToOneField(Vineyard, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True) I want to click import on the Vineyard model in admin, and then it also created the VineyardUser object. How can I do that? Now it only creates Vineyard objects even though there is a VineyardUser data in that csv file. I think we can use before_save_instance or after_save_instance but I'm not sure how to do that. Also one thing to note is that they may also have two fields with the same name. Any suggestion or solution to solve this problem?