Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save method doesn't work despite successful POST request
I'm using jquery to send request to a Django form. I have this function in views.py: @csrf_exempt def update_ops(request): print('something something') ops_id = request.POST['id'] instance = Ops.objects.all().filter(id=ops_id) form_qdict = QueryDict(request.POST['form_data']) form = OpsForm(form_qdict or None, instance=instance) if form.is_valid(): form.save() print('saved bro!') # return HttpResponseRedirect('/ops/') else: print('form is not valid') return render(request, 'ops_form.html', {'form': form}) urls.py: urlpatterns = [ url('^update_ops_form/', views.update_ops, name='update_ops_form') ] the html form in form.html: <form action="{% url 'update_ops_form' %}" id="post-form" method="post"> {% csrf_token %} <!--some html form--> </form> and the script in form.html: <script> var ops_id = $('#ops_id').text() console.log(ops_id) $("#post-form").submit(function (event) { event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); console.log(post_url)//get form action url var request_method = $(this).attr("method"); //get form GET/POST method var form_data = $(this).serialize(); //Encode form elements for submission console.log(form_data) $.ajax({ url: post_url, type: request_method, data: {'id':ops_id,'form_data':form_data} }) }); </script> What I want to do is to update an instance of the Ops Model with form using jquery. The POST request is successful, but it doesn't update the instance that I changed. The only possible reason for the error that I know of is because the url in action parameter of the html form doesn't match the url that maps to the update_ops() function in … -
Search in several models
I have two model classes as follows that are not related to each other. class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... first_name = models.CharField(max_length=30, null=False, blank=False) last_name = models.CharField(max_length=30, null=False, blank=False) father_name = models.CharField(max_length=30, null=False, blank=False) class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... code = models.CharField(max_length=15, null=True, blank=True) And now a request comes as follows: http://localhost:8000/api/v1/search/users/?first_name=john&&last_name=dev&&code=25 How can I search if one of the input parameters is in one of the tables (person or company)? The effort I have made but no result found: class SearchUserAPI(APIView): def get(self, request, format=None): try: from django.db.models import Q q = request.query_params search_models = [Person, Company] search_results = [] for model in search_models: fields = [x for x in model._meta.fields if isinstance(x, django.db.models.CharField)] search_queries = [Q({x.name + "__icontains": q.get(x.name)}) for x in fields] print(search_queries) q_object = Q() for query in search_queries: q_object = q_object | query results = model.objects.filter(q_object) search_results.append(results) data = [search_results] return Response(data, status=status.HTTP_200_OK) except Exception as e: return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
wagtail WagtailFormBlock localization
I have a WagtailFormBlock streamfield in my project. When I tried to translate my pages with that streamfield, I can only translate block's form_action and form_reference but can't change form as it is. Is it any way, to change form, when translate some page? img reference -
Django model importing issue
I'm new to Django. I've been trying to import my model.py into a custom management command file, but it tells me: Unable to import 'Educationa_Organization_Management_System.Subjects.models and when I tried to remove the folder name from the import, I still got this error message: Unable to import 'Subjects.models Here's my code in the custom command file : from django.core.management.base import BaseCommand from Educationa_Organization_Management_System.Subjects.models import Subject class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("Subject_name") parser.add_argument("Instructor_name") parser.add_argument("prerequisites", action="store_true") parser.add_argument("Assistant_name") parser.add_argument("Course_description") parser.add_argument("Validation_date") parser.add_argument("SubjectNumberOfChapters") parser.add_argument("numberOfLecturesPerWeek") parser.add_argument("numberOfSectionsPerWeek") parser.add_argument("Subject_FullGrade") def handle(self, *args, **options): subject = Subject( name=options['name'], Instructor_name=options['Instructor_name'], prerequisites=options['prerequisites'], Assistant_name=options['Assistant_name'], Course_description=options['Course_description'], Validation_date=options['Validation_date'], SubjectNumberOfChapters=options['SubjectNumberOfChapters'], numberOfLecturesPerWeek=options['numberOfLecturesPerWeek'], numberOfSectionsPerWeek=options['numberOfSectionsPerWeek'], Subject_FullGrade=options['Subject_FullGrade'], ) subject.save() self.stdout.write(self.style.SUCCESS( "Subject has been successfully added to the database")) and here's my model.py file content: from django.db import models class Subject(models.Model): Subject_name = models.CharField(max_length=50, blank=False) Instructor_name = models.CharField(max_length=50, blank=False) prerequisites = models.BooleanField() Assistant_name = models.CharField(max_length=50, blank=False) Course_description = models.TextField() Validation_date = models.DateTimeField() SubjectNumberOfChapters = models.IntegerField(blank=False, null=False) numberOfLecturesPerWeek = models.IntegerField() numberOfSectionsPerWeek = models.IntegerField() Subject_FullGrade = models.IntegerField() And finally, Here're my folders: Yeah, also, the app is in the setting.py file in the INSTALLED_APPS part. -
Django update form doesn't keep the files?
i want to update the note which is also in database, The code below is only update note instance accept the files. when i submit the form the form is create new files it's not changing the old files. i want to update the files data too. I would be grateful for any help. def PostUpdate(request, id): post = Note.objects.get(id=id) form = NoteFullForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): title = form.cleaned_data['title'] text = form.cleaned_data['text'] note_obj = Note.objects.create(title=title, text=text) for f in request.FILES.getlist('images'): Images.objects.create(note=note_obj, image=f) form.save() return redirect('/up/update/27/') else: form = NoteFullForm(instance=post) return render(request, 'uploading.html', {'form': form}) -
why django model methods is not applicable in queryset methods like values and annotate
I want to know, why Django custom methods in model does not apply in Django queryset methods? Is there any problems if we make custom manager to deal with it. -
how sum ForeignKey to ManyToManyField django queryset
i have this model class PortfolioExchangeTransaction(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now, verbose_name=_('Create Time')) portfolio = models.ForeignKey(Portfolio, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Portfolio'), related_name='exchange_transaction') type = models.CharField(max_length=40, choices=Transaction_TYPE, blank=True, null=True, verbose_name=_('Type')) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Exchange')) count = models.IntegerField(default=0, verbose_name=_('Count')) and want to sum count and portfolio of this model based on exchange so i use below code : transes.annotate(exc_count=Case( When(type='negative', then=F('count') * -1), When(type='positive', then=F('count')), ) ).values('exchange').annotate( sum_count=Sum('exc_count') ).values('exchange', 'sum_count').annotate( portfolios=Value(None, output_field=ManyToManyField(Portfolio)) ) the result is : <QuerySet [{'exchange': 248, 'sum_count': 4000, 'portfolios': None}, {'exchange': 512, 'sum_count': 10000, 'portfolios': None}, {'exchange': 591, 'sum_count': 0, 'portfolios': None}, {'exchange': 940, 'sum_count': 10000, 'portfolios': None}]> as can see i create portfolio field and want to sum foreignkeys to manytomanyfield ( now is None value ) how can do that? -
Django tries to render even commented-out HTML-code which leads to errors
When rendering a page of my django-project, I get the following error, even though the crucial part of the HTML code is commented-out: NoReverseMatch at /current/ 'blog' is not a registered namespace Request Method: GET Request URL: http://localhost:8000/current/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: 'blog' is not a registered namespace Exception Location: /home/user/.virtualenvs/Django3_course/lib/python3.9/site-packages/django/urls/base.py, line 83, in reverse Python Executable: /home/user/.virtualenvs/Django3_course/bin/python Python Version: 3.9.0 Python Path: ['/home/user/.../todowoo_project', '/home/user/.../todowoo_project', '/home/user/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts', '/home/user/.pyenv/versions/3.9.0/lib/python39.zip', '/home/user/.pyenv/versions/3.9.0/lib/python3.9', '/home/user/.pyenv/versions/3.9.0/lib/python3.9/lib-dynload', '/home/user/.virtualenvs/Django3_course/lib/python3.9/site-packages'] Server time: Tue, 26 Jan 2021 13:56:35 +0000 Error during template rendering In template /home/.../todo/templates/todo/base.html, error at line 97 'blog' is not a registered namespace [...] The commented-out code in question is the following: <!-- <li> <a role="button" href="{% url 'blog:all_blogs' %}" class="btn btn-primary">Blog</a> </li> --> I would like to keep this in case I need to remind myself how to send an URL to another app within my django project, in this case called 'blog'. Why isn't it possible to comment it out, leave it there and let it be ignored by the rendering process? Even wrapping it as php-code did not work: <?php <!-- <li> <a role="button" href="{% url 'blog:all_blogs' %}" class="btn btn-primary">Blog</a> </li> --> ?> -
Django - Unable to Locate Template from within App
Ive following the steps for adding a template, but when i try and access my URL im getting: TemplateDoesNotExist at / My code is below. Also I have my app in the INSTALLED_APPS in settings. And the template is located within the templates folder within my app. View from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html', {}) Setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Any ideas? -
Drop Down List Selection
When I select a drop down list value, it inserts it into my heper.py query. However, the drop down significantly reduced to just that one selection. I have to hit the back button to see all of my drop down values since it does not repopulate on the new page. Is there a way i can keep selecting different values from drop down, even in the new query result page? Actual Result Drop down List: Chris Evan Patty Then if I choose Chris on the drop menu then Evan and Patty disappear when it narrows the query results and inputs Chris in my query. drop down list: Chris code helper.py def EmployeeBalancing(get_dropdown_value, procdate): cursor = connection.cursor() print(cursor.execute(f'''select distinct to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function, from ppc_data.emp_performance where to_char(processingdate,'YYYY-MM-DD') = '{procdate}' and loginname='{get_dropdown_value}' order by to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function desc ''')) query = cursor.fetchall() return query def EmployeeBalancing_Null(): cd = datetime.now().strftime('%Y-%m-%d') print(cd) cursor = connection.cursor() cursor.execute(f'''select distinct to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function, from ppc_data.emp_performance order by to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function desc''') query = cursor.fetchall() return query views.py def stats(request): if … -
Django Template Takes The Information From The Other One
inside of the views.py views.py Hello, I am new to Django. I have two views like this. One of them is for normal user and the other one is for admin. But the template of admin takes it's information from the other one. Like, If I change the book_detail, admin_book_detail changes too. But if i change admin_book_detail's information, nothing happens. inside of admin_book_detail.html inside of admin_book_detail.html inside of book_detail.html inside of book_detail.html inside of the url urls.py -
how to set a None value with django form
i have a form with a google map and when the user does not click on the map i need to send latitude and longitude as None to views.py ,this is views.py : if request.method == "POST": if request.user.is_authenticated: if True: form = CreatMeetingForm(request.POST,request.FILES) print(request.POST) if form.is_valid(): if 'id' in request.POST: obj= get_object_or_404(Meeting, id=request.POST.get('id')) form = CreatMeetingForm(request.POST or None,request.FILES or None, instance= obj) meeting= form.save(commit= False) members = form.cleaned_data['members_email'] try: meeting.lat= round(form.cleaned_data['lat'],14) meeting.lng = round(form.cleaned_data['lng'],14) except : meeting.lat= None meeting.lng = None meeting.host = request.user update = True meeting.save() else : meeting=form.save(commit=False) members = form.cleaned_data['members_email'] try: meeting.lat= round(form.cleaned_data['lat'],14) meeting.lng = round(form.cleaned_data['lng'],14) except : meeting.lat= None meeting.lng = None meeting.host = request.user update=False meeting.save() else: print('form not valid') form.errors["code"] = 0 return JsonResponse(form.errors) else: return HttpResponse('Unauthorized', status=401) and this is my model fields: lat = models.DecimalField(max_digits=19, decimal_places=16,blank=True,null=True) lng = models.DecimalField(max_digits=19, decimal_places=16,blank=True,null=True) when i want to create a new form my code works but when in edit mode and i send the id in requet.POST it raises this error: {"lat": ["Enter a number."], "lng": ["Enter a number."], "code": 0} it seems i get the error in form.is_valid bcs i can see the print('form not valid') any suggestion? -
Django model relations [nesting and hierarchy]
I apologize in advance for the novice question and if it is already answered. I have searched multiple terms without getting anything clear for it. I'm trying to figure out a model schema and it's relations in a Django project. The questions that arise while doing that are the following: Regarding the first part of the code: (Country >State >City >University >Department > Subject): Are there too many levels of hierarchy? Any way to model it better or more efficiently? I have been looking to the nested relationships as well (serializers), but no clue if there's a better way to organize it. Is it a good practice to have models such as State or City with only one field in the hierarchy? I mean, I need them, but not sure if they are avoidable due to their simplicity with another models relationship solution. Can a "model" access its second/third/nth parent? Eg: A subject can access easily its department via: Subject.objects.filter(department__name='Maths') But is it possible to access the University or State from the subject object? How? Regarding the second part of the code (Person and laptop): I have a few roles in the models (president, dean, director, teacher). Some of those … -
Create generic viewset and serializer for models in django rest framework
I am making a lot of views and serializers for my models that takes all fields. They all look like this: class MyModelViewSet(viewset.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' I would like to make a generic Viewset and Serializer for that can simply take inn my model. I found this post to be helpful, but I would rather not have the model in the url. If possible, I would send the model with the router.register: router.register('my_url', MyView(MyModel), basename='my-basename') but this gives me an error: AttributeError: This method is available only on the class, not on instances. Any idea of how I can solve this? -
How to get a specific queryset in Django
I am building a hospital management app and I am currently building the Nurse's webpage. In that webpage, I would like the following to display: a list of all employed nurses, a list of their workshifts, and what departments they work for. I am trying to get the department section to display but I keep getting an error "too many values to unpack (expected 2)". What can I do so that the nurses' department shows? Models.py from django.db import models # Create your models here. #Work Related aka Department and Work Shift class Department(models.Model): name = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class WorkShift(models.Model): name = models.CharField(max_length=200, null=True, blank=True) start_datetime = models.DateTimeField(null=True, blank=True) end_datetime = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name #Personel Related aka Employees and Patients class Doctor(models.Model): name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) department = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE) work_shift = models.OneToOneField(WorkShift, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Nurse(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) sector = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE) reports_to = models.ForeignKey(Doctor, blank=True, null=True, on_delete=models.CASCADE) work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Patient(models.Model): STATUS = … -
render a template and Keep running another background task in Django
I would line to run a function without interrupting the current function as follows def taskone(request): #processes of task one tasktwo() return render(request,"index.html") As taskone executes, tasktwo should also start executing. Task one should allow task two to continue executing in the background as it renders the html page. Please someone give me an idea on how to go about it. -
How to match models and store a form in the database
I am creating questions on the first page, I am calling these questions on the second page and I want to fit the Answer model. But I can not dynamically assign the Answer model to the Question question to save later. this is current result -> enter image description here. The problem is that the answer in the html inputs is also a common name my age <input type="hidden" name="i_id" value="4"/> <input type="text" name="form-0-answer" maxlength="100" id="id_form-0-answer"> my name <input type="hidden" name="i_id" value="5"/> <input type="text" name="form-0-answer" maxlength="100" id="id_form-0-answer"> Both are called form-0-answer my code -> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): AnswerFormSet=modelformset_factory(Answer, fields=["questin","answer"]) questions=Question.objects.all() formset=AnswerFormSet() if request.method=="POST": print(request.POST) if formset.is_valid(): formset.save() return render(request, "question/ans.html", {"form":formset, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form method="POST" > {{ formset.management_data }} {% … -
NetBox plugin installation for development
I want do develop a plugin for netbox. I installed netbox on my machine and now I have to install the plugin, which is pretty blank at the moment(similar to the one from the netbox docs). For Basic information on how to install a plugin or develop one you can look at the netbox documentation. The Problem that I#m facing is when I try to start the netbox server it doesn't find the Plugin which is listed in the config file. First I installed the plugin (venv) i518240@ubuntu:~/projects/netbox_dashboard$ python setup.py develop running develop running egg_info creating ccloud_netbox_dashboard_plugin.egg-info writing ccloud_netbox_dashboard_plugin.egg-info/PKG-INFO writing dependency_links to ccloud_netbox_dashboard_plugin.egg-info/dependency_links.txt writing top-level names to ccloud_netbox_dashboard_plugin.egg-info/top_level.txt writing manifest file 'ccloud_netbox_dashboard_plugin.egg-info/SOURCES.txt' reading manifest file 'ccloud_netbox_dashboard_plugin.egg-info/SOURCES.txt' writing manifest file 'ccloud_netbox_dashboard_plugin.egg-info/SOURCES.txt' running build_ext Creating /home/i518240/projects/netbox/venv/lib/python3.8/site-packages/ccloud-netbox-dashboard-plugin.egg-link (link to .) Adding ccloud-netbox-dashboard-plugin 0.1 to easy-install.pth file Installed /home/i518240/projects/netbox_dashboard Processing dependencies for ccloud-netbox-dashboard-plugin==0.1 Finished processing dependencies for ccloud-netbox-dashboard-plugin==0.1 after that I added the name to the configuration.py from the Netbox files # Enable installed plugins. Add the name of each plugin to the list. PLUGINS = [ 'ccloud-netbox-dashboard-plugin', ] As respones, I get the following message when I try to start the server django.core.exceptions.ImproperlyConfigured: Unable to import plugin ccloud-netbox-dashboard-plugin: Module not found. Check that … -
'QuerySet' object has no attribute 'friends'
I am building a BlogApp and I was building a Feature BUT i am stuck on a Error. when i open Detail page then i keep getting :- 'QuerySet' object has no attribute 'friends' views.py def detail_view(request,id): data = get_object_or_404(Post,id=id) user = Profile.objects.all() post = get_object_or_404(Post,id=id) if post.allow_comments == 'everyone': if request.method == 'POST': if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('detail_view',id=id) else: comment_form = CommentForm() elif post.allow_comments == 'friend' and request.user in user.friends.all(): if request.method == 'POST': if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('detail_view',id=id) else: comment_form = CommentForm() context = {'post':post,'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'show_more.html', context ) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) name = models.CharField(max_length=100,default='') friends = models.ManyToManyField("Profile",blank=True) email = models.EmailField(max_length=60,default='') def __str__(self): return f'{self.user.username}' CHOICES = ( ('everyone','Every One'), ('friend','friend only'), ('none','Nobody'), ) class Post(models.Model): post = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') allow_comments = models.CharField(max_length=30,choices=CHOICES,default='everyone') def __str__(self): return self.post_title urls.py path('<id>',views.detail_view,name='detail_view'), Explanation of views.py My code is supposed to , When i click on friends only then it should check request.user friends list AND if request.user is exist then comment form will show. BUT this is keep showing me … -
Django - Days of the week (int) isn't rendering a string
I have a model in my app that stores the a single day of the week as: DAYS = ( (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday') ) day = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(0)], blank=True, choices = DAYS) According to the Django Documentation,: The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name However, that doesn't seem to be the case for me. For instance, in this template here in the same app, when I have something like: {{q.day}} This gives me: 1 instead of Tuesday. I tried some suggestions from SO, including creating your own model, and even considered passing custom functions through Jinja2, though I feel this to be unnecessarily complex. What would be the best way to go about this. Do I not understand the functionality of this clearly? Note: I want to store the day to be int because my app is running some complex algorithms and I want to just convert it for display purposes. -
Django channels custom permissions system
So I have a system where users can be part of models called boxes through the model member. Member models have their own set of roles which in turn have their own permissions. I have specific methods which determine which set of permissions a member has in a box. So now I have a websocket group named 'box_{box_id}' to which members can connect. Outbound events such as box related model creation are sent to this group. However, some members should not listen to certain events sent based on the permissions they have. This is a sample message that would be sent to the group which denotes an event {'event': EVENT TYPE, 'data': EVENT DATA} So now, for example, an user cannot listen to the event with type UPLOAD_CREATE if he doesnt have READ_UPLOADS permissions in the box How can I implement such checks using django channels? -
awsebcli: installed EB CLI with python 3.9 version via homebrew. Python 3.7 is used in project - potential problems?
I need to run AWS Elastic Beanstalk for deploying django (Django==3.1.5) project. So I've recently installed EB CLI (macOS) 3.19, which by default installed with Python 3.9.1 via Homebrew. But I have python 3.7 installed and using it for my project's configuration: python3 --version Python 3.7.6 Would it cause any problem in further deploy? Should I delete it and install via pip? Any help is appreciated. Thank you a lot! -
Save many-to-many field on object create - Django DRF
Pardon me if this is an obvious question. I've searched different answers but they don't answer my specific case. I have a model that has a many-to-many field relationship. When I create a new object via DRF rest API, the normal fields of the object (model) are saved correctly but the many-to-many related field remains empty. My model with the many-to-many related field: class CustomerProfile(models.Model): ... stores = models.ManyToManyField(Store) # <- the related field first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=60, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.first_name) The related (store) model: class Store(models.Model): store_name = models.CharField(max_length=30, unique=True, null=True) ... def __str__(self): return str(self.store_name) My serializer: class CustomerSerializer(serializers.ModelSerializer): stores = StoreSerializer(read_only=True, many=True) class Meta: model = CustomerProfile fields = ['stores', 'first_name', 'last_name', 'email', 'phone'] My view: class CustomerCreate(generics.CreateAPIView): queryset = CustomerProfile.objects.all() serializer_class = CustomerSerializer My post: axios({ method: "POST", url: this.api_base_url + "api/.../customer_create/", data: { first_name: 'Tom', last_name: 'Hardy', email: 'name@gmail.com', phone: '01234567898', stores: ['store_name',], // this is the store I want to link the customer to } }) When I post to this endpoint, an object is created but the stores array is always empty. Results: data: email: "name@gmail.com" first_name: "Tom" last_name: "Hardy" … -
How can I add multiple items at the same time that have foreign key but I want to assign them later in Django?
Let's say We have 3 Models in Django Company Model, Car Model and Engine Model. Each Company has Many Cars but each Car belongs to one Company. (One Company to Many Cars). Each Car has 1 Engine and each Engine belongs to 1 Car I want when I add a Company to initially create 10(fixed number) cars in that company and each car have engine as empty to assign it later. Because not every car has engine right now but it might be in the future. -
Why do I get error "Could not find a version that satisfies the requirement scipy==1.5.3" when running "pip install -r requirements.txt"?
I am trying to install all needed modules for an existing Django project. When I run pip install -r requirements.txt I get the following errors: ERROR: Could not find a version that satisfies the requirement scipy==1.5.3 ERROR: No matching distribution found for scipy==1.5.3 I'm running Python 3.9.1. Why am I getting those errors? This is as much as I could include from the output: Collecting scipy==1.5.3 Using cached scipy-1.5.3.tar.gz (25.2 MB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\knowe\documents\django\mbrain-gui\scripts\python.exe' 'c:\users\knowe\documents\django\mbrain-gui\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Knowe\AppData\Local\Temp\pip-build-env-33savj39\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- wheel setuptools 'Cython>=0.29.18' 'numpy==1.14.5; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.14.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.6'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'pybind11>=2.4.3' cwd: None Complete output (544 lines): Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX"' don't match your environment Ignoring numpy: markers 'python_version == "3.7" and platform_system != "AIX"' don't match your environment Ignoring numpy: markers 'python_version == "3.6" and platform_system == "AIX"' don't match your environment Ignoring numpy: markers 'python_version == "3.7" and platform_system == "AIX"' don't match your environment Ignoring numpy: markers 'python_version >= "3.8" and platform_system == "AIX"' …