Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how django related_name used with the special keyword /
I have three Model classes, Product, ShoppingCart, ShoppingCartItem In shoppingCartItem class the product field connect with Product class and used the related_name='+', but in ShoppingCart class in the sub_total() call the "item.product.get_price()". item is the related_query_name but the I have an issue with the .get_price() function. from django.utils import timezone from django.db import models class Product(models.Model): DISCOUNT_RATE = 0.10 id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() sale_start = models.DateTimeField(blank=True, null=True, default=None) sale_end = models.DateTimeField(blank=True, null=True, default=None) photo = models.ImageField(blank=True, null=True, default=None, upload_to='products') def is_on_sale(self): now = timezone.now() if self.sale_start: if self.sale_end: return self.sale_start <= now <= self.sale_end return self.sale_start <= now return False def get_rounded_price(self): return round(self.price, 2) def current_price(self): if self.is_on_sale(): discounted_price = self.price * (1 - self.DISCOUNT_RATE) return round(discounted_price, 2) return self.get_rounded_price() class ShoppingCart(models.Model): TAX_RATE = 0.13 id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) address = models.CharField(max_length=200) def subtotal(self): amount = 0.0 for item in self.shopping_cart_items: amount += item.quantity * **item.product.get_price() return round(amount, 2)** def taxes(self): return round(self.TAX_RATE * self.subtotal(), 2) def total(self): return round(self.subtotal() * self.taxes(), 2) class ShoppingCartItem(models.Model): shopping_cart = models.ForeignKey(ShoppingCart, related_name='items', related_query_name='item', on_delete=models.CASCADE) product = models.ForeignKey(Product, **related_name='+'**, on_delete=models.CASCADE) quantity = models.IntegerField() def total(self): return round(self.quantity * self.product.current_price()) -
Django - Should I set show_toolbar in production for management users?
I'm deploying my Django server to production. Obviously I'm settings DEBUG = False but I was wondering if I can safely set the SHOW_TOOLBAR_CALLBACK to my function that will return True when the user is a management user. e.g.: def show_toolbar(req): return (not req.is_ajax()) and req.user.is_authenticated and req.user.email == "admin@company.com" Is it not safe? Is there any reason NOT to do that? -
Unable to pass balance onto html: Django
I have created a payment portal app, wherein I need to pass a model and a user balance onto the HTML page. The model is passing fine, but I am having trouble in either passing the balance, or in using the passed balance in my HTML. Given below are the HTML and views.py files: HTML: <br> {% if balance %} <h3>Balance amount is {{ balance }}</h3> {% endif %} <h3>Select vendor to pay!</h3> views.py: def updatingBalance(request): if request.method=="POST": if 'form1' in request.POST: ven_id = request.POST.get("groupOfDefaultRadios") amount = request.POST.get("amt") x = employee.objects.get(name = request.user) x.balance = x.balance - int(amount) x.save() v = vendor.objects.get(id=ven_id) w = employee.objects.get(id=x.id) transaction.objects.create(vendor_id = v, emp_id=w,debit=amount,credit=0) y = employee.objects.get(name = request.user) return render(request, 'profiles/userLogin.html', {'model':y, 'balance':x.balance}) Any help is appreciated. Thank you. -
How to write unittests for Consumers in django channels?
A'm beginner in django-channels. I'm use channels 2.3.1. I have following code. main routing websocket_urlpatterns = [ url(r'^ws/events/(?P<room_type>[^/]+)/(?P<room_id>[^/]+)/$', consumers.Consumer, name='core-consumer'), ] app routing application = ProtocolTypeRouter({ 'websocket': URLRouter(core.routing.websocket_urlpatterns), }) consumer class Consumer(AsyncWebsocketConsumer): async def connect(self): room_type = self.scope['url_route']['kwargs']['room_type'] room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_name = f'{room_type}_{room_id}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def receive(self, text_data = None, bytes_data = None): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send(self.room_group_name, {'type': 'send_data', 'message': message} ) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def send_data(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'data': message })) def send_event(channel='', message=''): channel_layer = get_channel_layer() asyncio.run(channel_layer.group_send(channel, { 'type': 'send_data', 'message': message } )) signal def activate_notification(self): send_event(f'user_{self.id}', {'message': f"Welcome back to one deeds!"}) How can I test this with unittest? I read this documentation but nothing understand( I want to run test with command ./manage.py test I tried testing this with WebsocketCommunicator -
Django - TypeError: object of type 'int' has no len()
I have a django model Project that looks like this: class Project(models.Model): slug = models.SlugField(null=True, blank=True, unique=True,default="") project_title = models.CharField(null=True, blank=True, max_length=120) project_post = models.TextField(null=True, blank=True) project_cat = models.CharField(null=True, blank=True,max_length=20) project_thumb = models.ImageField(upload_to=upload_image_path, null=True, blank=True) project_movie = models.FileField(upload_to=upload_image_path, null=True, blank=True,default='False') project_views = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_views',default=0) project_likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_likes',default=0) project_date = models.DateTimeField(null=True, blank=True, auto_now_add=True) When I try to create a new project, I get this error: Django Version: 3.0.3 Python Version: 3.8.1 Traceback (most recent call last): File "C:\Users\...\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\...\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\...\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\...\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\...\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1638, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1567, in _changeform_view change_message = self.construct_change_message(request, form, formsets, … -
Docker: The command returned a non-zero code: 137
My docker file is as follows: #Use python 3.6 image FROM python:3.6 ENV PYTHONUNBUFFERED 1 #install required packages RUN apt-get update RUN apt-get install libsasl2-dev libldap2-dev libssl-dev python3-dev psmisc -y #install a pip package #Note: This pip package has a completely configured django project in it RUN pip install warriorframework #add a configuration file required for setup ADD appAdd.json / #Run a script #Note: Here appmanage.py is a file inside the pip installed location(site-packages), but it will be accessible directly without cd to the folder RUN appmanage.py appconfig appAdd.json #The <pip-packge> installed comes with a built in django package, so running it with following CMD #Note: Here manage.py is present inside the pip package folder but it is accesible directly CMD ["manage.py","runserver","0.0.0.0:8000"] When i run : sudo docker build -t test-app . The steps in dockerfile till: RUN appmanage.py appconfig appAdd.json runs sucessfully as expected but after that i get the error: The command '/bin/sh -c appmanage.py appconfig appAdd.json' returned a non-zero code: 137 When i google for the error i get suggestions like memory is not sufficient. But i have verified, the system(centos) is having enough memory. Additional info The commandline output during the execution of RUN appmanage.py appconfig … -
Django ajax form - redirect to main page after form validation
I have a sidenav_form that is submitted using an ajax post to a view called form_validation. The validation errors for empty fields or invalid email are shown correctly, since when the form is submitted and passed to the view, the view renders the form displaying the errors. Here is the console output: <ul class="errorlist"><li>email<ul class="errorlist"><li>Required Field</li></ul></li></ul> [08/Feb/2020 13:26:37] "POST /patients/validate_form/ HTTP/1.1" 200 1253 However, the behavior when passing the validator for repeated email is different. The error is sent to the request as before, but the user an't see it since it seems that the request redirects to another view... <ul class="errorlist"><li>email<ul class="errorlist"><li>This email has already been taken.</li></ul></li></ul> [08/Feb/2020 13:26:40] "POST /patient/ HTTP/1.1" 200 7769 [08/Feb/2020 13:26:40] "POST /patients/validate_form/ HTTP/1.1" 200 1279 The sidenav_form.html is the following: {% load i18n %} {% load crispy_forms_tags %} <!-- sideNav --> <div class="inside_sidenav"> <form class="form" id="form_patient"> {% csrf_token %} {{ form.as_p}} </div> <div class="form-actions"> <button type="submit" class="btn btn-primary" id="sidenav-btn-submit" formmethod="post">{% trans 'Guardar'%} </button> </div> </form> </div> </div> <script> $(function () { // SUBMIT DATA $('#sidenav-btn-submit').click(function () { console.log('noinstance') var url = "{% url 'patients:validate_form' %}"; var formb = $('#form_patient'); console.log(formb.serialize()); $.ajax({ url: url, data: formb.serialize(), type: "POST", headers: { "X-CSRFToken": '{{ csrf_token }}' … -
How to call the authenticate() method of Custom written AuthenticationBackend of django in views.py?
I am working on a Django project in which I have defined a custom user model for which I have required to write the custom authentication method, by following the documentation I have written it like following But I have a problem in calling it in the views.py kindly help me by looking in the following code I have defined my custom backend as follows My Custom Authentication Backend from django.contrib.auth.backends import BaseBackend from .models import User from IntellerMatrix.CommonUtilities.constants import Constants class AuthenticationBackend(BaseBackend): """ Authentication Backend :To manage the authentication process of user """ def authenticate(self, email=None, password=None): user = User.objects.get(email=email) if user is not None and user.check_password(password): if user.is_active == Constants.YES: return user else: return "User is not activated" else: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None settings.py AUTHENTICATION_BACKENDS = ['Modules.users.authentication.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] Views.py def login(request): email = 'ialihaider75@gmail.com' password = 'ali' user = # how to call here that custom authentication backend's authenticate method if user is None: return HttpResponse("<p>Not Valid</p>") else: return HttpResponse(user) -
Why I can't login to admin using client?
I try to test my custom action. But when I go to admin page using client I get error <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/"> class ExportToExcelTestCase(TestCase): def setUp(self) -> None: self.user = UserFactory() def test_export_to_excel(self) -> None: data = {'action': 'export_to_excel'} change_url = '/admin/donation/donation/' self.user.is_staff = True self.user.is_superuser = True self.user.save() self.client.login(username=self.user.username, password=self.user.password) response = self.client.post(change_url, data) print(response) #<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/"> -
Validation issue on django form submit for CheckboxSelectMultiple
I Have a form like Given below : [1]: https://i.stack.imgur.com/E62gL.png code what i am writting is like given below. class CustomBookingFeatureCreationForm(forms.ModelForm): def my_choices(): value = Features.objects.values() features = [] for feature in value: features.append([feature['id'], feature['name']]) return features feature = forms.MultipleChoiceField(choices=my_choices, widget=forms.CheckboxSelectMultiple()) class Meta: model = BookingFeature fields = ['feature'] when i am submitting the form its returning me the error like this how can i save this form with multipl choices please help me related tgis i am a newbe in django .. please suggest me a best way to solve this -
i cannot a user as an object to a many to many field
I am creating a functionality where a project/showcase has an administrators ManyToManyField, which would contain a list of users that can control a project. I am having issues adding users to this field. I was able to set the person that creates a project as an administrator by default, but adding other administrators has been a challenge. models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) serializers.py class ShowcaseAdminSerializer(serializers.ModelSerializer): class Meta: model = Showcase fields = ['administrator',] the view that is responsible for Administrators alone to add other administrators to the showcase/project, but this doesnt work views.py class showcaseAddAdminApiview(APIView): ''' Add a user as an admin to a showcase ''' serializer_class = ShowcaseAdminSerializer permission_classes = [IsAdmin] def post(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) if request.user in showcase.administrator.all(): showcase.administrator.add(user) showcase.save() serializer = self.serializer_class(showcase) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py path("<slug:slug>/addadmin/", qv.showcaseAddAdminApiview.as_view(), name="add-administrator-to-showcase"), -
How to format the queryset in Django Template
I want to display the month and totalpayment in tabler or readable form from the queryset value. Models.py class Payment(models.Model): statementperiod = models.DateField(default = date.today()) paymentdate = models.DateField(default = date.today()) paymentamount = models.IntegerField() paymentmethod = models.CharField(max_length=100 ) Status = models.CharField(max_length = 250, default = 'paid', choices = PAYMENT_CHOICES) Paynote = models.CharField(max_length = 250, null = True, blank = True) @classmethod def totalpayment(cls): total = Payment.objects.annotate(month=TruncMonth('paymentdate')).values('month').annotate(total_payment=Sum('paymentamount')) return { total} QuerySet value in the template: {<QuerySet [{'month': datetime.date(2019, 11, 1), 'total_payment': 315}, {'month': datetime.date(2019, 12, 1), 'total_payment': 8348}, {'month': datetime.date(2020, 1, 1), 'total_payment': 3459}, {'month': datetime.date(2020, 2, 1), 'total_payment': 2833}]>} So, How to format these values? -
Modifying property of checkbox elements with respect to Django model data
Problem I have a django model named 'Task' which is related to a model called 'List' (A list has several tasks). I have appended all the 'Task' objects of all 'List' objects in an array 'tasks'. The Task object has a boolean member 'completed' which is true if the task is completed and false if not. Now, in the template I want to iterate the array 'tasks' and find all those tasks which are completed and change the state of their check-boxes as 'checked' through their IDs (checkbox ID format : task). How do I do it? Code I have tried the following django template code with JavaScript but its not working apparently. <script> {% for list_tasks in tasks %} {% for task in list_tasks %} {% if task.completed == True %} document.getElementById("task{{task.id}}").checked=true; {% endif %} {% endfor %} {% endfor %} </script> -
How to add list of users of selected Group using Django admin inlines form?
I am working on an application where currently, I have 1) Staff Model is connected to User model via OneToOne Relationship and can have more than one Group. 2) Meeting model can also assigned to many Group. 3) RSVPinline is a part with MeetingAdmin as a inline form. Here i was trying to automatically ADD all 'Staff' associated in Selected Groups in django admin form while creating Meetings. I have tried save_model to add current user in meeting's 'creator' field. models.py class Group(models.Model): name = models.CharField(max_length=200) class Staff(models.Model): fullname = models.CharField(max_length = 250,verbose_name = "First Name") group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group") # protect error left to add is_active = models.BooleanField(default=True) user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True,verbose_name = "Associated as User") # protect error left to add left_date = models.DateField(null=True, blank=True,verbose_name = "Resigned Date") class Meeting(models.Model): title = models.CharField(_('Title'), blank=True, max_length=200) start = models.DateTimeField(_('Start')) group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group") # protect error left to add location = models.ForeignKey(Location, blank=False,verbose_name = "Location",on_delete=models.CASCADE) # protect error left to add class RSVP(models.Model): meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE) responder = models.ForeignKey(User, editable=True, on_delete=models.CASCADE, null=True, blank=True,verbose_name = "Attendees", related_name='guest') response = models.CharField(max_length = 20, choices= MEETING_RSVP, default='No response', verbose_name = "Status",null=True, blank=True) admin.py class … -
How to automate create or update of superuser in Django?
From this question, I see that it's possible to update the creation of superusers in Django using: echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'password')" | python manage.py shell This works for creating superusers, but not for updating them. Is there a way to automate the creation or update of superusers? Something similar to create_or_update. -
Syntax error while passing arguments to javascript function from Django template
I have to pass 4 arguments from a Django template to a javascript function. Out of these 4, 3 are integers/decimals and 1 is a string. <button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, {{item.name}})"> Add to cart </button> Here is the Javascript function. let USER_CART = []; function addCart(itemId, itemPrice, itemDiscount, itemName) { let itemQuantity = parseInt(document.getElementById(itemId).value); if (itemQuantity > 0) { let item_index = USER_CART.findIndex(item => item.id === itemId); if (item_index === -1) { let item = { id: itemId, price: itemPrice, discount: itemDiscount, quantity: itemQuantity, title: itemName, }; USER_CART.push(item); } else { USER_CART[item_index].quantity += itemQuantity; } } } Whenever I click on the button this error shows up on the console. SyntaxError: missing ) after argument list Another interesting thing is if I remove the item.name and itemName completely from the code, it works just fine. -
Reverse for 'test_id' with no arguments not found. 1 pattern(s) tried: ['testid/(?P<obj_id>[0-9]+)/$']
i'm getting above error.I don't know where i did mistake. Please help me to solve this error. urls.py path('test/<int:id>/', views.test, name='test') views.py def test(request, id): if request.methood == 'GET': print("Get") return render(request, 'test_page.html', {}) elif request.methood == 'POST': print("POST") return render(request, 'test_page.html', {}) test_page.html $.ajax({ url: "{% url 'data1:test' %}", type: "POST", async: false, data: {arr: JSON.stringify(arr), csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (data) { } }); -
Django avoiding infinite save() loop, with ImageField saved using custom model method
I want to make my model call save_image() everytime user creates new Post model. I tried to override save() method, but it causes infinite loop (because save_image() calls self.image.save(). ). I tried disabling signals, but they did nothing. I wanted to add something like @receiver(post_save, sender=Post) for the save_image, and remove override of save() (I don't even know if it will solve problem with infinite loop). The main problem here is that, save_post() MUST be called after standard save (because it needs Post.pk, Post.video). If you have any ideas, please help me. Here's my code: class Post(BaseModel): owner = models.ForeignKey(User, on_delete=models.CASCADE) # Other fields video = models.FileField(upload_to='post_videos/', default='defaults/video.mp4') image = models.ImageField(upload_to='post_images', default='defaults/post_image.png') def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) self.save_image() @receiver(post_save, sender=Post) def save_image(self): # Setting self.image to some frame of Video cap = cv2.VideoCapture(self.video.path) video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1 if cap.isOpened() and video_length > 0: success, image = cap.read() if success: rescaled = (255.0 / image.max() * (image - image.min())).astype(np.uint8) PILimg = Image.fromarray(rescaled) filename = "postimage"+str(self.pk)+".png" f = BytesIO() try: PILimg.save(f, format='png') s = f.getvalue() self.image.save(filename, ContentFile(s)) finally: f.close() -
django-import-export package : CATEGORYL1 invalid literal for int() with base 10: 'TOP'
I am trying to upload a .xlsx file and store the data into db using django-admin panel. The package I am using is django-import-export. Data is Uploaded almost successfully but there is one error related to foreignKey field i.e. : "CATEGORYL1 invalid literal for int() with base 10: 'TOP'" Here is my code for models.py,resources.py and admin.py repectively #models.py from django.db import models class ParentCode(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class CategoryL1(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class CategoryL2(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Item(models.Model): ItemCode=models.CharField(max_length=100) ItemName=models.CharField(max_length=100) CategoryL1=models.ForeignKey(CategoryL1,null=True,blank=True,on_delete=models.CASCADE) CategoryL2=models.ForeignKey(CategoryL2,null=True,blank=True,on_delete=models.CASCADE) UPC=models.CharField(max_length=100) ParentCode=models.ManyToManyField(ParentCode,blank=True) MRPPrice=models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) Size=models.CharField(max_length=100) Enabled=models.BooleanField(default=False) #admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Item # Register your models here. @admin.register(Item) class ViewAdmin(ImportExportModelAdmin): pass #resources.py from import_export import resources from .models import Item class ItemResource(resources.ModelResource): class Meta: model = Item fields=('__all__') screenshot of The excel sheet Im trying to upload . . screenshot of django-admin a after uploading data -
Django: Unable to access filefield file via url
tldr: Problems with accessing filefield's url attribute led me to realize that I also have to check how to serve media files in debug mode with django's runserver. I have no clue how to continue. :( long version: Hi there I am a Django newbie and totally lost how to access a filefield object with the browser. Here is my settings.py in the project root: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'rgeingabe/documents/') MEDIA_URL = '' #STATIC_URL = 'static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'rgeingabe/static') I also set the DEBUG mode to true. Here is the project's urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rgeingabe/', include('rgeingabe.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I hope that it is right to include that static information in the project's urls.py. First I tried to do that in the app's urls.py, but I guess that was wrong. Next, to the models.py: class Document(models.Model): beschreibung = models.CharField(max_length=255, blank=True) datei = models.FileField(upload_to='') hochgeladen_am = models.DateTimeField(auto_now_add=True) gehoert_zu_rg = models.ForeignKey('Pkvjanosch', on_delete=models.CASCADE) def save(self, rgauswahl, *args, **kwargs): d = Pkvjanosch.objects.get(rg_id = rgauswahl) neuer_dateiname … -
django + ajax send form
I try after receiving one form to get another views.py def get_name(request): if request.method == 'POST': user_code = generate_code(8) subject = 'ver code' message = user_code phone = request.POST['phone'] form = NameForm(request.POST) if form.is_valid(): Registration.objects.create(fio=request.POST['fio'],mail=request.POST['mail']) send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False) return JsonResponse({ 'form1': render_to_string( 'registers/endreg.html', {'form': NameForm1() } ) }) else: form = NameForm() return render(request, 'registers/detail.html', {'form': form}) def endreg(request): if request.method == 'POST': form = NameForm1(request.POST) if form.is_valid(): code_use = form.cleaned_data.get("key") try: user = Registration.objects.get(code=code_use) user.verification = True user.save() messages.warning(request, u'thanks.') except: messages.warning(request, u'error.') else: form = NameForm1() return render(request, 'registers/endreg.html', {'form': form}) and ajax $(document).ready(function() { $("#my_form").submit(function(event) { event.preventDefault(); $this = $(this); $.ajax({ type: "POST", data: $this.serialize(), success: function(data) { console.log(data); $this.html(data.form1); }, error: function(data) { console.log(data); } }); }); }); I am facing a CSRF token missing or incorrect problem. Because it is not transferred to form 2. how can I transfer this token to a new form -
Queryset does not update on Form
I have tried this but it does not seem to work for me. My form updates the choices when I runserver but later when I add a new stop, it does not show up in the list on routes form. models.py class Route(models.Model): DIRECTION_CHOICES = [ (True, "UP"), (False, "Down") ] STATUS_CHOICES = [ (True, "Active"), (False, "Inactive") ] TYPE_CHOICES = [ (True, "AC"), (False, "General") ] name = models.CharField(verbose_name="Route Name", unique=True, blank=False, null=False, max_length=50) direction = models.BooleanField(verbose_name="Direction", null=False, blank=False, choices=DIRECTION_CHOICES) status = models.BooleanField(verbose_name="Status", null=False, blank=False, choices=STATUS_CHOICES) list_of_stops = models.TextField(verbose_name="Stops", null=False, blank=False) type = models.BooleanField(verbose_name="Type", null=False, blank=False, choices=TYPE_CHOICES) class Stop(models.Model): name = models.CharField(verbose_name="Name", unique=True, blank=False, null=False, max_length=50) latitudes = models.DecimalField(verbose_name="Latitudes", max_digits=9, decimal_places=6) longitudes = models.DecimalField(verbose_name="Longitudes", max_digits=9, decimal_places=6) I don't think that there is any issue with the view but I can add it if you think there is any forms.py class RouteForm(forms.ModelForm): stops = [(stop.name, stop.name) for stop in Stop.objects.all()] list_of_stops = forms.MultipleChoiceField(choices=stops, required=False) class Meta: model = Route fields = ('name', 'direction', 'status', 'type') Can someone please temm me what I am doing wrong? -
Django no post request multiple file upload
I am trying to create a file upload system in django. For reference, I am using this :https://github.com/sibtc/multiple-file-upload Now what happens is that no post request goes when I select a photo or two. class PageDetailView(View): def get(self, request,**kwargs): page = get_object_or_404(Page, pk=self.kwargs['pk']) photos_list = Photo.objects.all() context = { 'page':page, 'photos':photos_list, } return render(self.request, 'page/page_detail.html', context=context) def post(self, request): form = PhotoForm(request.POST, request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) My urls is configured like this: path('page/<int:pk>/', PageDetailView.as_view(), name='page_detail'), Also, the photo form is like this: class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', ) Again, the photo model is like this: class Photo(models.Model): file = models.FileField(upload_to='photos') Finally where the magic should be, the template is like this: {% extends 'blog/pseudo_page_detail.html' %} {% load static %} {% block javascript %} {# JQUERY FILE UPLOAD SCRIPTS #} <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> {# PHOTOS PAGE SCRIPTS #} <script src="{% static 'photos/js/progress-bar-upload.js' %}"></script> {% endblock %} {% block content %} <h1>{{page}}</h1> <div style="margin-bottom: 20px;"> <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> <input id="fileupload" … -
Django optimize recursive query
I have this Django model: class Employee(models.Model): manager = models.ForeignKey('self', related_name='subordinates', on_delete=models.PROTECT, null=True, blank=True, default=None) is_admin_manager = models.BooleanField(default=False) **** Also, I have this recursive function, that calls on every instance of an employee in DRF serializer: def _get_admin_manager(self, obj): if not obj: return None if obj.is_admin_manager: return obj return self._get_admin_manager(obj.manager) The problem is, the more complex vertical hierarchy, the more requests to DB will be created. Is there is a way to optimize this? -
What is a way to serialize this JSON data?
How do I serialize this JSON? { "Data":{ "Age": 21, "Year": 2012, "Address": "123 Sesame" }, "Data2": { "Color": "Blue", "Number": 2, "Address": "123 Sesame" } } I need help with the serializers from rest_framework import serializers from .models import Data, DataTwo, Form class DataSerializer(serializers.Serializer): Age = serializers.IntegerField(source='age') Year = serializers.IntegerField(source='year') Address = serializers.CharField(max_length=50, source='address') def create(self, validated_data): return Data.objects.create(**validated_data) class DataTwoSerializer(serializers.Serializer): Color = serializers.CharField(max_length=50, source='color') Number = serializers.IntegerField(source='number') Address = serializers.CharField(max_length=50, source='address') def create(self, validated_data): return DataTwo.objects.create(**validated_data) class FormSerializer(serializers.Serializer): Data = DataSerializer(source="*") Data2 = DataTwoSerializer(source="*") def create(self, validated_data): return Form.objects.create(**validated_data) Also my models: from django.db import models # Create your models here. class Data(models.Model): age = models.IntegerField() year = models.CharField(max_length=50) address = models.CharField(max_length=50) class DataTwo(models.Model): color = models.CharField(max_length=50) number = models.IntegerField() address = models.CharField(max_length=50) class Form(models.Model): data = models.ForeignKey(Data, default="null", on_delete=models.CASCADE) data_two = models.ForeignKey(DataTwo, default="null", on_delete=models.CASCADE) If I view validated_data from FormSerializer I get this: {'Data': OrderedDict([('age', 21), ('year', 2012), ('address', '123 Sesame')]), 'Data2': OrderedDict([('color', 'Blue'), ('number', 2), ('address', '123 Sesame')])} I was under the impression that the serializer I created would take care of this. I'm not sure how to go about this. Feeling really lost