Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to loop a custom model form in django?
Is it possible to create multiple objects for a model in django by looping the same form in a for loop. I am using a custom model form. My template is: {% for query in queryset %} <form method="POST" action="{% url 'academics' %}" style=" padding: 5%"> {% csrf_token %} <input type="text" name="Student" class="form-control" id="id_Student" value="{{query}}"> <input type="text" name="Subject" class="form-control" required id="id_Subject"> <input type="checkbox" name="Presence" id="id_Presence"> <button type="Submit" id="submit">Submit</button> {% endfor %} <button type="Submit" id="submit">Submit</button> </form> My models.py is: class Attendance(models.Model): Student = models.CharField(max_length=100, blank=False) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' My views.py is: def academics(request): if request.user.is_staff: form = forms.AttendanceForm() context = { 'form': form, 'queryset': User.objects.filter(profile__Year='SY',profile__Department='CSE') } if request.method == "POST" : form = forms.AttendanceForm(request.POST) if form.is_valid(): student = request.POST.get('Student') hour = request.POST.get('Hour') subject = request.POST.get('Subject') boolean = request.POST.get('Presence') def bool(boolean): if boolean == 'on': return 'True' else: return 'False' form = Attendance(Student=student,Hour=hour,Subject=subject,Presence=bool(boolean)) form.save() return render(request, 'console/academics.html',context) Currently i can create multiple objects, but with the same values of the last form. ie, the object is created with the values of last form. Here i have looped the form so that n number of forms will … -
how can we prefetch the property of model , so that we will not have to request db everytime when the list of objects will be serialized in django
this is my serializer ---> class CurrentUserCalendarSyncSerializer(BaseOccurrenceSerializer): select_related_fields = ('event__group',) organization_name = serpy.StrField(required=False, attr='event.group.organization_name') division_name = serpy.StrField(required=False, attr='event.group.division_name') this is my model---> class OrganizationGroup(MPTTModel, AddressMixin, GeoLocationMixin, Timestampable): @property def organization_name(self) -> Optional[str]: return None if self.is_root_node() else self.get_root().name @property def division_name(self) -> Optional[str]: return None if self.get_ancestors().count() < 2 else self.get_ancestors()[1].name when i am serializing the list of occurrences it hits the db for multiple times and also takes time to get the response, i want to prefetch all these in view where i have created a list of object . -
Missing 'user' argument in a django UpdateView with two forms
I have a view on which there is two forms, one is form updating user password and another form with other informations such as email and username. I have followed tutorials and ended up with this code: views.py: class EditProfileView(PermissionRequiredMixin, generic.UpdateView): permission_required = 'is_staff' template_name = 'profile/edit-profile.html' form_class = UserForm second_form_class = PasswordChangeForm success_url = reverse_lazy('acp:edit-profile') model = User def get_object(self, queryset=None): return self.request.user def get_context_data(self, **kwargs): context = super(EditProfileView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET) return context def post(self, request, *args, **kwargs): self.object = self.get_object() if 'form' in request.POST: form_class = self.get_form_class() form_name = 'form' else: form_class = self.second_form_class form_name = 'form2' form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.render_to_response(self.get_context_data(form=form)) where i have this in my template: <input type="submit" name="form2" class="profile-buttons" value="Alterar senha"> Somehow the code breaks in this line: form = self.get_form(form_class) with the message "TypeError: init() missing 1 required positional argument: 'user'" -
change_view() missing 1 required positional argument: 'object_id' is showing in the superuser page?
In the admin section the elements when clicked on show object_id missing. The comment should be shown. But the error is showing. -
How to read file from python csv in html?
I have a problem that I want to read files from csv and make loop in it instead of writing one by one in html page. How to read and fetch files from csv in html using python code in django. This code is of index.html. <body> <center><h1>Article Writing Sites</h1></center> <div class="row"> <div class="column"> {% with open('file.csv') as open%} </div> <div class="column"> <p>this is next paragraph</p> </div> </div> </body> -
Django will run the function content twice when using render
I am sorry that my English is not good. My problem is that refreshing the page in Google Chrome will cause the function with render to run twice But run it once in the Firefox browser. I don't know if this is a problem with Google Chrome or something else?(I hope to get help, thank you) def add_teacher(request): Teacher.objects.create(username='zhangsan',avatar='https://static-image.xfz.cn/11.jpg',jobtitle='aaa',profile='bbb') print('=====') return render(request,'course/course_index.html') I ran the same content in Google Chrome,And only one data is created in Firefox. but the results are different. Two teachers' data will be created when Google Chrome refreshes the page, and only one will be created in Firefox. Pycharm will also print out twice the content. -
How can I initialize my form Image and Integer fields with model data?
I've managed to initialize a CharField, but how can I do the same with ImageField and IntegerField? My forms.py: class GoodGet(forms.ModelForm): class Meta: model = Good_Get Size = forms.ModelChoiceField(queryset = Good.objects.all()) fields = '__all__' def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) self.fields['Name'].initial = Good.objects.get(id=good_id1) self.fields['Photo'].initial = Good.objects.get(id=good_id1) self.fields['Price'].initial = Good.objects.get(id=good_id1) for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes So, I need to write these strings correctly: self.fields['Photo'].initial = Good.objects.get(id=good_id1) self.fields['Price'].initial = Good.objects.get(id=good_id1) How? -
How to trigger multiple submit buttons with one button outside the form?
I am new to Javascript/jQuery. I came to know that i can trigger multiple buttons for one submit button. But i want to submit multiple forms which is actually in a loop. If you don't understand the question. Please look at this question also. I need to submit all the forms at once. -
redirecting to two different view from a form input
I have a PostForm model form to create posts for my blog app. Now the user has two options after filling the post form he/she can publish it immediately or can put it into the drafts for later publishing. when published the user will be redirected to that post's detail view but when drafted it will redirect to user's draft list view. I don't want to create a detail view for the draft posts. But I am not able to implement how can I redirect a user to two different views with the two different submit option (Publish and draft) in the form. create view model = Post template_name = 'blog/post_form.html' form_class = PostForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Create' return context def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) post_form.html model = Post template_name = 'blog/post_form.html' form_class = PostForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Create' return context def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) -
Error "could not be changed because the data didn't validate"
I can't update extended user profile In views.py: views.py def profile(request, user_id): user = get_object_or_404(User, id=user_id) user_info = get_object_or_404(UserInfor, user_id=user.id) if request.method == "POST": user_form = UserForm(data=request.POST or None, instance=user) profile_form = ProfileForm(data=request.POST or None, instance=user_info) user = user_form.save(commit=True) user_info = profile_form.save(commit=True) user.save() user_info.save() return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form, 'user_id': user_id}) else: user_form = UserForm(instance=user) profile_form = ProfileForm(instance=user_info) return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form, 'user_id': user_id}) How can I fix error? -
Non_field_errors no data provided in django webapi
I am new in Django and python. Now I am trying to do web API with Django and python. I can get the get request but when I request the post method, this error is shown "non_field_errors": [ "No data provided" ] View.py=> from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models import Allowance from .serializers import AllowanceSerializer # Create your views here. class AllowanceAPIView(APIView): def get(self,request,pk=None): if pk: allowance=get_object_or_404(Allowance.objects.all(),pk=pk) serializer = AllowanceSerializer(allowance) return Response({serializer.data}) allowance=Allowance.objects.all() serializer = AllowanceSerializer(allowance,many=True) return Response({"allowance":serializer.data}) def post(self,request): allowance = request.data.get('allowance') serializer = AllowanceSerializer(data=allowance) if serializer.is_valid(raise_exception=True): allowance_saved=serializer.save() return Response({"success":"Allowance '{}' created successfully".format(allowance_saved.AllowID)}) def put(self,request,pk): save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk) data = request.data.get('allowance') serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True) if serializer.is_valid(raise_exception = True): allowance_saved=serializer.save() return Response({"sucess": "Allowance '{}' updated successfully".format(allowance_saved.AllowID)}) def delete(self,request,pk): #Get object with this pk allowance = get_object_or_404(Allowance.objects.all(),pk=pk) allowance.delete() return Response({"message":"Allowance with id '{}' has been deleted.".format(pk)},status=204) urls.py inside app => from django.conf.urls import url from .views import AllowanceAPIView urlpatterns = [ url(r'^$', AllowanceAPIView.as_view(), name='post-listcreate'), url(r'^(?P<pk>\d+)/$', AllowanceAPIView.as_view(), name='post-listcreate') ] urls.py inside project => from django.conf.urls import url, include from django.contrib import admin from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api/auth/login/$', obtain_jwt_token, name='api-login'), url(r'^api/allowances_mas/', include('tmswebapi.urls')), ] sample API request=> { "AllowID": "Allow1", … -
Raw query must include the primary key in custom posgresql function
i did this function with pg/sql languaje,for example: dinamico('some_string') and i am using this function in a simple django views: def detalle_fondo(request,fondo): det_fondos=f.objects.raw('select * from dinamico(%s)',[fondo]) return render(request,'sw/det-fondos.html',{'det_fondos':det_fondos}) the problem is django ask me for the primary key but i don now how to doit throught a custom function. Can you help me out? -
Django celery crontab every weekday between certain hours with 2 hour dela
Trying to achieve the title exactly. This is the crontab I have: 'schedule': crontab( minute='*/15', hour='9,10,11,12,13,14,15,16,17,18,19,20', day_of_week="1-5") Now, what I'm having trouble with is adding a 2 hour delay when scheduling. The idea is faking staff interaction for approvals. Person signs up I want to delay a task from the time they sign up to approve their account ~2 hours later but only run this between the weekdays during certain times (when staff would actually be working...) for a full "fake". So, any suggestions for the delay. To my understanding the tasks will just stall until they can be run by the beat schedule if someone signs up outside these hours, but I'm unclear how the delay works here. -
I have try to install pip install mysqlclient on mac give some error?
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz ERROR: Complete output from command python setup.py egg_info: ERROR: sh: mysql_config: command not found Traceback (most recent call last): File "", line 1, in File "/private/var/folders/2b/1sy6xpk55qz87d1dx31qn92w0000gn/T/pip-install-ke4S5K/mysqlclient/setup.py", line 16, in metadata, options = get_config() File "setup_posix.py", line 51, in get_config libs = mysql_config("libs") File "setup_posix.py", line 29, in mysql_config raise EnvironmentError("%s not found" % (_mysql_config_path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/2b/1sy6xpk55qz87d1dx31qn92w0000gn/T/pip-install-ke4S5K/mysqlclient/ -
How to create a submit button for each field on a form that will create a model object and post it at the end of list in the view
I am trying to create submit buttons for each of the fields so when a user clicks the create button that is next to the field the input from that field will create a sub model object and that object will be placed at the end of the list on the same page under the correct main model object it was created for. I have tried using formsets but when using them my fields would go away so typing in any input was impossible. My most recent fix attempt was to try to manipulate the view to catch the id of the form but that was a fail. views.py def post(self,request,pk,context=context): rule_form = RuleForm(request.POST) arg_form = ArgumentForm(request.POST) if request.method=='POST' and 'RuleButton' in request.POST: if rule_form.is_valid(): print(rule_form.cleaned_data) Rule.rules.create_rule ( **rule_form.cleaned_data, Topic = context['topic'], created_by = context['user'], creation_date = context['creation_date'] ) TopicDetailView.get(self,request,pk,context=context) else: print(rule_form.errors) TopicDetailView.get(self,request,pk,context=context) elif request.method=='POST' and 'ArgButton' in request.POST: if arg_form.is_valid(): print(arg_form.cleaned_data) ruleList = [] for rule in context['topic_rules']: ruleList += [rule.id,] context['arg_rule'] = Rule.rules.all().get(id=rule.id) Argument.arguments.create_argument ( **arg_form.cleaned_data, created_by = context['user'], Rule = context['arg_rule'] ) TopicDetailView.get(self,request,pk,context=context) else: print(rule_form.errors) TopicDetailView.get(self,request,pk,context=context) return render(request,self.template_name, context=context) topic_detail.html <h1>{{ topic }}</h1> <p>Create a Rule</p> <form method="POST"> {% csrf_token %} {{ rule_form }} <input type="submit" name="RuleButton" … -
ValueError: invalid literal for int() with base 10: 'category'
I'm using python 3.7 django 2.2 django rest framework 3.9.4 After running: python manage.py migrate An error comes out: ValueError: invalid literal for int() with base 10: 'category' This is my model: class Category(models.Model): name = models.CharField(max_length=40, default='', verbose_name="类别名", help_text="类别名") # 分类名 class Meta: verbose_name = "分类" verbose_name_plural = verbose_name def __str__(self): return self.name class Article(models.Model): ...code... category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类', default='') ...code... class Meta: ordering = ['-add_time'] verbose_name = "新闻" verbose_name_plural = verbose_name def __str__(self): return self.title # 在后台中以文章标题显示 Any friend can help? -
DELETE request using fetch doesn't work in Safari, but works in Chrome
I want to send DELETE request from frontend (React) to backend (Django REST Framework) but it fails with very little info. It works ok in Chrome but fails in Safari. Also it works ok with GET and POST requests, the only thing is that POST requests works only on second attempt (only in Safari, again). I've tried different CORS configurations but no luck. Django CORS configuration: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), } CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'http://localhost:3000', ) CORS_TRUSTED_ORIGINS = ( 'localhost:3000', 'http://localhost:3000', '*' ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( '*', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'access-control-allow-credentials', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-allow-origin', ) Frontend code: fetch('http://localhost:8000/api-v1/projects/'.concat(this.props.projectId), { method: 'DELETE', mode: 'cors', credentials: 'same-origin', body: {}, redirect: 'follow', referrer: 'no-referrer', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Access-Control-Allow-Headers': '*, Origin, X-Requested-With, Content-Type, Accept', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS', 'Access-Control-Allow-Credentials': true, 'Authorization': 'Basic ' + btoa('admin:pass'), },}).catch( e => console.error(e)); Django logs shows that DELETE request received and the response code is 301. Safari shows this in the console: [Error] The network connection was lost. [Error] Fetch API cannot load http://localhost:8000/api-v1/projects/54/ due to access control checks. [Error] Failed to load … -
How to get scheme from Django Response object?
I'm trying to determine whether a response is HTTP or HTTPS, but looking at dir(response) gives me no indication of such a possibility. I've looked at the Django docs here: https://docs.djangoproject.com/en/2.2/ref/request-response/ I'm trying to write a method to be called after each request. I would like to be able to call scheme on response, but obviously that is not possible. I want to achieve something like: def callback_after_request(self, response): if response.scheme == 'https': # do something to the headers How can I achieve this? -
Count more than one occurrence in a Django query
I have two models: Players and Tournaments. Players have also a type of game they play (dota, lol, magic, etc). They can participate in many tournaments at the same time (only once per Tournament). To manage the inscriptions, I use another model called TournamentMatch, that creates a new object for every inscription with the ID of the tournament and the player. I want to count the number of Players that have more than two inscription to tournaments and are, for example, dota players. I can easily achieve this with a for loop for every player, but for perfomance reasons, I want to achieve this using a Django query. For example, if I want to count the dota players that have one or more inscription, I will do: TournamentMatch.objects.filter( player__is_dota_player=True ).distinct( 'player' ).count() I'm sure is possible but I don't know how to count every ocurrence of distinct players on tournaments and only filter those that have more than one (and not only one). I will appreciate any help or pointers! -
What is proper way to link django-treebeard model with another django model as foreignkey?
I'm building a model which will show important facilities around stadium like depots,railway stations, hospitals, restaurants and bars etc and their distances. I've two models, one for Stadium and another for facilities around stadium. Facilities can be hierarchical if there are multiple options for the same. E.g. Stadium-1: -Hospital: - some hospital: 700 meters -Restaurant: - Chinese: - abc restaurant: 2km - Italian: - lmn restaurant: 300 meters - xyz restaurant: 1.2km The name of root node for each tree will be same as the name of stadium to which it'll be linked as foreign-key. Every stadium will have its own tree specifying important facilities around it and their distances from stadium. I am using Django-Treebeard for the purpose of creating facilities tree. My facilities model is MP_Node type. I'm using admin interface to add my data. When I try to link Stadium with facilities tree, it shows every node that was ever added in all tree models. This is messy. Imagine when data grows. It'll be a trouble. I've tried to link it as OneToOneField but nothing changed. class NearByFacilities(MP_Node): name = models.CharField(max_length=65, blank=True, null=True) distance = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) units = ( ('km', 'KiloMeters'), ('m', 'meters') ) … -
Parse a zip object using ast.literal_eval() or eval()
I have a zip object available in the Jinja template page, and when a user clicks some link I am sending that zip object as a request parameter. And then I try to parse the zip object using ast.literal_eval() but I am getting "Invalid syntax" error. I tried using eval() as literal_eval(). But both are giving me the same error. I searched for it but haven't found anything which describes how to parse a "" notation. data = request.GET movies,moviesindxs = zip(*literal_eval(data.get("movies"))) File "~/path/to/Django/app/views.py", line 198, in rate_movie movies, moviesindxs = zip(*literal_eval(data.get("movies"))) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 48, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 35, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 1 <zip object at 0x12d6549c8> -
How to filter integer timestamp field as choice of dates in django_filter
I have a working django-filter to filter later than a date, which is stored at the database level as an integer timestamp. Elsewhere I always represent that timestamp as a date in the template, but in the django_filter it shows the field value, which is a timestamp integer, of course. For example if my filter is: dispatch__gt = django_filters.NumberFilter(field_name='dispatch_time', lookup_expr='gt', label='Dispatched after') it would expect a timestamp input, which works fine but looks terrible. What I would like to do is have it display a choices filter based on a list of choices: newer than a year, newer than a month, newer than a week, etc. Can this be done with the django_filters.ChoiceFilter and a dynamically generated dictionary, or is there a better way? to be clear I am referring to this package: https://django-filter.readthedocs.io/en/master/index.html Thanks. -
How do I access the request params in order to authenticate an user
I would like to write a simple login form for my App. It is just a simple form, which sends data via post request to the django server. For authentification, I have to access the post request data, as mentioned in the django documentation but this doesn't work properly. This is my html form: <form method="POST" action="/login/">{% csrf_token %} <div class="form-group"> <label for="ID">User</label> <input type="text" class="form-control" id="ID" aria-describedby="User" placeholder="Username"> </div> <div class="form-group"> <label for="password">Passwort</label> <input type="password" class="form-control" id="password" laceholder="Passwort"> </div> <button type="submit" class="btn btn-primary">Einloggen</button> </form> This is my django code: def get_access(request): if request.method == 'POST': username = request.POST['ID'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) I get this Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 2.1.7 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'rest_framework', 'rest_framework.authtoken'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\felix\DEV\my_env\lib\site-packages\django\utils\datastructures.py" in __getitem__ 77. list_ = super().__getitem__(key) During handling of the above exception ('ID'), another exception occurred: File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\felix\DEV\my_env\Animoo\App\views.py" in … -
int() argument must be a string, a bytes-like object or a number, not 'OrderItem'? Django
I am creating an E-commerce now when I try adding an Item into the cart it returns the error above? It is complaining about this line of code in the view: else: order.items.add(order_item) View def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("core:product", slug=slug) Model class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username I need it to create a new item into the cart if it doesn't exist and if it exists inside the cart it increments the similar item by 1, instead of creating the same thing all over again. -
Django test setup fails when running single test file
The immediate symptoms: $ pytest …/apps/users/test/test_graph_permissions_command.py ============================= test session starts ============================== platform linux -- Python 3.6.8, pytest-4.6.2, py-1.8.0, pluggy-0.12.0 Django settings: dms.settings (from ini file) rootdir: /src/app, inifile: pytest.ini plugins: forked-1.0.2, celery-4.3.0, django-3.5.0, cov-2.7.1, xdist-1.28.0 collected 1 item …/apps/users/test/test_graph_permissions_command.py E ==================================== ERRORS ==================================== _ ERROR at setup of TestGraphPermissionsCommand.test_should_resolve_a_permission_hierarchy _ .venv/lib/python3.6/site-packages/pytest_django/plugin.py:519: in _django_setup_unittest request.getfixturevalue("django_db_setup") .venv/lib/python3.6/site-packages/pytest_django/fixtures.py:108: in django_db_setup **setup_databases_args .venv/lib/python3.6/site-packages/django/test/utils.py:174: in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:80: in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:123: in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) .venv/lib/python3.6/site-packages/django/core/serializers/__init__.py:128: in serialize s.serialize(queryset, **options) .venv/lib/python3.6/site-packages/django/core/serializers/base.py:90: in serialize for count, obj in enumerate(queryset, start=1): .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:120: in get_objects yield from queryset.iterator() .venv/lib/python3.6/site-packages/django/db/models/query.py:341: in _iterator yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size) .venv/lib/python3.6/site-packages/polymorphic/query.py:56: in _polymorphic_iterator o = next(base_iter) .venv/lib/python3.6/site-packages/django/db/models/query.py:55: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1087: in execute_sql sql, params = self.as_sql() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:474: in as_sql extra_select, order_by, group_by = self.pre_sql_setup() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:54: in pre_sql_setup self.setup_query() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:45: in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:219: in get_select cols = self.get_default_columns() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:666: in get_default_columns column = field.get_col(alias) .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:981: in get_col output_field = self.target_field .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:878: in target_field return self.foreign_related_fields[0] .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:632: in foreign_related_fields return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field) .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:619: in related_fields self._related_fields = self.resolve_related_fields() .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:604: in resolve_related_fields raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) E ValueError: …