Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete method is not allowed when calling api endpoint in Django Rest Framework using DestroyModelMixin
I have imported DestroyModelMixin in UpdateAPIView so that I can use both PUT and DELETE methods in the same api endpoint. It works for PUT and can be updated, but when I call DELETE in postman, it says DELETE is not allowed. But, when I make a separate view using just DestroyAPIView, it works fine. I want to have a single api for both update and delete. My models: class CartItem(models.Model): cart = models.ForeignKey(Cart,on_delete=models.CASCADE, related_name='cartitems') item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return self.item.name My view: class CartItemUpdateAPIView(UpdateAPIView,mixins.DestroyModelMixin): permission_classes = [IsAuthenticated] queryset = CartItem.objects.all() serializer_class = CartItemSerializer def perform_update(self, serializer): serializer.save() def perform_destroy(self, instance): instance.delete() My serializer: class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['id','cart', 'item', 'quantity'] depth = 1 My urls: path('api/cartitemupdate/<int:pk>', views.CartItemUpdateAPIView.as_view(), name='api-cartitem-update'), -
use asynchronous in Django Rest Framework
I am using rabbitmq in my projects(for microservices) , and i need to asynchronous DRF , I should costumize DRF ,is there other way to use it as asynchronous ? -
Can I create a model Class in django dynamically?
So I have a tools/model.py Where I add all the tools that I will be using. The thing is each tool has to be a table its self so I can create more than one tool of each and to link that tool to the project that it is being used in. I am using MYSQL database For example: Tools Table must have: tools_ID tools_name tools_quantity now according to the tools_name I want to create a model or a table for it. For example: If I added ScrewDrivers to the Tools table I want it to create a ScrewDrivers Table automatically, Where all the child tables that inherit from Tools tables has the same structure and can't add ScrewDrivers more than the quantity that is specified in the Tools table. ScrewDrivers table: Rows = Quantity in Tools table ID ScrewDrivers_name ScrewDrivers_status (Available or being used in a project) -
Website loads through IP address but not through domain name
I have a domain purchased, 'yashrm.com', I wrote an app in django and made use of linode to host my website. I installed apache and also configured domain settings of linode. My website loads through IP address but not through domain name, dont know why. I'm attaching the snippets. django settings.py file ALLOWED_HOSTS = ['www.yashrm.com','192.46.212.231'] /etc/apache2/sites-enabled: django_project.conf django_project.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or … -
How to connect PyMongo with uppercase host name?
I tried to connect Pymongo with the uppercase hostname, but it automatically converting to lowercase? Is there any way to connect with the uppercase hostname? from pymongo import MongoClient MongoClient("MONGO_1") Output MongoClient(host=['mongo_1:27017'], document_class=dict, tz_aware=False, connect=True) -
Declare dynamic variable in django template
I'm currently passing via the context a variable named image_1, image_2, etc. I'm unsure how many images there. So I'm trying to make a for loop to go through the total count and make variables, {{ image_1 }}, {{ image_2 }}, etc. But the only thing I can think to try is this, and it's not working. {% for i in 10 %} {{ image}}{{ i }} {% endfor %} Of course the 10 being another variable I am passing. So in summary I'm trying to make {{ image}}{{ i }} instead be the equivalent of {{ image_1 }} via the for loop. -
The application will not be deployed on heroku Nuxt/Django
I do a deployment of the application on NuxtJs /Django on heroku. When deploying, the installation of Nuxt does not occur, which I need to specify in the settings. Prior to this, the deployment of "clean" Nuxt had no problems. Link to my repo: https://github.com/FalseHuman/Blog-on-Vue-and-Django Thanks for the help -
Django - select_related does not show the table when trying to convert the object to Json
select_related does not show the table when trying to convert the object to Json. The 'ativacao' table select_related is not shown on print. clientes = Cliente.objects.select_related('ativacao').filter(user=id) clientes_json = serializers.serialize('json', clientes) print(clientes_json) -
How can I fix my PATCH request to append to ArrayField, rather than delete and replace the whole object?
I have a problem with my PATCH request instance. Currently, data that is being PATCHED and sent from a request is overriding every item in my list of strings ArrayField inside my model object. I need my patch request behavior to append to the rest of the items in ArrayField object, not delete/override. How can I go about doing that? I assume I need to override the patch method within RetrieveUpdateAPIView, so I've started out here: def patch(self, request, **kwargs): item = self.kwargs.get('slug') serializer = StockListSerializer(item, data=request.data, partial=True) if serializer.is_valid(): serializer.save() Response(serializer, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) serializer.py: class StringArrayField(serializers.ListField): def to_representation(self, obj): obj = super().to_representation(obj) return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") return super().to_internal_value(data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) view.py class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer queryset = Bucket.objects.all() def get_object(self, queryset=queryset, **kwargs): item = self.kwargs.get('slug') return get_object_or_404(Bucket, slug=item) url.py: path('bucket/symbols/<str:slug>/', EditBucketSymbols.as_view(), name='editsymbols') model.py: stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True, blank=True) -
Bad request error while implementing recurrent payment using django-paypal
def process_payment(request): price = request.session.get('price') host = request.get_host() paypal_dict = { "cmd": "_xclick-subscriptions", "business": 'receiver_email@example.com', "a3": "9.99", # monthly price "p3": 1, # duration of each unit (depends on unit) "t3": "M", # duration unit ("M for Month") "src": "1", # make payments recur "sra": "1", # reattempt payment on payment error "no_note": "1", # remove extra notes (optional) "item_name": "my cool subscription", 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('source:payment_done')), 'cancel_return': 'http://{}{}'.format(host, reverse('source:payment_cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) # Output the button. form.render() return render(request, 'Prayer/process_payment.html', {'form': form}) -
Django Rest API Method not allowed
I have this set of endpoints. the retrieve API works fine. When I try to access the update URL, it will throw the error "detail": "Method \"PUT\" not allowed.". Whenever I try to place the update URL above the retrieve, it will work. But if I do that, the retrieve won't work and will throw the error, "detail": "Method \"GET\" not allowed." urls.py path( "food/", views.FoodCreateAPIView.as_view(), name="food-create", ), path( "food/<pk>/", views.FoodRetrieveAPIView.as_view(), name="food-retrieve", ), path( "food/<pk>/", views.FoodUpdateAPIView.as_view(), name="food-update", ), -
can i use for in views.py in Django?
def index(request): answer_list = Answer.objects.order_by('-create_date') an_list = {} for i in answer_list an_list[i.id] = Answer.objects.get(question=i.id) context = {'answer_list': answer_list, 'an_list': an_list} return render(request, 'index.html', context) for i in answer_list ^ SyntaxError: invalid syntax I can get the right values in shell but in views.py, I got the Error. thank you for reading. -
in Meta : AttributeError: module 'django.db.models' has no attribute
I have 2 different application in python. I want to import model and use it to make serializer function in another app. Here is my code: from django.contrib.auth import models as auth_models from . import models as client_models from crm.models import models as crm_models from rest_framework import serializers class Capability(serializers.ModelSerializer): class Meta: model = crm_models.Capability fields = ["id", "name"] class Client(serializers.ModelSerializer): industry = Industry(read_only=True) capability = Capability(read_only=True) class Meta: model = client_models.Client fields = [ "id", "company", "entity", "account_status", "capability"] Here I am getting error for, in Meta model = crm_models.Capability AttributeError: module 'django.db.models' has no attribute 'Capability' -
Azure Django Web App: raise KeyError(key) from None KeyError: 'SECRET_KEY'
I'm trying to deploy my django app on azure from the repo on GitHub. In the settings.py file, I dont want to store the secret key directly on GitHub, so I added that on the configuration application setting of the Azure app page. To retrieve it, my settings.py file has SECRET_KEY = os.environ['SECRET_KEY'] The error I'm getting is: raise KeyError(key) from None KeyError: 'SECRET_KEY' Am I properly retrieving the secret key? -
Wagtail RichText Editor Internal link is always broken
I'm using headless Wagtail to serve a frontend. In my rich text editor, I want to use the internal page link. However anytime I add an internal page link, it shows with None value, like so: After this, if I refresh the page, this link is shown as broken. All the other link types seem to work. What's the problem here? -
does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import>>
I'm following the django tutorial and ran into this error. took some time to look at a lot of other people who hit this same error and see a lot of cases where "urlpatterns" was not spelled correctly but that doesn't seem to be my issue. this is my code: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] I also notice when I comment out the whole line of code that has path with include. the error goes away. -
Simple python function problem I can't figure out
I am trying to make a simple webpage where everyday at midnight it records the top 5 subreddits of the day and then shows them on a page. However at the moment all that is popping up is "day1" whenever I launch the page. Here is the code that I think is causing this problem. day_top_five = {} day = 0 def my_cron_job(request): global day_top_five global day day += 1 UClient = uReq('https://www.reddit.com/top/') page_html = UClient.read() UClient.close() page_soup = soup(page_html, "html.parser") value = page_soup.findAll("a",{"class":"_3ryJoIoycVkA88fy40qNJc"}) loop = 0 result = [] while loop <= 4: result.append(value[loop]['href']) loop += 1 day_top_five[f'day{day}'] = result return HttpResponse(day_top_five, datetime.now()) If anyone has any ideas what is wrong with this please let me know. -
Is there any way to build a real time Chat application using Django Channels, Daphne and Apache 2.2?
I am trying to use Django Channels with Daphne and Apache 2.2.15 on CentOS 6.10 for a real time chat application. I want to forward all WebSocket requests from Apache to Daphne. But the module mod_proxy_wstunnel is not supported in Apache 2.2. It's not possible to switch to Apache 2.4 because of project restrictions. Is there any way to build a Chat application using Django Channels and Apache 2.2? -
Make Django Form Validation For Reservation
i make a reservation system, which has form validation, This should check whether the the bus on that date is already booked or not, but, unfortunately there still error on this code.. so here my code : forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' tempReDate = date(1,1,1) # temp local variable def clean_start(self): start = self.cleaned_data['start'] # cheacking if date for this bus is free res_all = Booking.objects.all() for item in res_all: if start >= item.start and start <= item.end and item.resourceId == self.instance.resourceId: raise forms.ValidationError("This date already reserved by same bus, choose other date or other bus") #set variable to send for next funtion: clean_EndDate self.tempReDate = start return start def clean_end(self): #check if EndDate is empty if not self.data['end']: #set numbers days of reservation 1 if no end date self.instance.numOfDays = 1 return None # if start date is empty if self.tempReDate == date(1,1,1): raise forms.ValidationError("Must Choose start date") # if start date is not empty else: start = self.tempReDate end = self.cleaned_data['end'] # cheackig start date is not lower than end date if end < start: raise forms.ValidationError("start date cannot be later than end date") # cheackig if reservation is no longer than … -
DRF registration and login without "password2" and "username"
I'd like to customize the registration and login using the dj-rest-auth library. I have a CustomUser model and do not want username nor password2 (password confirmation) when registering. Instead, I'd like registration to require only these fields: first_name last_name email password And login to be simply: email password What are the step to customize registration with dj-rest-auth? custom user model: from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email -
Django - html submit to view to api call to html page
So I am as Green as they come and am attempting the following. Our Work Management app has an average API but a very poor customer portal. I am attempting to produce at least a prototype of what I want and have been using Django (for the first time) I think I am almost there but have got myself all tangled. Being a newbie the Documentation does not enlighten me much. From one of the web pages the user enters a job number and clicks submit. I need that job number to complete my API call then I want to display the job information in job.html After a few days (like 5) I have the job number passing to the view and see the JSON data in the terminal but cannot get it to display in job.html I am getting this error AttributeError at /job/ 'dict' object has no attribute 'headers' Request Method: POST Request URL: http://127.0.0.1:8000/job/ Django Version: 3.2.dev20210111104520 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'headers' Exception Location: c:\users\davidp\django\django\middleware\clickjacking.py, line 33, in process_response Python Executable: C:\Program Files\Python38\python.exe Python Version: 3.8.2 I had the job page working when I manually entered a job number to the … -
What is a good design pattern for batching API calls in response to a webhook? [Django]
Background I am developing a Django application to receive order information fired off by a WooCommerce webhook and manipulate data in our CRM through their API. Problem Our CRM has a limit on daily API calls. Currently, my application makes 3 API calls in response to each instance of the webhook firing to authenticate, find the id of records matching the incoming order, and manipulate that record. I'd like to queue order information as it comes in from the webhook and process it in batches to reduce the number of API calls. I'm a bit lost on how to design this queueing system. I have some basic ideas and I've been looking into Redis and Celery as possible libraries to use, but I haven't been able to find any instances of this exact problem. Any advice or resources for designing an approach would be super helpful! -
Why Does My Django UpdateView Dosen't Work
My UpdateView doesn't Work I Tried i think the code doesn't reach the form_valid this is my views.py class PollUpdateView(UpdateView): model = Poll fields = ('Question',) template_name = 'question_edit.html' pk_url_kwarg = 'poll_id' context_object_name = 'polls' def form_valid(self, form): polls = form.save(commit=False) polls.updated_by = self.request.user polls.updated_date = timezone.now() polls.save() return redirect('home') and my models.py class Poll(models.Model): Question = models.CharField(max_length=100,unique=True) created_by = models.ForeignKey(User,related_name='created_by',on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(User,related_name='+',on_delete=models.CASCADE,null=True) updated_date = models.DateTimeField(null=True) def __str__(self): return self.Question -
Why do my Celery Remote Control functions hang?
I am attempting to use Celery's Remote Control functionality to revoke tasks. Most of the time the function I attempt to use app.control.revoke(task_id) just hangs and does not produce a result. There were a few times it worked but 95% percent of the time it hangs. The same is true for app.control.ping I am using Celery version 4.2.1 and Kombu 4.6.8 (attempted upgrading Kombu to 4.6.11 with no change) on Heroku with cloudamqp for RabbitMQ. See below for the stacktrace from when I do a keyboard escape. File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/celery/app/control.py", line 253, in ping timeout=timeout, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/celery/app/control.py", line 454, in broadcast limit, callback, channel=channel, File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 346, in _broadcast matcher=matcher) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 307, in _publish with self.producer_or_acquire(producer, chan) as producer: File "/app/.heroku/python/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 267, in producer_or_acquire with self.producer_pool.acquire() as producer: File "/app/.heroku/python/lib/python3.6/site-packages/kombu/resource.py", line 83, in acquire R = self.prepare(R) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pools.py", line 62, in prepare p … -
Geolocation Django XMLHttpRequest not working inside of Javascript call. Do I need CSRF token?
My call from JS to my django views is not working at all and I am not sure why. Is it because I need a csrf token? If so, how do I even incorporate into the JS? My code in html is like this {% extends '_base.html' %} {% load static %} {% block title %}Location{% endblock title %} {% block content %} <button id = "find-me">Find Storages Near Me</button><br/> <div id="mapid"></div> {% endblock content %} JS function geoFindMe() { // get the coordinates on success function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; // send user data into backend reqeust const request = new XMLHttpRequest(); // post is more secure request.open('POST', '/find_nearby_storage'); request.onload = () => { alert('HTTP request back!'); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); urls.py path('find_nearby_storage/', find_nearby, name='locate'), views.py def find_nearby(request): # get user location if request.method == 'POST': print("hello from the reqeust") return HttpResponseRedirect(reverse('home')) else: return HttpResponseRedirect(reverse('about'))