Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
proper flow of add to cart using rest framework
I am developing an ecommerce application to get understanding of rest framework. I am stuck in the add to cart process. I am confused on what is the best approach to handle this functionality. I tried to create a separate function for getting the carts, posting the items into carts. How do i use session for achieving the proper flow of adding the items into the cart? Here is the model, serializers and view i created models.py class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) items = models.ManyToManyField(Variation, through='CartItem') quantity = models.PositiveIntegerField(default=1) subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085) tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) active = models.BooleanField(default=True) class Meta: verbose_name = 'Cart' verbose_name_plural = 'Carts' class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Variation, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) serializers.py class CartSerializer(serializers.ModelSerializer): items = VariationSerializer(many=True) class Meta: model = Cart fields = '__all__' class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = '__all__' views.py class CartAPI(APIView): serializer_class = serializers.CartSerializer def get(self, request, format=None): reply = {} try: carts = Cart.objects.all() reply['data'] = self.serializer_class(carts, many=True).data except CartItem.DoesNotExist: reply['data'] = [] return Response(reply, status.HTTP_200_OK) # TODO need to make it productive … -
how to pass current pk from URL to a model form
I have this view in my views.py def DressDelete(request, pk): deleted_dress = get_object_or_404(Item, pk=pk) if request.method == "POST": delete_dress_form = DressDeleteForm(request.POST) if delete_dress_form.is_valid(): model_instance = delete_dress_form.save(commit=False) model_instance.dress_removed = True model_instance.save() return redirect('dress_confirm') else: delete_dress_form = DressDeleteForm() context = { 'delete_dress_form':delete_dress_form, } return render(request, 'fostania_web_app/dress_delete.html', context) and now I want the line model_instance.dress_removed = True to be applied to the current item which is model_instance.dress_removed = True -
request.GET.get() doesn't capture the variable
in my urls.py I have re_path(r'^accounts/(?P<query>[0-9]+)/$',home) In the home view I have def home(request, query): myvar = request.GET.get('query','') print(myvar) return HttpResponse(myvar) In the above code Httpresponse doesn't print anything but if I change the code like below it works def home(request, query): return HttpResponse(query) this is the url : http://127.0.0.1:8000/accounts/45/ -
Django: (Adapted) Middleware causing Internal Server Error
As long as DEBUG=True is set in my settings file everything works fine, but if DEBUG is set to False, I get a "500 Internal Server Error", which I obviously can't debug too deeply. I've figured out that the culprit is a middleware I adapted from another SO answer. What it's supposed to do is figure out if a user is trying to access the website through the Heroku subdomain (myapp.herokuapp.com) and redirect to websitename.io. It was written when Django setting files still used MIDDLEWARE_CLASSES, and I've adapted it to use with MIDDLEWARE. Here's the code that's causing the site to crash: SITE_DOMAIN = "websitename.io" class CanonicalDomainMiddleware(object): """Middleware that redirects to a canonical domain.""" def __init__(self, get_response): self.get_response = get_response if settings.DEBUG or not SITE_DOMAIN: raise MiddlewareNotUsed def __call__(self, request): """If the request domain is not the canonical domain, redirect.""" hostname = request.get_host().split(":", 1)[0] # Don't perform redirection for testing or local development. if hostname in ("testserver", "localhost", "127.0.0.1"): raise MiddlewareNotUsed # Check against the site domain. canonical_hostname = SITE_DOMAIN.split(":", 1)[0] if hostname != canonical_hostname: if request.is_secure(): canonical_url = "https://" else: canonical_url = "http://" canonical_url += SITE_DOMAIN + request.get_full_path() return redirect(canonical_url, permanent=True) This is how I'm calling it in settings/base.py: … -
Why am I not able send through async_to_sync ?(asgiref==2.3.2)
I am trying to execute below code, but getting an error at cmd "async_to_sync(channel_layer.send)", $ python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) >>> async_to_sync(channel_layer.receive)('test_channel') {'type': 'hello'} The trace here: Traceback (most recent call last): File "<console>", line 3, in <module> File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/asgiref/sync.py", line 64, in __call__ return call_result.result() File "/anaconda3/envs/chatapp/lib/python3.6/concurrent/futures/_base.py", line 425, in result return self.__get_result() File "/anaconda3/envs/chatapp/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/asgiref/sync.py", line 78, in main_wrap result = await self.awaitable(*args, **kwargs) File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/channels_redis/core.py", line 134, in send async with self.connection(index) as connection: File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/channels_redis/core.py", line 447, in __aenter__ self.conn = await aioredis.create_redis(**self.kwargs) File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 177, in create_redis loop=loop) File "/anaconda3/envs/chatapp/lib/python3.6/site-packages/aioredis/connection.py", line 76, in create_connection assert isinstance(address, (tuple, list, str)), "tuple or str expected" AssertionError: tuple or str expected I am using asgiref==2.3.2, channels==2.1.2 Django==2.0.5 Python==3.5+ What needs to be changed to tuple or list here? -
django url pattern to much uuid
django url pattern to much uuid hi iam using django 1.11 i am tying to get url pattern which much uuid but it does not works i have tried more than 3 time but i am still getting error : Using the URLconf defined in eMarket.urls, Django tried these URL patterns, in this order: http://127.0.0.1:8000/view/49c26740-2211-4cc9-971b-5ff62ddc2e0e/ urlpatterns = [ url(r'^view/(?P<slug>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)$', viewProduct, name="view"), url('admin/', admin.site.urls), ] -
Accessing custom Django-Sitetree item fields
I've added several custom fields to my django-sitetree item that I need to access through the view and the template. Django-Sitetree template tag {% load sitetree %} gives me access to the standard sitetree fields, i.e. {% sitetree_page_description from "maintree" %} but I can't figure out how to display one of my custom fields. My custom model looks like this: class MyCustomSiteSection(TreeItemBase): """This is your site item model. """ tag_set = TaggableManager( 'Tags', help_text="What tags should be used for content in this section?", blank=True ) template = models.ForeignKey( Template, help_text="What template should be used to render this section?", on_delete=models.CASCADE ) is_edited = models.BooleanField( help_text="Is this section human controlled or simply a list of content?" ) In my view, I tried: current_tree_item_class = get_tree_item_model() # MyTreeItem from myapp.models (from the example above) test = current_tree_item_class.is_edited But on the page, I get: <django.db.models.query_utils.DeferredAttribute object at 0x10e1a9438> -
How to use Google task queues in Django application
I have a Django application which I intend to push on Google cloud. It has some module which requires heavy computation hence I need to use Google's tasks queue to do this computation in the background. I have read Google official task queue documentation page but it's not sufficient. Very limited resources are available that demonstrates how to use google task queues easily, On the other hand, there are plenty of resources available to get started with Celery (another background tasking mechanism). Can body refer me any good tutorials that explain everything from scratch. -
Django : how to change the value of a field or update the field in model / Db .?
I have two models, Car and Booking. A Car is a ForeignKey field in Booking model. If Car is booked, it's removed from Car list. After car booked is_avaialble_car = false . The car is not showing in CAr listview. but the Problem i am facing is: After i removed booking from admin the car is not showing in list view. if the car booking is closed i want to make is_available_car = True changed it from false to true . i had filter the query is_avaialble_car =True. Problem is after car is return and booking time finished . i have to manually change the value of is_available_car=True everytime . Help me out please that if car booking is finished or i delete the booking .the car available value changes to true !! These are my models and views: Models class Booking(models.Model): booking_name = models.CharField(max_length=240, null=False) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' ) book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car') rental_price = models.IntegerField(blank=False, null=False) times_pick = models.TimeField(blank=True) is_approved = models.BooleanField(default=False) def __str__(self): return self.booking_name def get_absolute_url(self): return reverse("buggy_app:detail",kwargs={'pk':self.pk}) class Car(models.Model): reg_no = models.CharField(max_length=16, unique=True) model_year = models.DateField() car_name =models.CharField(max_length=40) car_image = models.ImageField(upload_to='cars', blank = True) is_available_car = models.BooleanField(default = False) def __str__(self): return … -
cannot run django-admin.py startproject on bash terminal
I tried to start a new Django project but for some reason my terminal gives an error (bash: django-admin.py: command not found), while in the past I've been running several projects without problems. It seems something has changed in my Mac Terminal. Also through my Pycharm I'm no longer able to start a new project. Is there a way to reset my terminal and/or to set-up a Django project without using the terminal. MBPvanPKL:Mysite pkl$ django-admin.py startproject mysite -bash: django-admin.py: command not found -
How to Deploy Django projects on ubuntu 18.04 locally
I wanna install Ubuntu & Gitlab to manage developing projects completely offline. So, I can manage Django apps on it with my team. From then we will need to test Django web apps continuously.So that I think that we need to deploy it through Ubuntu server to be able to check it any time we need to like APIs, links, ..etc. Could you help me to configure Gitlab and let projects to be deployed once it edited? -
Django - Nested variables with dynamically generated URLs
I'm trying to dynamically generate a URL based on a variable (objecttype) passed into a template: <a href="{% url 'wakemeup:edit_object' objecttype='school' objectid='new' %}"> Here the objecttype variable should be passed in via the objecttype context variable. I tried using the |add: operator and including {{ objecttype }} directly in the url, but I keep getting parsing errors. Can someone please help me out? -
Calling Model Method Via Django Rest Framework View
I have a model: class Size(models.Model): size = models.DecimalField(max_digits=5, decimal_places=1) def plus_one(self): self.size += 1 self.save() And I have a simple serializer for this: class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = '__all__' How can I call a plus_one model method from my view, using DRF? How is it callable, what is good practice for that? Thanks! -
Combining ModelChoiceFields in a Djano form to save in a single ManyToManyField
I have a ModelForm where I want to combine a series of ModelChoiceFields into a single ManyToMany field when I save to the database. So my model form is something like: class ExampleForm(forms.ModelForm): fulltime = forms.ModelChoiceField( queryset = Type.objects.filter(tag_type=jb_models.F_PTIME), ) optional = forms.ModelChoiceField( queryset = Type.objects.filter(tag_type=jb_models.OPTIONAL), ) class Meta: model = Job fields = ('jobtype', 'title', \ 'fulltime','optional') widgets = { 'jobtype': forms.HiddenInput(), 'title': forms.TextInput(attrs={'size':50}), } def save(self, commit=True): instance = super().save(commit=False) instance.jobtype.set(self.cleaned_data['fulltime']) instance.jobtype.add(self.cleaned_data['optional']) instance.save() return instance This gives me the TypeError object is not iterable. How should I approach this? -
How to limit UpdateView of a model to some objects from another model?
I have models X, Users, and XMember. XMember is like this: class XMember(models.Model): x = models.ForeignKey(X, on_delete=models.CASCADE) user = models.ForeignKey(Users, on_delete=models.CASCADE) access_type = models.PositiveIntegerField(choices=ACCESSROLE, null=True) Access roles are: ACCESSROLE = ( (1, 'Writer'), (0, 'Reader'), ) I need to limit the UpdateView of model X to only the users having access_type of "Writer" in model XMember. I tried modifying the update view like this: def get(self, request, *args, **kwargs): print("Function begin") x = X.objects.get(pk=self.kwargs["pk"]) try: xmember = XMember.objects.filter( x=x, user=self.request.user ).get() except XMember.DoesNotExist: raise Http404("x not found!") else: if xmember.access_type: kwargs['access_type'] = True return super().get(request, *args, **kwargs) raise Http404("You don't have access to this page!") But it doesn't work and the function get() somehow gets called more than one time. When I try to update X (with access_type = 1) I get: Problem matching query does not exist. and the line: print("Function begin") gets executed twice.. So what am I missing here ? -
Should django-admin version be same as Django?
I tried to configure my PC for Django course , i have fresh Ubuntu 18.04 : I followed all steps from the course : I had newest python pre-installed, Python 3.6.5 so i went : sudo apt install python3-pip went ok, then : pip3 install django==2.0.2 (version suggested by instructor) that completed as well, then : django-admin startproject wordcount and that gave me error : Command 'django-admin' not found, but can be installed with: sudo apt install python-django-common So i tried to install this but it didn't help. so i checked web for answers and i found that i should do : sudo apt-get install python-django And after that i could use django-admin startproject wordcount and it created a project for me but i saw that some elements of default files are different from what i saw on course video so i check and : django-admin --version 1.11.11 also django-admin --help gives me message like this : Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). Any ideas what went wrong and … -
Success event is never triggered in my javascript for polling event
Very new to programming. I am trying to develop a web application using django and celery. I want to display a loader till some background celery task is executing and then display the data fetched by celery worker. Till now, my state is this My loader.js script is var myVar; function myFunction() { myVar = setTimeout(showPage, 3000); } function poll1() { setTimeout(function() { $.ajax({ url: "http://localhost:8000/celery-progress/task_progress/12/", headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, type: "GET", success: function(myFunction) }} (function poll(){ $.ajax({ url: "http://localhost:8000/celery-progress/task_progress/12/",type: "GET", success: function showPage1() { document.getElementById("loader").style.display = "none"; document.getElementById("myDiv").style.display = "block"; }, dataType: "json"}); })(); function showPage() { document.getElementById("loader").style.display = "none"; document.getElementById("myDiv").style.display = "block"; } When the html body load i have tried calling both 'poll1' and 'poll'. But my loader keeps on rotating indefinitely. The data returned by the polling url "http://localhost:8000/celery-progress/task_progress/12/" is a json "{"complete": true, "success": true, "progress": {"current": 100, "total": 100, "percent": 100}}" Any help would be great! -
Django Rest Framework, Query Dict is empty when using MultiPartParser
I'm trying to upload images by using DRF: I have simple serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('file',) This file field is simple ImageField in my model. Then I have created viewset: class ImagesViewSet(ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser, FormParser) @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated]) def upload_avatar(self, request): print(request.data) return Response({"image": "ok"}) I just want to print what I'm trying to upload. After makeing request to upload data: My Query Dict returns me: <QueryDict: {}> Is it bug? Or I did miss something? Version of DRF: 3.8.2 Django: 2.0.6 -
embed pdf file from Dropbox in Django html
I am using Django 2.0 deployed at Heroku. Since, Heroku does not support media storage (they are deleted after few times of storing file, may be stored in tmp directory), I'm suing Dropbox to upload media files whenever upload is triggered. I'm using django-storages and Dropbox SDK to setup Dropbox for hosting media files. My settings file has line DROPBOX_OAUTH2_TOKEN = '****' DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' It is working file for uploading and downloading of file as using object.pdf_file.url Generates download link. But, I generally need to upload pdf files containing question papers and want to embed it in my website. <embed src="{{ object.pdf_file.url }}" type="application/pdf" width="100%" height="600px" /> But this is not working as Dropbox pdf files can not be embedded this way. I thought of a work around and thinking of to download Dropbox file to local path and then use it in embed. Heroku's cycling restore will delete downloaded files periodically. But, the URL generated looks like https://dl.dropboxusercontent.com/apitl/1/AAACdZSSThUwYLskNld3EJeFHYmgQqs6JouqH305U4_msH3iyXqb3p_HgL11VFZTIA-MF0troTpZeQ7-ok1WuSJI3F5Zw0aUbfivBBvVWjacrMuJYoM3Rzl9XV_qc3uUU5wHXZjwQb2R-QC4zEEYkTy2U5wzer0sOapncfdBtTfW3ybruSU6IYVCkmUzpfU3mpAdYjQF-JGvO9RVP1dCqCHztIdc5YwM6LmBZPjZdqQ3CaCnO50IJjTQPb6k8zqpESGAEQFk_9d2jik77B8ds8RAkkZS4pH2zRur1ItizRmqL9NmWDvs7xP_tlIZzLRo7MGDG7kt-DXTCmdy1kEbBG_CB7vu7UrsdyWyh3mgd7jsiYclts-h2AnAbh28KwSZ5GJW3PbVeKAhvKc4-Ud72MS2 which can not be deleted directly. How can I download the Dropbox file and use in HTML embed? Is there any other way of embedding PDF file from Dropbox to HTML? -
formplayer commcare cannot create menus
i installed commcare-hq on my ubuntu server, i feel like this issue is connected to formplayer, which i installed as the following 1- create the file submodules/touchforms-src/touchforms/backend/localsettings.py URL_ROOT = ‘http://localhost:8000/a/{{DOMAIN}}’ 2- copy scripts/get_webhost and append to root/etc/hosts 3- added FORMPLAYER_URL = ‘http://localhost:8010’ and BASE_ADDRESS = ‘webhost:8000’ to localsettings.py so after i press make a new version on the applications page Cannot Create Menus Details: Unable to validate the forms due to a server error. Please try again later. and on my server: raise ConnectionError(e, request=request) ConnectionError: HTTPConnectionPool(host=‘localhost’, port=8080): Max retries exceeded with url: /validate_form (Caused by NewConnectionError(’<requests.packages.urllib3.connection.HTTPConnection object at 0x7f5740ddbc10>: Failed to establish a new connection: [Errno 111] Connection refused’,)) 2018-06-23 11:27:15,510 INFO “POST /a/firstproject/apps/save/ce10d51a6470029490265ce8f79ac915/ HTTP/1.1” 200 673 -
django makemigration not detecting field addition to existing model but detects model additions
git diff shows + best_img_path = models.CharField(max_length=255) for models.py But makemigrations says No changes detected However on adding a new model makemigrations detects changes. Any ideas? FYI, I'm on django 2.0 with mysql -
heroku migrate raises app.settings module not found
I am trying to deploy a django 1.11 with the following file structure. But running heroku run python manage.py migrate gives me the error module not found 'app.settings' app app conf (base.py, development.py,production.py,__init__.py) wsgi.py manage.py .env .gitignore my manage.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.conf.development") my wsgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.conf.production") in gitignore, development.py is ignored. I don't have settings.py anywhere in my project so I am not sure where it is getting 'app.settings' Additional files: Procfile web: gunicorn app.wsgi --log-file - --log-level debug Where app.wsgi (copied from codementor). I actually don't really understand the application parameters or what it is coming from: from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Django mptt: Can I set maximum depth of a tree?
We are using django-mptt in a project. MyModel can have multiple children of the same MyModel but the maximum depth it 1 - so there can be only a root and it's children for every tree. Is it possible to set maximum depth in mptt? At least in admin? We use DraggableMPTTAdmin and don't want users to move nodes to depth 2. -
How to loop through dates in django
Does anyone knows as to how to loop through dates in Django. I have a code here which does not loop :- for dt in range(date1,date2): print(dt.dateTime()) -
Django form to display content in specified division of the Template
I am new the Django and Need help i have designed HOMEPAGE template home.html and it has 3 div's 1. 2. 3. As per the requirement, whenever anyone submit any form from sidebar , the output should always be displayed in i am able to achieve this when it comes to click button action HOME.HTML <span class="w3-small w3-bar-item w3-button" onclick="loadDoc1()">Teamcenter Syslog</span> function loadDoc1() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("display_page").innerHTML = this.responseText; } }; xhttp.open("GET", "{% url 'log_viewer_app:home' %}", true); xhttp.send(); } but i dont know how to do the same for the form in the django framework HTML file {% extends "base.html" %} {% block body_block %} <div class="container"> <h1> Teamcenter Syslog Viewer : </h1> <form action="/log_viewer_app/tc_syslog_viewer/" method="POST"> {% csrf_token %} <label for="text"><u>Syslog filename:</u></label> <input type="text" class="form-control" placeholder="Enter the syslog filename without extension" name="syslog_file_name" required> </br> <label for="environment_name"><u>Environment:</u></label> {% for key in title_list %} <div class="form-check"> <label class="form-check-label" for="radio1"> <input type="radio" class="form-check-input" name="environment_name" value="{{ key }}" checked>{{ key|upper }} </label> </div> {% endfor %} <br/> <input type="submit" class="btn btn-primary" name="submit" /> </form> </div> {% endblock %} VIEW.PY def tc_syslog_log_display(request): print("HELLO.............") print ("environment_name : " + environment_name) …