Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Errno - 13 Permission denied: '/media/ - Django
I am using Django 3.1 in ubuntu, I got an error while uploading media files PermissionError at /admin/main/artist/1/change/ [Errno 13] Permission denied: '/media/artists' Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/media/artists' Exception Location: /usr/lib/python3.8/os.py, line 223, in makedirs Python Executable: /home/rahul/.local/share/virtualenvs/music-69qL54Ia/bin/python This code works in windows, but not in ubuntu Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / '/media/' Models.py class Artist(models.Model): image = models.ImageField(upload_to='artists/%Y/%m/%d/', default='demo-artist.jpg', null=True, blank=True) I tried this but didn't work https://stackoverflow.com/questions/21797372/django-errno-13-permission-denied-var-www-media-animals-user-uploads -
How to Remove single Inverted comma from array in python?
i am new in python.I have array like this a =['1','2'] i want to convert this array into below formet a=[1,2] How to do that? -
Reverse for 'equipment_categories' with arguments '('',)' not found. 1 pattern(s) tried: ['equipments/equipment_categories/$']
I am trying to make a website that sorts equipment based on their category and i am getting the reverse match error when i link the urls on the webpage. Please i need advice on how i can properly pull this off. Thanks in advance. urls.py from django.urls import path from . import views app_name = 'equipments_catalogue' urlpatterns = [ path('equipment_list/', views.EquipmentListView.as_view(), name='equipment_list'), path('equipment_categories/', views.EquipmentCategoryView.as_view(), name='equipment_categories'), path('equipment_by_category/<str:cats>/', views.EquipmentListByCategory, name='equipment_by_category') ] views.py from django.shortcuts import render from django.views.generic import ListView from . import models # Create your views here. class EquipmentCategoryView(ListView): model = models.Category template_name = 'equipment_categories.html' def EquipmentListByCategory(request, cats): equipment_category = models.Equipment.objects.filter(category=cats) return render(request, 'equipment_by_category.html', {'cats': cats , 'equipment_category': equipment_category}) class EquipmentListView(ListView): model = models.Equipment template_name = 'equipment_list.html' template {% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block content %} <h1>Welcome to JPI Equipment Categories Page</h1> {% for category in object_list %} <a href="{% url 'equipments_catalogue:equipment_categories' equipment_by_category.category %}">{{ category.name }}</a><br><br> {% endfor %} {% endblock %} -
What is the equivalent of the Django {% block %} and {% extends %} tags in Next.js?
I am modernizing the code of my Django web application by re-creating its frontend in a separate Next.js application. I am having problems finding the equivalent of the Django {% block %} tag in Next.js. Concretely, all pages across my app share the following HTML skeleton: a navbar at the top, and a mainbar and a sidebar below it. In Django, I achieved this using a base.html file containing the navbar, a {% block mainbar %} tag, and {% block sidebar %} tag and then extended this template from other child templates using {% extends "base.html %}. Here is my Django base.html: <body> <!-- Navbar --> <header id="navbar"> ... </header> <!-- Body --> <div id="body"> <!-- Mainbar --> <main id="mainbar"> {% block mainbar %} {% endblock %} </main> <!-- Sidebar --> <aside id="sidebar"> {% block sidebar %} {% endblock %} </aside> </div> </body> How can I recreate the concept of a {% block %} and {% extends %} tags in Next.js? Or, how can I recreate a template inheritance structure similar to the one above? -
Django forms serialize to JSON for angular API
I need to serialize Django form to json to use API for front on Angular. Dont know how to properly make this. My form: class BSForm(forms.ModelForm): class Meta: model = BS fields =[ 'c','b_input', ] widgets = { 'c': forms.TextInput( attrs={ 'class': 'form-control' } ), 'benchmark_input': forms.Textarea( attrs={ 'class': 'form-control' } ), } labels = { "c": "C Name", "b_input" : "Provide Input to add", } My view: class BSView_API(APIView): def get(self, request, *args, **kwargs): my_form = BSForm() return JsonResponse({"form": my_form}) def post(self, request, *args, **kwargs): if request.method == "POST": my_form = BSForm(request.POST) context = { "form": my_form } if my_form.is_valid(): my_form.save() my_form = BSForm() messages.success(request, 'success!') else: print("An error occurred") print(my_form.errors) messages.error(request, 'Something went wrong: %s ' % my_form.errors.as_data()) return JsonResponse({'nbar': 'benchmark', 'bbar': 'home'}) What's the proper way to serialize such froms for API? I've tried to use list(my_form.__dict__) but the I'm loosing form data. -
Django REST Framework: Posting to URL with ID in URL
Given the following contrived example, how can I POST to a URL with an ID in path and have it resolve the model instance instead of including the model instance in the POST body itself? urls.py path("api/schools/<int:pk>/student/", views.CreateStudentView.as_view(), name="createStudent") models.py class School(models.Model): name = models.CharField(default="", max_length=128) address = models.CharField(default="", max_length=128) mascot = models.CharField(default="", max_length=128) class StudentModel(models.Model): first_name = models.CharField(default="", max_length=128) last_name = models.CharField(default="", max_length=128) notes = models.CharField(default="", max_length=512) school = models.ForeignKey(School, on_delete=models.CASCADE) serializers.py class CreateStudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ("first_name", "last_name") views.py class CreateStudentView(generics.CreateAPIView): serializer_class = CreateStudentSerializer queryset = Student.objects.all() I want to be able to POST just the new student's first name and last name to the URL to create a new student in my database. However, because I don't provide a School object in the body of my POST I get an error. I was hoping it would be possible for my code to resolve which school I want to add the student to because the URL contains the ID. I get an error when I POST the following body to /api/schools/1/student/. The school with an ID of 1 does exist in the database. { "first_name": "John", "last_name": "Smith" } IntegrityError at /api/schools/1/student/ NOT NULL … -
Django reverse lookup on multilevel models
I am trying to query for storetypes at a location without success. I can however query for locations in a city using the models shown.I want to use the querysets in a menu with a submenu with another submenu at the root url of the project. Please help. #models class Supplier(): shopping_center = models.ForeignKey('Shopping_center') storetype = models.ForeignKey('Storetype') class City(models.Model): name = models.CharField() class Location(models.Model): city = models.ForeignKey('City') class Shopping_Center(models.Model): location = models.ForeignKey('Location') class Storetype(models.Model): title = models.CharField() -
How do I structure a project which uses django and ebay python sdk?
I am completely new to django and making non-static websites, so I'm sorry if this is a stupid question, but I couldn't find info anywhere on how to actually structure files for a django project. I built a program that scrapes data from one online store, formats the data, and then adds the item to eBay via ebay python sdk. For this, I wrote three .py files - one that uses the requests library to get product data, one that formats the data into the correct structure to feed into the api, and finally the file that makes the api call. The way I understand eBay SDK, these files all have to be in the ebaysdk directory in order to work (at least, the one that makes the api call has to be in there). My problem is that I now want to make a simple django website, which takes a product url from the user from that store, and then automatically uploads the product. I am confused about how to make my three .py files work with a django website? Do I have to restructure the whole thing and put them into my views.py file as functions? But then, … -
Django allauth signup view not working coorecly
I have a problem signup allauth. I am tryin add new account but when try it i get this error. Other functions(login, logout and other password works) are working. Other view is working but singup not working, when i want to add new user, i got this problem. Internal Server Error: /accounts/signup/ Traceback (most recent call last): File "/root/PycharmProjects/essahmi/venv/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/root/PycharmProjects/essahmi/venv/lib/python3.8/site- packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/PycharmProjects/essahmi/venv/lib/python3.8/site- packages/django/views/generic/base.py", line 70, in view . . . return super(CloseableSignupMixin, self).dispatch(request, File "/root/PycharmProjects/essahmi/venv/lib/python3.8/site- packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/root/PycharmProjects/essahmi/venv/lib/python3.8/site-packport_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'some' I have not written any code yet baceuse i … -
cannot parse {{post.content}} inside if condition
I made a blog website and I am trying to render all my posts. I have truncated my posts whose content was greater than 500 alphabets and I added a read more anchor tag. I want that read more anchor tag to come only if my content is greater than 500 works I wrote this line but it didn't work: {% if len({{post.content}}) >500 %} can someone help me with what I should use in place of this code? -
TypeError: Cannot read property 'title' of undefined | django react js
I can't figure out why it's showing TypeError in Card. Though it's working fine in backend. Error: TypeError: Cannot read property 'title' of undefined view.js ... export default class ArticleDetail extends React.Component { state = { articles: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`).then( res => { this.setState({ article: res.data }); } ) } render (){ return ( <Card title={this.state.article.title}> <p> {this.state.article.content} </p> </Card> ) } } models.py class Article(models.Model): title = models.CharField(max_length=20) content = models.TextField() -
How to set value on forms.ChoiceField in django view?
This is my form : class ch_form(forms.Form): ch_field = forms.ChoiceField( required=True , label= 'ch_field : ' , ) and this is my view : def testView(request): form = ch_form( initial={ 'ch_field':[ (1, 'test1'), (2, 'test2'), (3, 'test3'), ] } ) But its not work. So my question is how can I set value for forms.ChoiceField in view function during the runtime. sorry for my bad English. -
django makemessages error "Non-ASCII string at"
When I run the command python manage.py makemessages -l tr I get the following error "xgettext: Non-ASCII string at ./venv/Lib/site-packages/fpdf/fonts.py:22.". I go to the file with errors and look at the relevant line, this line _ ("xx") is not a line that starts like this so why does it give such an error here? took a screenshot of the moment i got the error and the corresponding fonts.py file fonst.py image view -
How to draw rectangle into HTML page using Python
I am using Django with Python to create an HTML page as shown in the image with rectangles image -
TypeError: join() argument must be str or bytes, not 'PosixPath'
So, I'm receiving the following error: TypeError: join() argument must be str or bytes, not 'PosixPath' It happens while checking my Django installation on Ubuntu 16.04. The full error would be: STATIC_ROOT = os.path.join(BASE_DIR, 'static') File "/usr/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'PosixPath' This is from the settings.py file. In the file I have: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') On my development environment it is working and running through it, yet here I receive the error. The version of Python on production is 3.5.1-3. Normally the packages should be installed the same as well (pip freeze/install -r). Anyone have an idea to push me in the correct direction? Thanks in advance, -
Django child fields return null on parent GET request
I'm having an issue getting the proper data through a GET request. The parent Order has several OrderItem children. When doing a POST request to create the parent with a child at the same time, the response shows the created parent object but with all fields set to null for the child. I don't understand why it does this as in Django admin page I can verify that the child has saved the data properly upon the parent's creation. When showing the list of parents or the details of one parent, it seems the child's data are not returned properly. However in the serializers I have the corresponding fields. What am I missing or doing wrong? Thanks for your responses! I'm getting this on the endpoint /api/orders/24: { "bar_id": 2, "order_items": { "order_id": null, "ref_id": null } } And this on the endpoint /api/order_items/21: { "order_id": 24, "ref_id": 3 } So I should be getting on the endpoint /api/orders/24: { "bar_id": 2, "order_items": { "order_id": 24, "ref_id": 3 } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models … -
Django serializers filter foreignkey
view: class MPNView(viewsets.ModelViewSet): queryset = MPN.objects.all() serializer_class = MPNSerializer serializers: class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class MPNSerializer(serializers.ModelSerializer): products = ProductsSerializer(many=True) class Meta: model = MPN fields = "__all__" model: class MPN(Model): number = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) class Product(Model): mpn = models.ForeignKey(to=MPN, on_delete=models.CASCADE, related_name="products", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) Results i am getting: [ { "id": 1221, "products": [], "number": "B07BMTYSMR", "created_at": "2020-09-29T03:05:01.560801Z" }, { "id": 1222, "products": [ { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", }, { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", } ] } ] Results i am expecting: [ { "id": 1222, "products": [ { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", }, { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", } ] } ] Here is my code . Shared view, model and serializers Here i am trying to get result with ForeignKey related fields But, I wants to add one filter so it will ignore data where products is [] (empty array) Please have a look how can i achive that -
django rest framework vs django rest framework 2
hello can someone explain to me the difference between django-rest-framework and django-rest-framework 2 because on internet both have different sites https://www.django-rest-framework.org/ and http://www.tomchristie.com/ bot both have same GitHub repo. and I am also very much confused between laravel and django way of returning json response in laravel we can return query result and it will automatically convert in JSON but in django we create serializers but by creating nested serializers can we able to return any type of response related to those tables? it will be appreciated if someone can provide me with some reference to learn nested serilizing thanks in advance... -
How to allow users to pay with paypal each other in Django
I was following This and ended up with users can pay me and get their product, however, I want users to pay each other. Both users should enter their email address linked with their PayPal, now how can I make the transaction transfer money to other user email address instead of me? My html <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <scriptsrc="https://www.paypal.com/sdk/js?client-id=MY_SANDBOX_CLIENT_ID"></script> <h1>you are about to pay {{ trade.price }}</h1> <div id="paypal-button-container"></div> <script> paypal.Buttons({ createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '{{trade.price}}' } }] }); }, onApprove: function (data, actions) { return actions.order.capture().then(function (details) { $.ajax({ url: "{% url 'payment:pay_trade' trade.id %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}" }, method: 'POST', success: function (response) { alert('Successfully paid') }, error: function (response) { alert('something went wrong') } }) }); } }).render('#paypal-button-container'); </script> The function: def pay_trade(request, trade_id): trade = get_object_or_404(Trade, pk=trade_id) if request.method == 'GET': return render(request, 'payment/pay_trade.html', {'trade': trade}) else: # Give something to the buyer # No idea how to check if the transaction was made but i hope so ;-; return JsonResponse({}) Also, it would be great if someone can help me to check if the payment is done before making the function, thanks! -
Override the maximum number of characters in the admin form
There is a model with a maximum length of 32 characters in the field. The model is used in the form in the administrator interface. The value to be entered in the field must allow an unlimited number of elements separated by commas. This field is then parsed and passed to the bulk_create method. The problem is that the model level length limits do not allow entering more than 32 characters into the form. How to avoid this constraint? models.py class MyModels(models.Models): .... items = models.CharField(verbose_name=_(u'Item ID'), max_length=32) forms.py class ItemForm(ModelForm): class Meta: model = MyModel fields = ['items'] -
Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P<pk>[0-9]+)$']
I have two models and a third model for a many-to-many relationship the form should take a date from the first model that is the date model and the user will choose images from the second model and connect them but when I'm making the form I'm getting this error Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P[0-9]+)$'] my models.py class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20,unique=True) sof_zman_1 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_2 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_tefila = models.TimeField(auto_now=False,blank=True,null=True) def get_absolute_url(self ): return reverse('date_detail',kwargs={'pk':self.pk}) def __str__(self): return self.hebrew_date # images class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':self.pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) image = models.ManyToManyField('luach.images',related_name='images') def __str__(self): return self.pk my views.py def create_day_image_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': form = DayImageForm(request.POST) if form.is_valid(): dayimage = form.save(commit=False) dayimage.date = date dayimage.save() return redirect('date_detail',pk=mydate.pk) else: form = DayImageForm() return render(request, 'luach/dayimage_form.html',{'form': form}) my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('date/<int:pk>',views.MyDateDetailView.as_view(),name='date_detail'), path('date/<int:pk>/add_image/',views.create_day_image_view,name='add_image') ] and my dayimage_form.html {% block content %} <div class='container'> <div class="jumbotron"> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type='submit' class='btn btn-success'>save</button> </form> <a class="btn btn-danger" href="{% url 'date_detail' pk=mydate.pk %}">cancel</a> </div> </div> {% endblock %} -
Error: Invalid value for '-A' / '--app': module 'proj' has no attribute 'celery'
I am trying to run celery using supervisord using command supervisorctl start sv_celery. I'm getting the below error. Error: Invalid value for '-A' / '--app': module 'proj' has no attribute 'celery' My proj directory has the celery.py and tasks.py files My Celery.py: from celery import Celery import os if(os.environ.get("DJANGO_ENV") == "production"): os.environ.setdefault("DJANGO_SETTINGS_MODULE", \ "projectname.settings_prod") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", \ "projectname.settings") import django django.setup() app = Celery('proj', broker='pyamqp://', backend='redis://localhost', include=['proj.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() My Tasks.py from .celery import app @app.task def add(x, y): return x + y My Supervisord/conf.d/celery.conf ; the name of your supervisord program [program:sv_celery] ; Set full path to celery program if using virtualenv command=/root/venv/bin/celery -A proj worker --loglevel=INFO ; The directory to your Django project directory=/root/projectname/projectname ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=root ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/celery_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/celery_worker.log ; If true, this program will start automatically when supervisord is started autostart=true ; May … -
Sort Django Rest API Endpoint Response by Date
Let's say I have a response from a endpoint. I am using Django Rest Framework. Let's say this is what is returning from endpoint. [ { Name: "q4", Date: "2020-09-30T18:00:52+03:00", Url: "/test/test", }, { Name: "q2", Date: "2020-10-01T13:32:21+03:00", Url: "/test", }, { Name: "q1", Date: "2020-09-30T17:42:06+03:00", Url: "/xyz", }, { Name: "q3", Date: "2020-09-30T13:04:23+03:00", Url: "...", }, { Name: "q5", Date: "2020-10-01T13:04:45+03:00", Url: "...", }, ] How am I going to change ordering of response by respecting to date and time like this? [ { Name: "q3", Date: "2020-09-30T13:04:23+03:00", Url: "...", }, { Name: "q1", Date: "2020-09-30T17:42:06+03:00", Url: "/xyz", }, { Name: "q4", Date: "2020-09-30T18:00:52+03:00", Url: "/test/test", }, { Name: "q5", Date: "2020-10-01T13:04:45+03:00", Url: "...", }, { Name: "q2", Date: "2020-10-01T13:32:21+03:00", Url: "/test", } ] -
How to make a djangomodel form appear in two different colums with fields divided into two coulmn?
I have this form rendered in my webapp. I dont want this in single column, instead in two columns with fields divided. How can I do that?? This is my form in template. <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success" formaction="{% url 'addcustomer' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'customerlist' %}">Cancel</button> </form> -
How to update User Profile in Django?
I am trying to update user profile, and I am using signals for this, but when i create a user from my Django default admin panel then it's creating a record automatically in profile table with Null values. I am using OneToOneField relation between User and Profile models, Please let me know how i can update the profile section after create a user. It's functionality is something like this, when i create a user then I will assign the user a Group, if the user is logged in on my website then he/she can see the functionality of that group and profile update functionality is available in that Group. Here is my Profile modal... class Profile(models.Model): age=models.CharField(max_length=225) customer=models.OneToOneField(User, related_name='related_user',on_delete=models.CASCADE) @receiver(post_save, sender=user) def create_profile(sender, instance, created, **kwargs) if created: Profile.objects.create(user=instance) group = Group.objects.get(name='profile') instance.groups.add(group) Now it's happening when I create a user it's automatically creating record in profile table, but I want the record update when I assign the profile group to that user (If i assign profile group to the user then profile record should be update), after that i will update all the fields in user profile.