Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python weasyprint unable to find 'gobject-2.0-0' library
While following the installation process for Saleor headless e-commerce, the Python Weasyprint package fails to load the gobject-2.0.0 dependency which I have already installed on my machine using Macport. Below is the source code showing where the error is emitting from after starting the Django server. The file holds utility functions for generating invoices for the plugin file. utils.py import os import re from datetime import datetime from decimal import Decimal import pytz from django.conf import settings from django.template.loader import get_template from prices import Money from weasyprint import HTML # <----------- This what is emitting the error because the # package can't find the needed dependency. from ...giftcard import GiftCardEvents from ...giftcard.models import GiftCardEvent from ...invoice.models import Invoice MAX_PRODUCTS_WITH_TABLE = 3 MAX_PRODUCTS_WITHOUT_TABLE = 4 MAX_PRODUCTS_PER_PAGE = 13 def make_full_invoice_number(number=None, month=None, year=None): now = datetime.now() current_month = int(now.strftime("%m")) current_year = int(now.strftime("%Y")) month_and_year = now.strftime("%m/%Y") if month == current_month and year == current_year: new_number = (number or 0) + 1 return f"{new_number}/{month_and_year}" return f"1/{month_and_year}" def parse_invoice_dates(number: str): match = re.match(r"^(\d+)\/(\d+)\/(\d+)", number) if not match: raise ValueError("Unrecognized invoice number format") return int(match.group(1)), int(match.group(2)), int(match.group(3)) def generate_invoice_number(): last_invoice = Invoice.objects.filter(number__isnull=False).last() if not last_invoice or not last_invoice.number: return make_full_invoice_number() try: number, month, year = parse_invoice_dates(last_invoice.number) … -
I get a form object when I need want to get a form:
Views.py: from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserPostForm from django.contrib.auth.models import User def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def profile(request, username): post_form = UserPostForm() context = { 'username': username, 'post_form': post_form, } return render(request, 'users/profile.html', context) urls.py: from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path("admin/", admin.site.urls), path("", include("photoblog.urls")), path("register/", user_views.register, name="register"), path("profile/<str:username>", user_views.profile, name="profile") profile.html: {% extends 'photoblog/base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Welcome to the {{ username }} profile page</h1> <form method="POST"> {{post_form}} </form> {% endblock %} forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from photoblog.models import Post class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserPostForm(): class Meta: model = Post fields = ['title', 'author', 'content', 'date_posted'] Whenever I load up the page, I get an <users.forms.UserPostForm object at 0x7ff183aea670> when I want the actual form to show up on the page. How do I get that to work? I tried uploading UserPostForm() as a variable in the view … -
(Django CBV) Need object be attached to a user with CBV
I implemented this functionality with using FBV, but when I'm trying to use CBV, Objects were created with empty user field. views.py class BlockCreate(CreateView): model = TrainingBlock template_name = 'training_room/create_block.html' form_class = BlockForm success_url = reverse_lazy('gym') def set_user(self, form): form.instance.user = self.request.user return super(BlockCreate, self).set_user(form) models.py class TrainingBlock(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) duration = models.IntegerField(default=10) if_ended = models.BooleanField(default=False) def __str__(self): return self.name forms.py class BlockForm(forms.ModelForm): class Meta: model = TrainingBlock fields = '__all__' exclude = ['user'] -
django sql .raw filtering on a string not working
I am trying to filter on a foreign key but getting an error. Current code is: Views.py def kingmailboxcodesshow(request): lname = "King" lockbox_list = MailBoxCodes.objects.raw('SELECT * FROM mailboxcodes WHERE Address_id__contains %s',[lname]) return render(request,"users/mailboxcodesshow.html",{'MailBoxCodes':lockbox_list}) receiving this error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''King'' at line 1") I am still really new to django and python, looking at the error I am thinking i need a few less ' around the King, but I am not sure how to make that happen. I have a bunch of addresses in the Address_id and I just want to retrieve all the address with the work King in their street address. I would greatly appreciate any and all assistance. Thank you in advance. -
ImportError: cannot import name 'Random' from 'django.db.models.functions'
Well, I am trying to run my django project in new environment, I installed all of my requirements although every package is installed but it is still giving me below mentioned error. I am not sure but I am guessing it is due to version conflict of some modules. Can anyone help me out? Thanks in Advance :) I looked for existing solutions or someone who faced similar situation but no success. -
drf-yasg doesn't include the "api/" portion of the urls
I'm using drf-yasg to generate a Swagger schema, but it removes the "api/" portion of the url. schema_view = get_schema_view( openapi.Info( title="My API", default_version='v1', description="...", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="hello@mycompany.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], ) router = routers.DefaultRouter() router.register(r'spaces', SpacesViewSet, basename='spaces') urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('api/', include(router.urls)), path('api/search-options', SearchPlacesOptionsView.as_view()), ] result on /swagger As you can see for the routes from the drf router, it doesn't include the /api portion of the url. However for the regular api/search-options endpoint it removes the /api portion as well, so I don't think it has something to do with the router. -
Creating a form for each comment jquey and djang
I want for my website in the comments section, when the user clicks on the answer, an input form will be added to the bottom of the same comment, and if there is another form for other comments, they will be hidden. this is my code html and django: <li class="comment" style="margin-right: 100px;"> <div class="comment-body"> <div class="single-comment"> <div class="comment-img" style="margin-left: 50px;"> {% bs_icon 'person' size='65' %} </div> <div class="comment-inner"> <h6 class="commenter"> <a class="hover-flip-item-wrapper" href="#"> <span class="hover-flip-item"> <span data-text="{{ reply.user_name }}">{{ comment.user_name }}</span> </span> </a> </h6> <div class="comment-meta"> <div class="time-spent">آبان 23, 1401 در 12:23 بعد از ظهر</div> <div class="reply-edit"> <div class="reply"> <a class="comment-reply-link hover-flip-item-wrapper" href=""> <span class="hover-flip-item"> <span data-text="Reply" id="reply-comment">پاسخ</span> </span> </a> </div> </div> </div> <div class="comment-text"> <p>{{ comment.text_comment}}</p> </div> </div> </div> </div> <div class="comment-respond reply-form" id="{{ comment.id }}" style="margin-right: 100px;display:none;" > <h4 class="title">پاسخ شما</h4> <form action="#"> <p class="comment-notes"><span id="email-notes">آدرس ایمیل شما منتشر نخواهد شد.</span></p> <div class="row"> <div class="col-12"> <div class="form-group"> <label>پاسخ شما</label> <textarea name="message" placeholder="بنویسید ..."></textarea> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>نام <span>*</span></label> <input id="name" type="text"> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>ایمیل <span>*</span> </label> <input id="email" type="email"> </div> </div> <div class="col-lg-12"> <div class="form-submit"> <button name="submit" type="submit" id="submit" href="#" class="axil-btn btn-bg-primary w-auto">ارسال پاسخ</button> </div> </div> … -
Web Scraping refreshing in Django Project
I have to create a project with the framework django, and I have to introduce a system of web scraping with bs4. I did it, but I can’t refresh the data. I scrap the data with bs4, requests and time, them display them into my html page. But when I print the data with 3 secondes refreshing with module time, the data are refreshing. But when I display the data into my html page, they don’t actualised them. I would like to be able to scrap and display data from other website into my django app. -
Django multiple table query - convert MySQL to Django (Python) query
I need to figure out how to translate MySQL query into Django (Python) language. Any help? Basically I need to get the total from each table plus the remain total after spend. class Trip(models.Model): name = models.CharField('Name', max_length=254) class Account(models.Model): name = models.CharField('Name', max_length=254) class Wallet(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) incoming_date = models.DateField(verbose_name='Incoming Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) class Expense(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) outcome_date = models.DateField(verbose_name='Outcome Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) SELECT *, (wallet_total - expense_total) AS remain_total FROM ( SELECT account.name, SUM(wallet.total) AS wallet_total FROM account INNER JOIN wallet ON wallet.account_id = account.id WHERE wallet.trip_id=4 GROUP BY account.name ) AS wallet, ( SELECT account.name, SUM(expense.total) AS expense_total FROM account INNER JOIN expense ON expense.account_id = account.id WHERE expense.trip_id=4 GROUP BY account.name ) AS expense; -
Django and AWS S3 returns This backend doesn't support absolute paths
I am working on a Django project whereby when users register their profiles get automatically created using the signals.py. Everything works fine in the localhost, but now I want to migrate to the AWS S3 bucket before deploying my project to Heroku. After configuring my AWS settings in settings.py, I get the error NotImplementedError: This backend doesn't support absolute paths. after trying to create a superuser through the python manage.py createsuperuser command. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', null=True, blank=True) bio = models.TextField() resume= models.FileField('Upload Resumes', upload_to='uploads/resumes/', null=True, blank=True,default='resume.docx') Here is the signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And here is my settings.py; # S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID='' AWS_SECRET_ACCESS_KEY='' AWS_STORAGE_BUCKET_NAME='' # Storages configuration AWS_S3_FILE_OVERWRITE= False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Only public read for now AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL='public-read' STATIC_URL = '/static/' Inside the s3 bucket, I have the default.jpg and resume.docx in the root folder. Any assistance will be highly appreciated. Thanks. -
How to test all Object values in a python function
I would like to test all x values in this function, without calling each x value ( x[0] ...), so a kind of x[n] or ' for all values of x'. And to list all TickerZ values in a list depending on if the x value passed the IF statement. room = str('Bingo Bango Bungo EURUSD=X') x = room.split() def Symbol(symbol): aapl = yf.Ticker(symbol) ainfo = aapl.history(period='1y') if len(ainfo) >= 40: print('yes it is a symbol') global tickerZ tickerZ = symbol new_Memory = Memory.objects.create(user=current_user, raw_message=room, date1=datemin, date2=datemax, ticker=tickerZ, command=cmd_exec) new_Memory.save() return tickerZ symb1 = Symbol(x[0]) symb2 = Symbol(x[1]) symb3 = Symbol(x[2]) symb4 = Symbol(x[3]) Code explanation: So basically, i have a string, i'm splitting it into words, which represent all x values. In this case x[0] is Bingo. I'm passing all x's into a IF statement to filter the relevant x values. I know if a x is relevant if TickerZ has a value, because the variable is defined after the filter. -
How to make Django redirect to other page?
I have an app named "works" where all my works should contain. There are cards-previews to my works. So I want them clickable and redirecting to the work that is clicked and soon shown the html file of the work. The problem is in redirecting to that work. In myapp/urls.py is the following urlpatterns = [ path("", WorksView.as_view(), name="works"), path("<slug:work_slug>/", WorkDetailView.as_view(), name="work-detail"), ] myapp/models.py class Works(models.Model): -- other attributes -- slug = models.SlugField( null=False, db_index=True, blank=False, max_length=255, unique=True, verbose_name="URL", ) def get_absolute_url(self): from django.urls import reverse return reverse("work-detail", kwargs={"work_slug": self.slug}) So what class based view should be used in myapp/views.py for WorkDetailView? I have tried View, TemplateView, RedirectView, but neither of them work properly that I want to. The last try was that: class WorkDetailView(View): def get(self, request, *args, **kwargs): work = get_object_or_404( Works, slug=kwargs["work_slug"] ) print(work.get_absolute_url()) return render(request, work.get_absolute_url(), {"works_data": work}) The work.get_absolute_url works good, but Django cant find template My project folder: But when I change the return string to return render(request, f"{work.get_absolute_url()[1:-1]}.html", {"work": work}) it works and prints "works/not-found/", but I dont think that it is the correct way So how can I do it right? The last try was to make that using View but Django … -
Django signals / notification system
Is it a good aproach to use Django signals to implement email notification system? I have CustomUser model related with CustomUserPreferences planned as follows: class CustomUserPreferences(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, default=None, on_delete = models.CASCADE, primary_key = True) lesson_notification = models.BooleanField(default=True) journal_notification = models.BooleanField(default=False) login_notification = models.BooleanField(default=False) excercise_notification = models.BooleanField(default=False) homework_notification = models.BooleanField(default=True) class CustomUser(AbstractUser): ... email = models.EmailField(_('email address'), unique=True) preferences = models.OneToOneField(CustomUserPreferences, null = True ,default=None, on_delete = models.CASCADE) students = models.ManyToManyField(to = 'self', related_name = 'teachers', symmetrical = False, blank = True) Whenever a new object of lets say Lesson is created I want to send an email to the user and that's fine - becaouse it won't overload any server. The question is: will it pay off to use signals for a list of users that contains lets say 100s or 1000s of users? I'm afraid it will slow down the whole application. Is there any other "clear and elegant" way to do this? Django docs advices not to use signals whenever it's possible. -
api call method and viewset
I try to create a api call: class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGgroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer_class()(mainGroups) return Response(serializer.data) serializer: class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] So the main url works: http://127.0.0.1:8000/djangoadmin/groups/ But if I go to: http://127.0.0.1:8000/djangoadmin/groups/maingGroups/ I get this error: { "detail": "Not found." } urls.py: router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] and urls.py of admin looks: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("djangoadmin/", include('djangoadmin.urls')), path("admin/", admin.site.urls), ] Question: how to create api method in main url? -
I have created a django ModelForm that is not showing up in my html template, I am trying to determine why that code is not rendering my form?
models.py from django.db import models # Create your models here. class Subscriber(models.Model): """A subscriber Model""" email = models.CharField(max_length=255, blank=False, null=False, help_text="Subscriber Email Address", unique=True) full_name = models.CharField(max_length=100, blank=False, null=False, help_text="First and Last Name") class Meta: verbose_name = "Subscriber" verbose_name_plural = "Subscribers" forms.py from django.forms import ModelForm from .models import Subscriber class SubscriberForm(ModelForm): class Meta: model = Subscriber fields = ["email", "full_name"] views.py from django.shortcuts import render from .forms import SubscriberForm from django.http import HttpResponseRedirect from django.contrib import messages # Create your views here. def subscriber(request): if request.method == "POST": subscriber_form = SubscriberForm(request.POST or None) if subscriber_form.is_valid(): subscriber_form.save() messages.success(request, "") return HttpResponseRedirect("/") else: subscriber_form = SubscriberForm() context = { "form_subscriber": subscriber_form } return render(request, "subscriber/subscriber_form.html", context) subscriber_form.html {% block content %} <div> <form method="POST"> {% csrf_token %} {{ subscriber_form.as_ul }} <input type="submit" value="Submit"> </form> </div> {% endblock %} Only my submit button is publishing, however the form is never showing up for me. I have followed the django docs exactly and still am not getting any good results. -
how to call a function as a context in django
class User(AbstractUser): GENDER_STATUS = ( ('M', 'Male'), ('F', 'Female') ) address = models.TextField(null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) def get_full_name(self): return f'{self.first_name} {self.last_name}' i declare a function get_full_name and then i want too call it in my view and show it in my template. this is my view from django.shortcuts import render from accounts.models import User def about_us(request): fullname = User.get_full_name context = { 'fullname': fullname } return render(request, 'about_us.html', context=context) and this is my template as you can see i used a loop for my context <div class="container"> <div class="d-flex flex-wrap justify-content-around"> {% for foo in fullname %} <p>{{ foo }}</p> {% endfor %} </div> </div> but i cant get the get_full_name parameters in my template as value too show. i'll be more than happy if sombodey help me. THANK YOU! -
Cannot assign "OrderItem.product" must be a "Product" instance
I am trying to create a "create order" endpoint, i keep getting Cannot assign "<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f50dad00f70>": "OrderItem.product" must be a "Product" instance. heres my models def product_images(instance, filename): return f"product/{instance.product_name}/{filename}" class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField( storage=MediaRootS3BotoStorage(), upload_to="product_images", null=True, blank=True, ) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Product, self).save(*args, **kw) # Ecommerce Models Store and Product def store_images(instance, filename): return f"{instance.store_name}/{filename}" class Store(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField(upload_to="store_images", null=True, blank=True) delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) address = models.CharField(max_length=100, null=True, blank=True) phone_number = models.CharField(max_length=100, null=True, blank=True) products = models.ManyToManyField("Product", through="StoresProduct") def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Store, self).save(*args, **kw) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField("Product", through="StoresProduct") quantity = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def get_total(self): return self.product.price * self.quantity class StoresProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(Store, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) quantity = models.IntegerField(blank=True, null=True) date_created … -
Django printing variable in template that has been passed to it in python
I am trying to get 'date' which can be eg 2023/01/29 to print in my template file. def time_booking(request): if 'date' in request.COOKIES: context = { 'date':request.COOKIES['date'], } print("Run Run") return render(request, "path_to_file.html", context) <h1>Date will be here here</h1> {% if date != -1 or null %} <h1> Date is real {{date}}</h1> {% else %} <h1> Date is not real{{date}} </h1> {% endif %} <h1> complete run </h1> The code currently check if the variable 'date' exists and isn't -1 but I then go to print it and the content doesn't come out. I tried using a single set of {} as well as using print(content[date]), but again the variable was not output. I am trying to get it to output the date which has been entered before hand. Any help would be greatly apricated. -
Static Files not loading when DEBUG = False
I'm using namecheap shared hosting and I hosted my site using cpanel. My site is working fine but if i made DEBUG = False in project settings.py file the static files are not loading. My site url: https://drshahidabegum.com/ settings.py ----------- # Static files (CSS, JavaScript, Images) STATIC_DIR = [ BASE_DIR / "static", ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py in project folder ------------------------- """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dr_shahida.urls')), ] # Configure Admin Titles admin.site.site_header = "DR. Shahida Begum" admin.site.site_title = "DR. Shahida Begum" admin.site.index_title = "Welcome to Admin Dashboard" handler404 = 'dr_shahida.views.error_404_view' urls.py in app folder ------- from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='index'), path('testimonial/', views.testimonial, name='testimonial'), path('contact/', views.contact, name='contact'), path('blog/', views.blog, name='blog'), path('blog/post/<int:post_id>', views.blogdetailview, name='blogdetailview'), path('set_language/<str:ln>', views.set_lang, name='set_lang'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want my static files to work when DEBUG = False in project settings.py file. -
Truly dynamic DateField values in Django
Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the default parameter on the end field – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(default=datetime.date.today) – will populate the field with a fixed value. A property to work around the problem – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(blank=True) @property def get_end(self): if not self.end: return datetime.date.today() return self.end – does not work with querysets. Is there any way to implement a truly dynamic value on the database level using Django's ORM? -
Django-graphene query sorting is not working
I have model Event which I want to sort by event_datetime column in resolver, but it doesn't work. My Event model looks like this: class Event(models.Model): name = models.CharField(db_index=True, max_length=255) event_type_id = models.ForeignKey(EventType, on_delete=models.PROTECT, default='friendly match', related_name='events_by_type') city = models.CharField(max_length=255, db_index=True, blank=False) country = models.CharField(max_length=255) place_id = models.ForeignKey(Place, on_delete=models.SET_NULL, null=True, related_name='events_by_place') event_datetime = models.DateTimeField() tournament_id = models.ForeignKey(Tournament, on_delete=models.PROTECT, blank=True, null=True, related_name='events_by_tournament') description = models.TextField(blank=True) organizer = models.ForeignKey(User, on_delete=models.PROTECT, related_name='organizer', blank=True) participants = models.ManyToManyField(User, blank=True, related_name='events_by_participant') creation_datetime = models.DateTimeField(auto_now_add=True, editable=False) update_datetime = models.DateTimeField(auto_now=True) And my Query object looks like this: class Query(graphene.ObjectType): events_by_organizer = graphene.List(EventType, id = graphene.ID(required=True)) def resolve_events_by_organizer(root, info, id): try: return Event.objects.filter(organizer=id).order_by('-event_datetime') except Event.DoesNotExist: return None In graphQL I get events query without sorting by event_datetime. How can I sort query in Django-graphene? -
How to fix django.db.utils.OperationalError: (1046, 'No database selected')
I have a column problem in the database when the yak uses python manage.py migrate. I want to write code to use DATABASE_URL in docker-compose.yml, how should I solve it? I've experimented with writing these codes. Can you advise me a bit? mysql> show databases; +--------------------+ | Database | +--------------------+ | DatabaseUBU | | information_schema | | mariadb | | mydb | | mysql | | performance_schema | | sys | +--------------------+ 7 rows in set (0.02 sec) mysql> create database mariadb; ERROR 1007 (HY000): Can't create database 'mariadb'; database exists docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db volumes: mysqldata: setting.py import dj_database_url import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', **dj_database_url.config(default=os.environ.get('DATABASE_URL')) } } -
How to write to Django FileField from a tempfile?
I am processing an image within a Django app. I used rasterio to process the geospatial image. I want to save the output directly to a FileField in a Model. I used a tempfile to write the output from rasterio, and used the method Model.FileField.save to hopefully write it with a reference to my Model instance. I have a simple model: class MaskedLayer(models.Model): name = models.CharField(max_length=250, blank=True) file = models.FileField( upload_to='masked', null=True, max_length=500) In my tasks, however this is an example: from celery import shared_task import rasterio import tempfile from app.models import MaskedLayer @shared_task def process_image(): mask_layer_name = 'processed_image.tif' masked_layer = MaskedLayer.objects.create() with rasterio.open('example.tif') as dataset: # only example of reading/processing of image out_image = dataset.read() with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(out_image) with rasterio.open(tmpfile.name) as dataset: masked_layer.file.save(mask_layer_name, File(dataset)) pass I get this response. I am not sure of the error. Feel free to use the example file. Fatal Python error: Segmentation fault Current thread 0x00007f453b463740 (most recent call first): File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 232 in get_traceback_frame_variables File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 544 in get_exception_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 490 in get_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 320 in get_traceback_data File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 403 in get_traceback_text File "/usr/local/lib/python3.11/site-packages/django/utils/log.py", line 125 in emit File "/usr/local/lib/python3.11/logging/init.py", line 978 in handle … -
VS Code + Pylance does not find venv-installed modules while venv is activated
I use VS Code Version: 1.74.3 on MacOS 13.2. python -V returns Python 3.11.1. I get the following error message: Import "django.shortcuts" could not be resolved from source Pylance(reportMissingModuleScource). As you can see in the screenshot, the correct venv is activated and includes Django. I checked also these threads: Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10 and https://stackoverflow.com/a/65802367/2321643 but the suggested solution with reloading the windows did not help. Using Debug I can safely run my Django-application without any import issues. What do I need to do that Pylance does not issues these problems? -
Override response in Django Rest Framework serializer
I have a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name') And view: class UserListView(ListAPIView): model = User serializer_class = UserSerializer And as expected on a GET request i get a response like [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", } ] What should i change to get response like this: [ 'users': [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", }] ] I think it's easy, but can't understand how.