Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Visual Studio Code - Python Interpreter path does not work for me
as i already tried for hours by myself, i could not find out, what i am doing wrong. I am doing the Tutorial of Django on Youtube, which can be found on the following URL: https://www.youtube.com/watch?v=rHux0gMZ3Eg After craeting a virtual environment and starting a project in Virtual Studio Code, he tries to add the python path into the VSCode. In the video he is then able to use Python from the terminal inside the VSCode. However, around minute 19 you can find that in the video. If i do it by myself, nothing is happenning and i am also not able to use Python on the VSCode then. I did not figure out, what i am doing wrong, since i am exactly doing it like in the video. Does anyone have an idea, what i am doing wrong here? Thanks to anyone having an idea. Here are screenshots of what i have done for adding the path. enter image description here enter image description here enter image description here -
NOT NULL constraint failed: products_product.vendor_id django
so i recently changed my project user form to abstract base user and well my users can not add products or view their profile i know its problem in views.py and forms.py but whatever i change it too still has some probelm beside the error views.py rom django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserChangeForm from django.utils.text import slugify from django.shortcuts import render, redirect from .models import NewUser from products.models import Product from .forms import ProductForm from .forms import UserCreationForm # Create your views here. def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = NewUser.objects.create(user_name=user.first_name) return redirect('home') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required def vendor_admin(request): context = { 'user':request.user } vendor = request.user.user_name return render(request,'vendor/vendor_admin.html',{'vendor': vendor ,'context':context}) @login_required def add_house(request): if request.method == 'POST': form = ProductForm (request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) NewUser.user_name = request.user.user_name product.slug = slugify(product.عنوان) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request,'vendor/add_house.html',{'form': form}) class UserEditView(generic.UpdateView): models = NewUser form_class = UserChangeForm template_name = 'vendor/edit_profile.html' seccess_url = reverse_lazy('vendor_admin') def get_object(self): return self.request.user forms.py rom django.forms import ModelForm from products.models import Product from django import forms from django.contrib.auth.models import … -
Django: why does my custom filter not find an existing item in the array?
I am a beginner in Django. Right now i am working on my first project: reservation of sits for cinema event. The html map of sits is based on the array of cols and rows, provided from the Hall model. There is also an Invoice model, which stores the information about reserved places, based on this event. Based on this, i am trying to disable the html-map checkboxes of the sit places, which are already reserved. Here is my code: views.py def event_map(request, slug, event_id): selected_event = Event.objects.get(pk=event_id) movie = selected_event.film hall = selected_event.hall time = selected_event.get_time_slot_display() date_event = selected_event.get_week_day_display() sits = list(range(0, hall.hall_sits)) cols = list(range(0, hall.hall_cols)) hall_information = generate_hall_information(hall.hall_name) reserved_places = list() invoices = Invoice.objects.all().filter(event=selected_event) for invoice in invoices: reserved_places += invoice.invoice_details.split(',') reservation_form = Reservation() if request.method == 'POST': print(request.POST) form = Reservation(request.POST) if form.is_valid(): post = form.save(commit=False) post.invoice = request.user post.event = selected_event post.save() return render(request, 'pages/event_map.html', { 'movie_name': movie.name, 'hall': hall, 'time': time, 'date': date_event, 'sits': sits, 'cols': cols, 'hall_information': hall_information, 'reservation_form': reservation_form, 'reserved_places': reserved_places, 'test': reserved_places }) event-map.html <div class="theatre-map event-map-grid hall-{{ hall }}" id="theatre-map-target"> {% for sit in sits %} {% if sit|if_in_list:reserved_places %} <label class="res" id="{{ sit }}" disabled=""></label> {% else %} <label … -
Django - My list coming from a form collapses to a string when i call it
when i print the full request body its a list but when i reference it turns into a string with just the first value in the list def create_quiz_post(request): if request.method == 'POST': quiz = Quiz.objects.create(name=request.POST['name'], creator=request.user) Quiz.objects.get(id=quiz.id).topic.add(request.POST['topic_id']) print(request.POST) print(request.POST['question']) return redirect('/') OUTPUT 1 <QueryDict: {'name': ['2'], 'question': ['2', '2'], 'option1': ['', ''], 'option2': ['', ''], 'option3': ['', ''], 'option4': ['', ''], 'topic_id': ['1']}> OUTPUT 2 2 -
Celery in docker container first works for a while, then starts to timeout
Deploying the project, everything works. After an indefinite time, celery stops responding. Getting a gunicorn error: sys.exit(1) Tried run task.deploy() inside the django container and nothing happens in the celery container. There are no errors in the logs either in django container or in celery container. If I restart the Celery container, then everything works again for a while, then it starts timeout again. Docker containers: - django - celery - celerybeat django settings celery settings: CELERY_BROKER_URL = REDIS_URL CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py in django project: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YoungAI.settings') app = celery.Celery('YoungAI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() docker-compose: version: '3' services: redis: container_name: redis image: redis:4.0.2 restart: always networks: - youngai youngai-nginx: container_name: youngai-nginx image: youngai-nginx build: conf/nginx/ restart: always networks: - youngai - third_party_backend youngai-backend: container_name: youngai-backend image: $CONTAINER_BUILD_IMAGE restart: always env_file: /opt/.env-youngai build: . command: ./docker-entrypoint.sh volumes: networks: - youngai - third_party_backend youngai-celery: container_name: youngai-celery image: $CONTAINER_BUILD_IMAGE restart: always … -
Django - Href not redirecting user but being loaded locally
I am creating a simple application in django. I have an element, and when the user clicks on it, I want to be able to redirect them to a new page (classes.html). I used href="{% url 'classes' %}", but when the user clicks on it, nothing happens. However, I can see that the url has been loaded because the tag at the bottom screen loads the URL. Additionally, when I go to inspect the , I see that the URL has been loaded and when I click on it, it takes me to the classes URL. Can someone please help me so that when the user clicks on the , it redirects them to the classes screen? I have tried conducting a hard reload, re doing my URLS and views, and setting up a virtual enviorment, but nothing seems to work. -
django How do I solve a: NOT NULL constraint failed: accounts_user.group error?
Hi all I'm struggling to diagnose this error. I have looked through similar questions, however their's seem to be specific to ID's names etc. Im trying to create a new user when they fill out a register form. However when the form is submitted I get the following: " NOT NULL constraint failed: accounts_user.group " My code and the exact error i get is below, any help will be appreciated Form.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from .models import EmailActivation, GuestEmail, User User = get_user_model() class RegisterForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name','email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals if commit: user.save() return user Models.py from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.db … -
Django profile not being updated
Enabling my users to update their profile information. However, when I send new profile information, Django sends my back the profile information I had prior to updating. Simply put I would to receive updated profile information when I update a user profile along with a new access_token (I use the information to populate my profile). This is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() return instance urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), and my views.py: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['PUT']) def perform_update(self, serializer, pk=None): serializer.save(user=self.request.user.id) -
PAGINATION using class APIView in Django Rest Framework
I have try to paginate my data.. but this is not work , I'm still getting all data from DataBase this is views.py : class User_apiView(APIView): pagination_class=PageNumberPagination def get(self, request): user = User.objects.all() # pagination_class=PageNumberPagination serializer = TripSerializer(user, many = True) return Response(serializer.data) this is settings.py : REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } this the data I recieve in this url http://127.0.0.1:8000/api/users/?PAGE=4&PAGE_SIZE=1 HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, ] -
How i can ouput categiries in django on dpopdown in navbar?
Views, functions from categories def get_categories(request, cat_id): product = Product.objects.filter(cat_id=cat_id) cats = Category.objects.all() if len(product) == 0: raise Http404() context = { 'product': product, 'cats': cats, 'menu': menu, 'title': 'Отображение по категориям', 'cat_selected': cat_id, } return render(request, 'task1/get_category.html', context=context) Models with get_absolute_url class Category(models.Model): name = models.CharField(max_length=255, verbose_name='Категории') slug = models.SlugField(max_length=255, unique=True, verbose_name='URL', db_index=True) class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('сategory', kwargs={'cat_id': self.pk}) Urls.py path('category/', get_categories, name='category'), This is piece of code from base.html. Dpodown from navbar. <div class="collapse navbar-collapse" id="navbarNavDarkDropdown"> {% for c in cats %} <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Категории </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink"> <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> {% else %} <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> </ul> {% endif %} </li> </ul> {% endfor %} </div> I'm really idk what to do, help me please I've tried, but i get mistake Navbar looks like, i have 4 categories and i get 4 columns in navbar -
How to make Whitelisted IPs won't be blocked and other IPs should be blocked if crosses the certain time in django rate limited?
@method_decorator(ratelimit(key='ip', rate='10/m', block=True), name="process_request") Class SomeMiddleware (object): def process_request(request): Pass I have ALLOWED_IPS = ["SOME IP"] in settings.py and i imported here. If any IPs matching with this list, they won't be blocked under this condition otherwise it does. How can I achieve this? -
Get username of authenticated user in middleware [Djoser] Django
Im using django with rest framework and djoser. I have a code to check the latest activity on the website. But i have problem to get username of authenticated user. request.user.is_authenticated always return false. On frontend i have vue. p.s When i login to admin panel of 127.0.0.1:8000 show "true" from django.utils import timezone from .models import CustomUser class UpdateLastActivityMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') print(CustomUser.objects.filter(is_online=True)) print(request.user.is_authenticated) if request.user.is_authenticated: CustomUser.objects.filter(user__id=request.user.id) \ .update(last_online_at=timezone.now()) -
django-social-auth redirect to different url based on params
I am using social-auth-app-django to enable OAuth2 from google. My application has two types of users and both are given an option to use google auth. Now after these users register using google, I want to redirect to some page where they add additional information based on the type of user. I am not able to figure out a way how to identify them based on the type of user. I am looking for a way where I can send extra parameter to google and then google return that parameter. This way I can identify the user type. I am simply providing the following in django template. <a href="{% url "social:begin" "google-oauth2" %}"><button>Google</button></a> Edit: One way I am thinking is of having two redirect URL configured in google. Then I can simply add function for these two redirect URL and my problem will be solved. I am not able to figure out how to add that redirect URL in the request to google. -
"Cannot call delete() after .distinct()" error after django update
I am using djangocms_blog. Today I updated django from 3.1 to 3.2.12 and suddenly when I try to delete post object, there is "Cannot call delete() after .distinct()" error Traceback: env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … env\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\views\decorators\cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\sites.py, line 232, in inner return view(request, *args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 1739, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) … env\lib\site-packages\django\contrib\admin\options.py, line 1408, in response_action response = func(self, request, queryset) … env\lib\site-packages\django\contrib\admin\actions.py, line 45, in delete_selected modeladmin.delete_queryset(request, queryset) … env\lib\site-packages\django\contrib\admin\options.py, line 1109, in delete_queryset queryset.delete() … env\lib\site-packages\django\db\models\query.py, line 728, in delete raise TypeError('Cannot call delete() after .distinct().') … I restored Django 3.1 version and everything works fine, but working on old version isn't best solution -
How to make Django username field of LoginView(FormView) lowercase?
I've made it so that any user that signs up with a username will automatically have their username converted to lowercase. user/forms.py I now have the issue where I can't figure a way to convert the username in the login form to become lower when submitted. As I would still like the user to be able to enter their name in the case of their choice. I've tried the python tolower() function on a few things in the LoginView, yet unsuccessful. If anyone has an idea on how I could achieve this please let me know. Here is the user/forms.py class UserSignupForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] def clean_username(self): username = self.cleaned_data["username"].lower() if not re.match(r"^[A-Za-z0-9_]+$", username): raise forms.ValidationError( "Sorry , you can only have alphanumeric, _ or - in username" ) else: return username Here is the user/urls.py path("signup/", user_view.signup, name="signup"), path("login/",auth_view.LoginView.as_view(template_name="user/login.html"),name="login"), -
Form action is not calling the required function from views.py in Django
I am new in Django and doing my first project in it. I had made a form in my index.html file and that form took an image, and sent it to a predictImage function in views.py file. The predictImage function applied YOLO model on the image and returned the image with labels to the same index.html page. This was working fine and I was getting the required results. After the submit button was clicked, I was getting redirected to index.html/predictImage where the results were being shown. (I had conditions added in my index.html to show the results) Then, I decided to add a Users Model and made a Login page for me, user was required to login before he could upload the image. For this, I added sessions as well. Now, I created a Photo model, to store every photo that every user uploads. All of this was successfully made but now, when I tried to do the same thing again, i.e., upload the image and submit it, it didn't work and it instead redirected me to index.html I tried to debug this, and I found out that I was not even going to views.predictImage when I clicked the submit … -
What is the easiest way to create a histogram (with target line) in Chart.js?
I have a matplotlib code that seems to do what I want it to do. I am trying to use it in a django web app. For example: home_totals_dict[a] = [ 140, 130, 120, ...] a = team_name plt.figure() plt.hist(x=home_totals_dict[a], bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5) plt.hist(x=away_totals_dict[b], bins='auto', color='#d62728',alpha=0.7, rwidth=0.5) plt.axvline(x = c, color = "k",linestyle = "--" ) plt.xlabel(a + "/ "+ b) The result is the image attached. Every time I try do something similar in chart.js the x axis gets all messed up and am having trouble normalizing the x-axis prior to adding the data to chart.js -
Serializer returns media files URLs in http not in https in Django Rest Framework
I'm trying to serialize a model and one of its fields is a FileField when calling serialiser.data it returns the URL of the FileField in an HTTP schema, not an HTTPS. I get { "id": 1, "name": "demo", "file": "http://domain-name.com/media/image.png" } I want it to be { "id": 1, "name": "demo", "file": "https://domain-name.com/media/image.png" } I'm using Nginx and set proxy_set_header X-Forwarded-Proto https; Then in your Django settings added the following: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') And the problem is not fixed, what should I do to solve it? -
send_mail (smtp) from docker-compose (django + nginx + gunicorn)
I am trying to send email via Django. The mail should be sent to the user who would register to our system using Gmail. I am also using docker-compse django, nginx, gunicorn and postgres. This is my email configurations inside the django. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and docker-compose version: '3.7' services: web: build: context: ./dj-psych dockerfile: Dockerfile.prod command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static/ - media_volume:/home/app/web/media/ expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/static - media_volume:/home/app/static ports: - server-port:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: nginx.conf upstream config { server web:8000; } server { listen 80; location / { proxy_pass http://config; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/static/; } location /media/ { alias /home/app/media/; } } I think the smtp server port (586) should be open in docker. So I tried binding port web and nginx. But I can't. how can i do it?? I tried. from django.core.mail import EmailMessage email = EmailMessage('subject', 'body', to=['yj.jeon.gn@gmail.com']) email.send() This is … -
Django: Cannot filter against a non-conditional expression during trying to relate every values written to the current user
I want to relate every values written to the current user ,( the story that i want to print some fields of a form) and am afraid in case more than 1 user logged in the same time and want to generate a pdf, both of them print the same last -values entered in the printout. So i want to filter the values of fields based on the current user logged in with session. First Step: I have add another class in models.py models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) Second Step: in views.py:(the function that is responsible for generating the pdf) , I have coded like that: def forms_render_pdf_view(request, *args, **kwargs): template_path = 'pdf.html' user = request.user user_sessions = UserSession.objects.filter(user = user) field_name = 'emploi' obj_m = Loads.objects.filter(user_sessions).last() field_obj_m = Loads._meta.get_field(field_name) field_value_m = field_obj_m.value_from_object(obj_m) emploi = str(field_value_m) when i try to generate my printout it gives me: Cannot filter against a non-conditional expression. Thanks in advance, How i can relate every values written to the current user correcly . -
Adding an object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post model has a manytomany field to User model. I try to add a user object to the field with the view function below but it doesn't work. When I check the post in the admin page, the user is not added to the likers. @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) I make the request in javascript in this way: fetch(`likepost/${likeValue}/${postId}`, { method: 'PUT' }); -
Python Django django-admin startproject admin problem
I am facing problem when I start making project via Django.....Whenever I cammand in CMD "django-admin startproject clone" It request for USER/ADMIN--- and I forget...That thing please that what to do try to help me...whenever I try to give something in input field it show me an error... After 1year I am switching in Django...It soo me some file which was on my Desktop that time...Please try to Help me...... [Output[\]\[1\]][1] --Shadab -
Basename attribute in the same routes
relatively speaking, I have two simple models: Processor and Motherboard. class Processor(Product): supply_type = models.CharField(max_length=10) socket = models.CharField(max_length=20) cores_amount = models.IntegerField() threads_amount = models.IntegerField() technological_process = models.IntegerField() class Motherboard(Product): socket = models.CharField(max_length=20) ram_generation = models.CharField(max_length=10) ram_type = models.CharField(max_length=10) ram_slots_amount = models.IntegerField() There are also corresponding serializers written for them. class ProcessorSerializer(ModelSerializer): class Meta: model = Processor fields = '__all__' class MotherboardSerializer(ModelSerializer): class Meta: model = Motherboard fields = '__all__' And of course viewsets. class ProcessorViewSet(ModelViewSet): queryset = Processor.objects.filter(is_published=True) serializer_class = ProcessorSerializer lookup_field = 'slug' class MotherboardViewSet(ModelViewSet): queryset = Motherboard.objects.filter(is_published=True) serializer_class = MotherboardSerializer lookup_field = 'slug' SimpleRouter was created in urls, where the following routes were added. router = routers.SimpleRouter() router.register(r'processors', ProcessorViewSet) router.register(r'motherboards', MotherboardSerializer) When I try to make a migration I get the following error: router.register(r'motherboards', MotherboardSerializer) assert queryset is not None, 'basename argument not specified, and could ' AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. I tried to add this attribute, however, an error appears that the get_extra_actions method is not defined. I have three old models added in the same way. The problem appeared precisely when adding new models and routes for … -
Weasyprint how fix html/css that come from email
Weasyprint generate pdfs from emails. Sometimes emails come with some html/css in it. I add example from pdf from paypal in which all pdf in html/css information. Or Microsoft default mail also use some html when send emails. Is it possible to add some default things to fix html/css in a right way? My code: filename = f'{uuid.uuid4()}.pdf' data = {"body": content} context = Context(data) template = Template('{{ body|linebreaks|safe }}') html_string = template.render(context) html = HTML(string=html_string) pdf = html.write_pdf() Some example from paypal email that come <html dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0,minimum- scale=1.0,maximum-scale=1.0,width=device-width,height=device- height,target-densitydpi=device-dpi,user-scalable=no" /> <title>Confirm your new email address</title> <style type="text/css"> /** * PayPal Fonts */ @font-face { font-family: PayPal-Sans; font-style: normal; font-weight: 400; src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui- web/paypal-sans-small/1-0-0/PayPalSansSmall-Regular.eot'); /* IE9 Compat Modes */ src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff2') format('woff2'), /* Moderner Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff') format('woff'), /* Modern Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.svg#69ac2c9fc1e0803e59e06e93859bed03') format('svg'); /* Legacy iOS */ /* Fallback font for - MS Outlook older versions (2007,13, 16)*/ mso-font-alt: 'Calibri'; } -
how can i use audio file in pydub through django
Well, i have a code that creates and saves audio and i need to instert in that code a silence cutting system views.py def audio(request): if request.method == 'POST': cu = request.user.customer.pk users = get_object_or_404(Customer, pk=cu) js = get_object_or_404(JsonMap, user_id=users.id) audio = request.FILES['data'] name = audio.name name = name.replace(':', '-') song = Song.objects.create() audio_cut_logic = SoundCutter() song.js = js song.name = name song.audio_file = audio song.save() return render(request, 'action.html', {'file_url': js}) models.py def remove_sil(self, file, format="wav"): sound = AudioSegment.from_file(file, format=format) non_sil_times = detect_nonsilent(sound, min_silence_len=50, silence_thresh=sound.dBFS * 1.5) if len(non_sil_times) > 0: non_sil_times_concat = [non_sil_times[0]] if len(non_sil_times) > 1: for t in non_sil_times[1:]: if t[0] - non_sil_times_concat[-1][-1] < 200: non_sil_times_concat[-1][-1] = t[1] else: non_sil_times_concat.append(t) non_sil_times = [t for t in non_sil_times_concat if t[1] - t[0] > 350] return sound[non_sil_times[0][0]: non_sil_times[-1][1]] i tried to create sound.audio_file through my function song.audio_file = audio_cut_logic.remove_sil(audio) then i tought i need to create that audio file firstly and then use my func song.audio_file = audio song.audio_file = audio_cut_logic.remove_sil(song.audiofile) but all i got is: AttributeError: 'AudioSegment' object has no attribute '_committed'