Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Server Error (500) when using s3 aws amazon to store media and static fil
I got Server Error (500) when trying to launch any django page with DEBUG=FALSE, even with default admin page. my static files and media files are configured to upload to s3 aws storage Anyone has encountered this problem ? Please give me some advice Many thanks -
How to implement autocomplete user search in React and Django Rest Framework
So basically I'd like to implement a user search system in react which would send an api request to my django backend which would send back the results. This is an easy implementation if I wanted the results once I hit search but I want the results displayed as autocompletes. For example in Twitter it autocompletes what you are searching for. How would I implement this. I am using axios for my requests if that helps. A side note would be that I'd like to wait maybe a second or 2 before sending the request because I would want to send to many requests and slow down the server. Thank you! -
Display User's 'is_active' status in TabularInline Django
I have a Client object that has a User and a Company objects as FKs class Client(models.Model): user = models.OneToOneField(User) company = models.ForeignKey(Company, blank=True, null=True) In my CompanyAdmin, I want a list of all clients as a TabularInline, including the active status of each client (based on user object) class CompanyClients(admin.TabularInline): model = Client fields = ('user', 'master') class CompanyAdmin(admin.ModelAdmin): inlines = [CompanyClients] I want to add a column in my TabularInline to indicate that that user is active or not. I tried using 'user__is_active' to my fields but I get this error: Unknown field(s) (user__is_active) specified for Client I just want an indication even if read-only (which I tried by putting a readonly_fields and it didn't work too), not looking to save/edit each client user's active status value from the Tabular form. How can I approach this? Thanks in advance. -
User avatar not displayed in Django
models.py class Avatar(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, null=True) avatar = models.ImageField(upload_to='user_avatars', null=True) forms.py class UserPhotoForm(forms.ModelForm): class Meta: model = Avatar fields = ('avatar', ) widgets = { 'avatar': forms.FileInput(attrs={'class': 'input'}), } views.py def cabinet(request): user = request.user if request.method == 'POST': form = UserPhotoForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() else: form = UserPhotoForm() return render(request, 'account/cabinet/cabinet.html', {'form': form}) cabinet.html <div class="avatar"> {{ request.user.avatar.url }} #there is trying {{ request.user.avatar.avatar.url }} <img src="{{ request.user.avatar.avatar.url }}" alt="" width="80px" height="80px"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" id="file"/> </form> I want to user have a avatar. So I created the model and the form. Image is not displaying on the page. But form saves the image to folder. Where is mistake? request.user.avatar.url doesn't work. Maybe the image is not attached to User? Thanks for the help P.S. djagno-avatar is not good for me. -
autocomplete in django-admin site for every foreign-key field
What could be the way to make every foreign-key field searchable/autocomplete in django-admin site in general? Means whenever I define a foreign-key field in model, i would need nothing more to make it autocomplete. I could not find any such module because the module like https://django-autocomplete-light.readthedocs.io/en/master/gfk.html facilitate with even complicated way, and do not provide a thing like odoo where developer would not need to code for each field to make it autocomplete I have using odoo, where I define a field in any child_model1 like parent_id = fields.Many2one('my_module.parent_model1') I simply get a searchable and autocomplete select list in my child_model1's form, I have nothing to add more anywhere. But in contrast with django when i define a filed on child_model1 like parent_id = models.ForeignKey(ParentModel1) First i would need to define on_delete=?, even I have no option to set anywhere globally that hello django please always restrict on delete until I tell you to make a field on_delete=cascade Then I need that all of my foreign-key fields in any model need to be autocomplete but I always have to write each field in each each child model's admin like autocomplete_fields = ['parent_id'] also I have to give something like search_fields … -
How to use Cross Site Request Forgery protection correctly?
I've only started getting into web programming with Django recently. In order to make my website more secure, I used csrf_token when sending POST request, followed what I saw in https://docs.djangoproject.com/en/3.1/ref/csrf/. However, as I included <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> in my HTTP file from Javascrip Cookie Library, I can get the csrf_token directly from my browser in Inpsect>console. I am not sure if I did this correctly or not, please give me some pointers. -
Django CSS File Not Working/Not being served
I cannot figure out why my css file is not working. I added my css, html and settings.py files. Can anyone help? I've tried collectstatic but get an error: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:\\mysite\\dreamboard\\static\\dreamboard\\style.css' I tried replacing my path in the STATICFILES_DIRS but it still does not work. I'm not sure what to do. It could be the bootstrap? Or something. I want to have a style sheet so I can my form to a popup button. Everything is titled and spelled correctly. Any ideas? Here are my files: {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'dreamboard/style.css' %}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/73cead4581.js" crossorigin="anonymous"></script> <title>Hello, world!</title> </head> <body class="bg-light"> <h1>Hello, world!</h1> <div class="container"> <div class="row bg-dark"> <div class=" col-sm"> <h1 style="color:white">Dreamboard</h1> </div> <div class="col-sm"> <button class="btn-lg btn-primary" type="submit">Add Dream</button> </div> </div> </div> </div> <form class="" action="" method="post" autocomplete="off"> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{form.first_name|as_crispy_field}} </div> <div class="col-md-6"> {{form.last_name|as_crispy_field}} </div> </div> {{form.dreamItem|as_crispy_field}} <br> <button type="submit" class="d-grid gap-2 col-12 btn btn-success">Submit</button> </form> <!-- Optional JavaScript; choose … -
change specific field of an object using POST method django rest api
i'm using djangorestframework. and i want to be able to change specific field of my objects using POST method. can anybody help please?? i have no idea how to do that. here is my model: class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) gender = models.CharField(max_length=10) national_code = models.CharField(max_length=11) personal_code = models.CharField(max_length=15) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=50) married = models.BooleanField() age = models.IntegerField() wage = models.IntegerField() def __str__(self): and i want to be able to for example change one of my employee's wage(with personal code 123)to new wage 500000 using such url: POST /myupdate/123/500000 -
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.