Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django subqueries too slow
I'm working on a project in which users can have one profile, each profile can have many accounts, and an account can have many payments. The important parts of the models are the following: class Profile(models.Model): username = models.CharField(max_length=250) account = models.ForeignKey(Account) class Account(models.Model): payment = models.ForeignKey(Payment) class Payment(models.Model): amount = models.DecimalField(max_digits=8, decimal_places=2) account_id = models.CharField() # An unique id for the account the payment belongs I have to create an annotation in the Profile model with the Sum of the amounts of all payments from that user to manipulate this data with pandas afterwards. I managed to create a QuerySet using nested subqueries to get the job done, but this operation is extremely slow (slower than iterating through all of the profiles to calculate this value). Here is how I did it: payment_groups = Payment.objects.filter(account_id=OuterRef("pk")).order_by().values("account_id") payments_total = Subquery(payment_groups.annotate(total=Sum("amount")).values("total"), output_field=models.DecimalField()) account_groups = Account.objects.filter(profile=OuterRef("pk")).order_by().values("profile") accounts_total = Subquery(account_groups.annotate(total=Sum(paymments_total)).values("total"), output_field=models.DecimalField()) profiles = Profile.objects.all().annotate(account_total=acount_total) What in this code is making the subqueries so slow? I have done similar subqueries before to get the sum of fields in a child model. I know that doing this in a grandchild is more complex and requires more time but it shouldn't be that slow. Is there a … -
Compare and change DateTime object in SQL
I have model in my django project, which consists field like like given below uploadedTime = models.DateTimeField(auto_now_add=True, blank=True) And this saves dateTime object something like this.. 2022-03-21 17:53:15.156665 I want to make such a function which will take this dateTime object from database and will compare this with current dateTime() object, And if there's more than 2 hours gap between them then it will return true else false. Inshort I want all the entries from database which were inserted to database two hours ago. I tried many ways and reading docs but can't find a correct way, Can anyone guide me how to do this? Thank You :) -
How to give access to a object of a model to different users in django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to add students in a particular class by inviting students or by "clasroom_id". I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict) -
create text for django class without importing all django code
I am writing a desktop application around objects that will be downloaded from a django website. On the desktop application I will load a json file coming from the website. Therefore I need a set of classes in my desktop application , lets call them WClassA, wClassB, .... and a set of classes in my django application DClassA, DClassB. I would like to avoid to write the classes twice. What is the solution to avoid code duplication? I cannot import Django classes in my application because this would require to import all django. I thought about defining having a "fake django" Model file in my desktop application. But it loos kind of dirty. -
Django I'm trying do perform a simple task, display on the page whatever was input in a textfield
All I want is the user to type in something in a single textfield and have the input displayed on the same page by the form. Please help!!!! I tried so many solutions nothing seems to work and its such a simple task please see my code: views.py def math_drills(request): num1 = random.randint(0,100) num2 = random.randint(0,100) total = num2 + num1 if request.method == 'POST': form = Addition(request.POST) u_i = request.POST['uans'] return redirect('math_drills_url') return render(request,'math_drills.html',{ 'num1':num1, 'num2':num2, 'total':total, }) html <div class="col-lg-12"> <script type="text/javascript"> </script> <label class="" id="num1" name="">{{num1}}</label> + <label class="" id="num2" name="">{{num2}}</label> = <form action="" method="post"> {% csrf_token %} <input id="your_name" type="text" name="uans" value="" id="" style="width:2%;"> <input type="submit" value="add"> </form> </div> -
How to add list_display fields from a reverse relationship in django admin
I'm pretty new to django and the admin module. I'm looking for a way to add on a admin class some fields that i query through a reverse relationship. I can currently retrieve the interesting fields and put them in one column thanks to a specific function using list_diplay, but i cannot manage to create a list_display field BY returned query object: as example, now I get as column: |Inventory_id| Mousqueton1 | | 22 | foo1,foo2 | and i would like to have this kind of output, to easily create filters: |Inventory_id| Mousqueton1 | Mousqueton2 | | 22 | foo1 | foo2 | Here's my current models.py class Kit(models.Model): inventory_id = models.CharField(max_length=20,unique=True) description = models.TextField(null=True) creation_date = models.DateField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) class Mousquetons(models.Model): inventory_id = models.CharField(max_length=20,unique=True) serial = models.IntegerField(unique=False) description = models.TextField(null=True) creation_date = models.DateField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) kit = models.ForeignKey(Kit,on_delete=models.PROTECT,null=True) and admin.py @admin.register(Kit) class KitAdmin(admin.ModelAdmin): list_display= ['inventory_id','m'] def get_queryset(self, obj): qs = super(KitAdmin, self).get_queryset(obj) return qs.prefetch_related('mousquetons_set') def m(self, obj): return list(obj.mousquetons_set.all()) Maybe my data modeling is not the right way to perform this kind of operation, Any advice would be great. Thanks ! -
django model form initial instance does not add images
hi guys I am trying to set up a simple model form that has some instance as initial values, I have an image field and it causes problems because it is required, and the initial value is empty, I know I could get around it by setting it to not required and validating it in a custom validation but I was wondering if there was a simpler way or maybe a library to this this is my form class adminPackageForm(forms.ModelForm): class Meta: model = package fields = ("__all__") and I am rendering it using the crispy tailwind theme -
Django - sorting results ("choice") by number of votes
I don't know how to display on the page the result of each "choice" in descending order depending on the number of "votes" received. Please help me with a solution. Below is my setup. Thank you! models.py class Question(models.Model): question_text = models.CharField(max_length=200, verbose_name='Intrebare') pub_date = models.DateTimeField('publicat la:') def __str__(self): return self.question_text class Meta: verbose_name = 'Intrebari sondaj' verbose_name_plural = 'Intrebari sondaj' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200, verbose_name='') votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Meta: verbose_name = 'Variante raspuns' verbose_name_plural = 'Variante raspuns' views.py # preluare si afisare intrebari din sondaj def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'sondaj/index.html', context) # afisare optiuni aferente fiecarei intrebari din sondaj si intrebare in sine def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Nu exista sondaje publicate") return render(request, 'sondaj/detail.html', {'question' : question}) # preluare si afisare rezultate la nivelul fiecarei intrebari sondaj @login_required(login_url='/') def results(request, question_id): question = get_object_or_404(Question, pk=question_id) comments = question.comments return render(request, 'sondaj/results.html', {'question': question, 'comments' : comments}) # listare optiuni de ales pentru fiecare intrebare din sondaj def vote(request, question_id): #print (request.POST['choice']) question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # reafisare intrebare sondaj … -
How to access the actor of a django notification in a usable format?
I am using django-notifications (here is the code) to create notifications for my web app. I have the issue of whenever I try to access the the actor object e.g. via Notification.object.get(id=1).actor I get the following exception: ValueError: Field 'id' expected a number but got '<property object at 0x7fc171cc5400>'. which then causes then exception: ValueError: invalid literal for int() with base 10: '<property object at 0x7fc171cc5400>' Here is the code for my signal: @receiver(post_save, sender=ClubJoinRequest) def notify_owner_of_request(sender, instance, created, **kwargs): """ Notification for when a user has requested to join a club, the club owner will receive a notification. """ if created: notify.send( sender=sender, actor = instance.user, verb = "requested to join ", recipient = instance.club.owner, action_object = instance, target = instance.club, ) No matter what kind of object or value I make the actor it always has the same error. To note, I can access action_object, target, verb, and recipient perfectly fine, and the notification does work (there is one made and correctly). The Notification model from notification-hq has the following attributes: actor_content_type = models.ForeignKey(ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_object_id = models.CharField(max_length=255) actor = GenericForeignKey('actor_content_type', 'actor_object_id') accessing actor_content_type gives me this: <ContentType: clubs | club join request> even though it should … -
I'm trying populate script where I kept os.environ.setdefault('DJANGO_SETTING_MODULS','todolist.settings') before django.setup() but its not working
import os os.environ.setdefault('DJANGO_SETTING_MODULS','todolist.settings') import django django.setup() import random from todo.models import Todo from faker import Faker fakegan = Faker() todos = ['goals','workout','2lit water'] def add_todo(): q = Todo.objects.get_or_create(title=random.choice(todos))[0] q.save() return t def populate(N=5): for entry in range(N): top = add_todo() fake_title = fakegan.title() if __name__ == '__main__': print('populating fake_data') populate(20) print('populating complated!') Error: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
mySQL: LEFT JOIN without repeatition | any other idea to get this result in Python
It's the whole day I am trying to manage a SQL query: SELECT t1.id, t2.name, t3.pressure, t4.therapy FROM tbl_user_details as t1, tbl_user_details_2 as t2 LEFT JOIN tbl_pressure as t3 ON (t3.id=t2.id) LEFT JOIN tbl_therapy as t4 ON (t4.id=t2.id) WHERE t2.id = t1.id that gives me the following result (each column comes from a different table): as you can see, it does repeat the fields id, name and the last pressure in order to fill "otherwise blank spaces". I found several posts about this topic but none of the solution fitted for me. I would like to get a result such as the following, indeed: My final goal: process the resulting array and convert it as a csv to export the data. I am working with Django-Python and at first I tried to organize the CSV programmatically starting from zero - then I thought about asking mySQL to get the hard work done. And it did, just with this problem. As for me would it be great also to "merge" horizontally the records of each table given the same ID. Any idea how I may try to solve this? Thank you for your future help. -
How can I make one user can give only one rating to an item?
How can I make one user can give only one rating to an item? I read about UniqueConstraint but I can't understand how to use it here. models.py #... User = get_user_model() class Item(models.Model): id = models.PositiveIntegerField( primary_key=True, validators=[MinValueValidator(1)]) is_published = models.BooleanField(default=True) name = models.CharField(max_length=150) text = models.TextField(validators=[validate_correct]) tags = models.ManyToManyField('Tag', blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name #... class Rating(models.Model): id = models.PositiveIntegerField( primary_key=True, validators=[MinValueValidator(1)]) EMOTION_TYPES = ( (1, 'Hatred'), (2, 'Dislike'), (3, 'Neutral'), (4, 'Adoration'), (5, 'Love'), ) star = models.IntegerField(null=True, choices=EMOTION_TYPES) -
Django app with Heroku with a virtual display
I have an app that uses Python Turtle to draw images. I use tkinter to create a window and PIL to do an ImageGrab to save a PNG. How do I run this on Heroku where I cannot directly access the server and specify a virtual display? I can make this work with Xvfb on my own server, but I don't know how to use Xvfb with Heroku. Everything I can find online about this is from 2015, so I highly doubt the solutions presented there are still relevant. -
Send information with the post method in the rest framework
I want to add a new comment with the post method, but it gives an error {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ModelBase.', code='invalid')]} Serializers : from rest_framework import serializers from .models import Products,ProductsComments class ProdcutsSerializers(serializers.ModelSerializer): colors = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') category = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') sizes = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') class Meta: model = Products fields = '__all__' class ProductsCommentsSerializers(serializers.ModelSerializer): user = serializers.SlugRelatedField(many=True,read_only=True,slug_field='id') product = serializers.SlugRelatedField(many=True,read_only=True,slug_field='id') class Meta: model = ProductsComments fields = '__all__' Views : from rest_framework.decorators import api_view,permission_classes from rest_framework.response import Response from rest_framework import status from .serializers import * from .models import * @api_view(['GET']) def products_list(request): products = Products.objects.all() data = ProdcutsSerializers(products,many=True).data return Response(data) @api_view(['GET']) def products_comments_list(request): products_comments = ProductsComments.objects.all() data = ProductsCommentsSerializers(products_comments,many=True).data return Response(data) @api_view(['POST']) def products_comments_add(request): data = ProductsCommentsSerializers(data=ProductsComments) if data.is_valid(): print('Ok') else: print('not') #print(data) print(data.errors) return Response({"M": "not"}) -
Django Trying to render the data that i added to a DetailView via get_context_data()
I'm making a simple real estate app where users can create Estates. The Estate model has one main image, but the user can upload multyple images using another model and form for that. On the estate details page which is a DetailView I want to display the images and info about the user who is the owner of the current Estate. I'm passing the above info using get_context_data(). While debugging everything seems fine to me the context contains the info about the user and the images but this information is not rendered. Can you please help me with this issue? my user model is linked to the current estate with the following: class Estate(models.Model): user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) This is the EstateImagesModel class EstateImages(models.Model): IMAGE_UPLOAD_TO_DIR = 'estates/' estate = models.ForeignKey( Estate, related_name='images', on_delete=models.CASCADE, ) image = models.FileField( upload_to=IMAGE_UPLOAD_TO_DIR, ) and the detail view is class EstateDetailsView(views.DetailView): model = Estate template_name = 'main/estates/estate_details.html' context_object_name = 'estate' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['is_owner'] = self.object.user == self.request.user estate_images = list(EstateImages.objects.filter(estate_id=self.object.id)) seller = Profile.objects.filter(user_id=self.object.user_id) context.update({ 'estate_images': estate_images, 'seller': seller, }) return context -
How to make a value unique for 2 fields in Django model?
I need all values in 2 fields to be unique for both of them. I have username and email in my custom User model. I want to prevent this: user1 - username = some_username, email = MY@EMAIL.COM user2 - username = MY@EMAIL.COM, email = some_email I don't want to constrain '@' or '.' so what can I do? -
Django CKEditor Code Snippet not rendered correctly
I am building a Django blog that supports code snippets for both post and comments. The following is my CKEditor config in settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join( [ 'codesnippet', 'widget', 'dialog', ]), }, 'comment': { 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['NumberedList','BulletedList'], ['Indent','Outdent'], ['Maximize'], ['CodeSnippet'] ], 'extraPlugins': ','.join( [ 'codesnippet', 'widget', 'dialog', ]), } } All instances of RichTextField in the models and forms are replaced with RichTextUploadingField. Then I ran the migrations. My text field has the code snippet button. Clicking the button allows the end users to post code snippets. But when the form is submitted the snippet is not marked down correctly. There are no markdown nor syntax highlighting. Am I missing something within the configs? Or does Django's form have limited support for code snippets? -
How to change boolean member into two checkbox for search
I have boolean member in Model. TYPE_SET_CHOICES = ( (True, 'OK'), (False, 'NG'), ) is_OK = models.BooleanField(choices=TYPE_SET_CHOICES,default=False) then I want to make search form for this model. My purpose is showing two checkboxs and enable user to check both ok row and ng row. is_OK_check = forms.TypedMultipleChoiceField( required=False, coerce=str, label='', choices=(('', 'OK'), ("","")), # What should be here? maybe something confused. widget=CheckboxSelectMultiple) How can I make this ?? -
Django(view) - Ajax Interaction?
I want to send django values to the server using ajax. parts.html <h1>{{parts.name}}</h1> <form class="form-group" method="POST" id="part_solution_form"> csrf_token %} <label for="part_solution">Write your solution here</label> <input id="part_solution" name="part_solution" type="text" class="form-control" required> </form> views.py def selected(request, part_id): parts = Part.objects.get(id=part_id) return render(request, "cram/parts.html", {"parts": parts}) def check_parts(request): if request.method == 'POST': part = request.POST['part'] solution = request.POST['solution'] parts.js $("#part_solution_form").on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/cramming/check_fib/', data: { part: $(_________), //{{ parts.id }} I want to send solution: $("#part_solution").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val() }, success: function () { alert("SuccessFull") }, error: function () { alert("Error") } }) } ); I want to send value {{part.id}} from selected function through parts.html using ajax to check_parts. I don't know the value that I left empty in js to get value from HTML. Thanks in advance. Also, I want check_parts response (if it contains JsonResponse) in same ajax in success. -
Django administration Site. 'Delete multiple objects' produces ValidationError
When attempting to delete multiple rows, which have a one to one relationship with two other tables I received the following error: ['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] The models are set up as such: class Media(models.Model): date = models.DateField(primary_key=True, unique=True) received_url = models.CharField(max_length=200, blank=True, null=True) class Api(models.Model): media = models.OneToOneField(Media, on_delete=models.CASCADE) request_url = models.CharField(max_length=200) class Text(models.Model): media = models.OneToOneField(Media, on_delete=models.CASCADE) title = models.CharField(max_length=100) copyright = models.CharField(max_length=200, blank=True, null=True) I am trying to delete the items in the Home › My_App_Main › Medias › Delete multiple objects from the Django administration site. Which presents me with the following: Are you sure? Are you sure you want to delete the selected medias? All of the following objects and their related items will be deleted: Summary Medias: 2 Apis: 2 Texts: 2 Objects Media: 2022-03-21 Api: 2022-03-21 Text: 2022-03-21 Media: 2022-03-20 Api: 2022-03-20 Text: 2022-03-20 I then click Yes, I'm Sure Which triggers then triggers the error. Checking the POST request in the network log for the browser I noted the dates appear to be in the wrong format: _selected_action […] 0 "March+21,+2022" 1 "March+20,+2022" action "delete_selected" post "yes" I tried in both … -
How to add/give access to user to a model object and how to show all object a particular user created in his homepage
I am doing an online classroom project like google classroom. So I created a model for teachers to add courses now if a teacher adds 2-3 or more courses how will I show all of his created courses on his homepage like rectangular cards we see on google classroom also how I add a student to that class I created a unique "classroom_id" field in course model how I will design that student can join that particular class by entering the classroom id. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) -
Querying other Model in class-based view produces error
I have two tables, in one of which the possible items with their properties are recorded, in the other the stock levels of these respective items are recorded. class itemtype(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=100) group_name = models.CharField(max_length=100) category_name = models.CharField(max_length=100) mass = models.FloatField() volume = models.FloatField() packaged_volume = models.FloatField(null=True) used_in_storage = models.BooleanField(default=False, null=True) class Meta: indexes = [ models.Index(fields=['item_id']) ] def __str__(self): return '{}, {}'.format(self.item_id, self.item_name) class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount_total = models.IntegerField(null=True) price_avg = models.FloatField(null=True) amount = models.IntegerField(null=True) price = models.FloatField(null=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}, {} avg.: {} ISK'.format(self.material, self.amount, self.price) I have a ModelForm based on the table material_storage, in which a checkbox indicates whether transport costs should be included or not. In the form_valid() method of this ModelForm class the calculations are performed. To do so, I have to retrieve the volume per unit of the given item to use it for my transport cost calculations. Trying to geht that value the way shown below leads to an error I don't really understand. class MaterialChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.item_name class NewAssetForm(forms.ModelForm): material = MaterialChoiceField(models.itemtype.objects.filter(used_in_storage= True)) needs_transport = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(NewAssetForm, self).__init__(*args, **kwargs) self.fields['amount'].widget.attrs['min'] … -
Django testing - group object not working when using factory_boy
I'm trying to streamline my testing by using factory_boy. I would like to test views that depend on some group permissions. If I write my test by creating a user and group in setUpTestData, I can get the test to work. However, if I create the user and group using factory_boy, it doesn't look like the permissions are set in the test. view @method_decorator([login_required, teacher_required], name='dispatch') class GradeBookSetupCreateView(PermissionRequiredMixin, UpdateView): raise_exceptions = True permission_required = 'gradebook.change_gradebooksetup' permission_denied_message = "You don't have access to this." form_class = GradeBookSetupForm model = GradeBookSetup success_url = "/gradebook/" def get_object(self, queryset=None): try: obj = GradeBookSetup.objects.get(user=self.request.user) return obj except: pass The permission problem is from the PermissionRequiredMixin and permission_required. There is also a permission in the decorator but that is working fine. Here is a test that works: class GradeBookSetupTests(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username='teacher1', email='tester@email.com', password='tester123' ) cls.user.is_active = True cls.user.is_teacher = True cls.user.save() teacher_group, created = Group.objects.get_or_create(name='teacher') teacher_group = Group.objects.get(name='teacher') content_type = ContentType.objects.get( app_label='gradebook', model='gradebooksetup') # get all permssions for this model perms = Permission.objects.filter(content_type=content_type) for p in perms: teacher_group.permissions.add(p) cls.user.groups.add(teacher_group) cls.user.save() print(cls.user.groups.filter(name='teacher').exists()) my_g = cls.user.groups.all() for g in my_g: print(g) cls.gradeb = GradeBookSetupFactory(user=cls.user) def test_signup_template(self): self.client.login(username='teacher1', password='tester123') response = self.client.get(reverse('gradebook:gradebooksetup')) self.assertEqual(response.status_code, 200) … -
Retrieving data without refreshing the page with ajax in django
I can post with ajax, but when I want to pull data without refreshing the page, I can only do it 2 times, then the button loses its function. <div> <input type="hidden" name="producecode" class="pcode" value="{{per.produceCode}}" /> <input type="hidden" name="useremail" class="uponequantity" value="{{user.username}}" /> <button class="btn btn-sm btn-primary upoq"><i class="fa fa-plus"></i></button></div> and jquery $.ajax({ type: "POST", url: "/uponequantity/", headers: { "X-CSRFToken": '{{csrf_token}}' }, data: { "producecode":$(this).parent().find(".pcode").val(), "useremail":$(".uponequantity").val(), }, success: function() { window.location.assign('/basket/'+"?b="+$(".uponequantity").val()); } }); /*$.ajax({ url:'/baskett/'+"?b="+$(".uponequantity").val(), headers: { "X-CSRFToken": '{{csrf_token}}' }, type:'POST', success:function(result){ $('.basket').html(result); } }); */ }) -
Rebase git branch upon 2 pull requests
I have a Django project with 4 other members, and I'm creating a model, let's call it "model M". Model M is having 2 foreign keys, the first is model A and the other is model B. At this moment, model A and model B are both not approved and merged to the main branch on our GitHub repo, and both on different pull requests, and I need to rebase my current branch of creating model M upon those 2 pull requests of A and B. I know I can rebase my branch on 1 pull request, but is it possible to rebase it upon 2 different pull requests? If so, how can I do it without having them rebase on each other (because they don't really rely on each other)? Thanks! I've rebased my branch on the first pull request, model A. But when I've tried to rebase the current branch on model B as well, I got conflicted (because they don't have the same commit history).