Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin cannot set form dynamically
I'm trying to set form fields dynamically and access it in admin.py in get_forms method, but unfortunately, dynamic data is not there. It seems like forms __init__ is being called after the get_form itself. Which would appropriate method in Django admin to retrieve already updated form fields? Here is simple example forms.py class MyForm(admin.ModelForm): title = forms.CharField(widget=forms.TextArea()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.update({ 'some_field': forms.CharField(widget=forms.TextArea()) }) admin.py class AccountAdmin(admin.ModelAdmin): def get_form(self, request, **kwargs): form = super().get_form(request, obj, **kwargs) print(form.base_fields) return form -
how not to increase view count when someone sending more than one GET request
i am trying to count view of blog posts. here is my models.py class Blog(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='post_author') blog_title=models.CharField(max_length=264,verbose_name='Put a Title') category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='category',default=None) slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True) blog_content=models.TextField(verbose_name='what is on your mind?') blog_image=models.ImageField(upload_to='blog_images',verbose_name='Image') publish_date=models.DateTimeField(auto_now_add=True) update_date=models.DateTimeField(auto_now=True) view_count=models.IntegerField(null=True,default=0,blank=True) class Meta: ordering = ('-publish_date',) here's how i am increasing the view count of a post for every GET request def blog_details(request, slug): blog = Blog.objects.get(slug=slug) if request.method == 'GET': blog.view_count =blog.view_count+1 blog.save() *skipping giving the whole(irrelevant to the question) code of the function* Now how can i increase view count of a post for the first GET request from a user(registered or anonymous) by 1. If they send more get request view count would not be increased. Pardom mistake and THANK YOU in advance -
Django admin give user permission on some records and linked foreign key records
In Django Admin Dashboard, I have to give access to a particular client such that he can view all related cases. But not all cases. In other words, give a user access control to some of the records and foreign key records. But not all. What is the easiest way in Django? class Client(models.Model): name = models.CharField(max_length=200) class Case(models.Model): client_name = models.ForeignKey(Client, on_delete=models.SET_NULL) name = models.CharField(max_length=200) -
how to click on a row in html table to open a page to edit that row's content
in my html code Ive created a table, I want to click on row specifically the id cell for it to direct me to my edit page in my views.py file. Im very new to django and im not sure how to go about this. please let me know. -
Show field many to many in django admin panel
I use this functions (cedi) but dont work.I want to show field nombre of Cedi model in panel admin of Campania model. The name of the column appear but the info or every instance doesn´t. @admin.register(Campania) class CampaniaAdmin(ImportExportMixin, admin.ModelAdmin): # conecta con CampaniaResource resource_class = CampaniaResource list_display = ('nombre', 'descripcion', 'cedi') list_filter = ('nombre', ) readonly_fields = ('fecha_creacion', 'fecha_modificacion') search_fields = ['nombre',] def cedi(self, obj): return ", ".join([i.nombre for i in obj.cedis.all()]) models class Campania(models.Model): nombre = models.CharField(verbose_name='campaña', max_length=200, primary_key=True) fecha_creacion = models.DateTimeField(auto_now_add=True) fecha_modificacion = models.DateTimeField(auto_now=True) descripcion = models.TextField() # campo manytomany cedis = models.ManyToManyField(Cedi) def __str__(self): return self.nombre class Cedi(models.Model): nombre = models.CharField(max_length=200, primary_key=True) fecha_creacion = models.DateTimeField(auto_now_add=True) fecha_modificacion = models.DateTimeField(auto_now=True) # campo ForeignKey pais = models.ForeignKey(Pais, on_delete=models.CASCADE) def __str__(self): return self.nombre -
CSRF 403 in default Django login
I'm fairly new to Django. Here's what I need insight on: After updating from Django 3 to 4: On the local dev server, no issue. On production: CSRF 403 error on login. There's a cookie loaded on the login page containing csrftoken: pAFeeUI8YFXZ2PKRYxOTX1qz4Xgto42WVNi7FFvBlZDqcFLwQ2rdQvVeZBHFSpLW (Local and Session storage are empty) In the FORM element: <input type="hidden" name="csrfmiddlewaretoken" value="Vz4FiujD4qkLpxCwWNJU0HCWs4u0Qf4RrMHyJf66rK0cznDbOimeTb7BnIVckANR"> Notice they don't match. I tried manually deleting the cookie and also running ./migrate.py clearsessions. The first time, yesterday, it seemed that the error did not occur in an Incognito Window, but today it persists even in an incognito window, as well as a different browser. One additional piece of information allauth had been previously installed, but was causing infinite redirect loop on login, so removed. The login page url is /login/?next=/. Thanks much. -
How to trigger Django signal when using flush?
I'm using redis for caching data on my project and delete the cache through the signal. Whenever there is a change on my database the signal clear the cache using the key provided as follow @receiver(post_save, sender=Book) def cache_clean_books(sender, instance, created, **kwargs): if created: cache.delete("all_books") else: cache.delete(f'book_id_{instance.id}') Everything is working fine from here but when I use python manage.py flush to clear data from the database my signal is not triggered. Is there any way I can use to hit the signal whenever I flush data in django please? -
python recursive key and value find on condition
I have written this function to find key @type of a specific value. I mean, I want to get all the objects who have key @type of specific value. the objects is very nested. and the key is @type is duplicate, it can be found many place, I guess that is why it is not working: def recurseitem(obj, value): if '@type' in obj: if obj['@type'] in value: return obj for k, v in obj.items(): if isinstance(v,dict): return recurseitem(v, value) and processing data here def get_results(data): # data = [] results = {} valuetype_to_find = { 'product': ['product', 'Product', 'car', 'Car'], 'AutoDealer': ['AutoDealer'], 'PostalAddress': ['PostalAddress'], 'offer': ['Offer', 'offer', 'Offer',] } for vk, vt in valuetype_to_find.items(): results[vk] = recurseitem(data, vt) or {} return results I am expecting get_results should return data like this: { 'product': {..all the product key from data.....} 'AutoDealer': {...all the AutoDealer..data.....} 'PostalAddress': {...all the postal address data.......} 'offer': {...all the offer data.......} } But unfortunately it is not working, I am not sure what's wrong with this. it should work well but not working ! here you go for example data data = { "@context":"https://schema.org", "@type":"Product", "additionalType":"http://www.pr.org/id/Car", "name":"2022 Honda Ridgeline RTL AWD", "description":"Sunroof, HPlease confirm the accuracy of … -
In my project, there are list of information stored under different category. How do I make each category render only what is saved under it
models.py from django.db import models Create your models here. class Category(models.Model): title = models.CharField(max_length=225) class Meta: verbose_name_plural = 'categories' class Contact(models.Model): category = models.ForeignKey(Category, related_name='contacts', on_delete=models.CASCADE) first_name = models.CharField(max_length=225) last_name = models.CharField(max_length=225) email = models.EmailField() phone = models.CharField(max_length=225) address = models.CharField(max_length=225) zipcode = models.CharField(max_length=225) city = models.CharField(max_length=225) image = models.ImageField(upload_to='uploads/', blank=True, null=True) class Meta: ordering =('first_name',) views.py def detail(request): contacts = get_list_or_404(Contact) if request.method == 'GET': return render(request, 'contact/detail.html', {'contacts': contacts}) -
AttributeError: 'name_Funcition/task' object has no attribute 'GET' - Django, Celery + RabbitMQ
I'm starting Celery+RabbitMQ to use async functions on my Django system and I'm facing some issues. As I understand it, when using Celery+RabbitMQ, the function that I insert in my tasks.py file will be executed "outside" my Django system, and I believe that I am not able to use/separate it all correctly. I organized my project as follows: settings.py CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' project/init.py from .celery import app as celery_app __all__ = ('celery_app',) projetec/celery.py from __future__ import absolute_import from django.conf import settings import os from celery import Celery # Defina o módulo de configurações padrão do Django para o programa 'celery' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery( 'proj', broker='amqp://guest:guest@localhost:5672//', backend='rpc://', include=['app.tasks'] ) # Startando o app config if __name__ == '__main__': app.start() # Usar uma string aqui significa que o trabalhador não precisa serializar # o objeto de configuração para processos filhos # - namespace='CELERY' significa todas as chaves de configuração relacionadas ao celery # deve ter um prefixo `CELERY_`. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app/tasks.py @shared_task( bind=True, # Chama funções do celery max_retry=3, # Maximo de tentativas de execução default_retry_delay=20, # Tempo entre as … -
How to render value stored in Django Model to Template (xxxxxx.html)?
In Django database, the field "sex" was properly record. However, when render in template (xxxxxx.html), it always shows the FIRST option, instead of showing the value recorded in Model. This problem happens only for tag; if using tag, it shows correct database value. How to fix it? Thanks. -
Django ORM query performance
I am trying to find best the django query for my django app. I am using default sqlite DB as backend. I am using timeit to find time taken for query. >>> import timeit >>> >>> setup_arg = 'from .models import AwsConsoleAccess' >>> stmt1 = """AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785')""" >>> stmt2 = """AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').values('status')""" >>> >>> >>> print(timeit.timeit(setup=setup_arg, stmt=stmt1, number=100) * 1000, 'ms') 7.873513997765258 ms >>> print(timeit.timeit(setup=setup_arg, stmt=stmt2, number=100) * 1000, 'ms') 11.816384001576807 ms SQL query executed >>> print(AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').query) SELECT "aws_console_awsconsoleaccess"."created",.....(all fields) FROM "aws_console_awsconsoleaccess" WHERE "aws_console_awsconsoleaccess"."request_id" = 8548a2d54bb74fa9add2a41219dc8785 >>> print(AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').values('status').query) SELECT "aws_console_awsconsoleaccess"."status" FROM "aws_console_awsconsoleaccess" WHERE "aws_console_awsconsoleaccess"."request_id" = 8548a2d54bb74fa9add2a41219dc8785 In theory select field from table should run faster than select * from table but my result are not reflecting it. Did I do my testing properly? Is there any other way to test the performance between two queries in DJango ORM? -
DJANGO4: names_to_path raise FieldError "Cannot resolve keyword '%s' into field. " Why does django cant resolve the keyword 'fatura'?
DJANGO: names_to_path raise FieldError "Cannot resolve keyword '%s' into field. " I want to return a queryset with all related records. Something like this: r = Repasse.objects.filter(fatura__id = 9) But I get an error... django seems not to be able to resolve 'fatura': names_to_path raise FieldError "Cannot resolve keyword '%s' into field. " So I've tryed this raw query: r = Repasse.objects.raw('SELECT * FROM imob_repasse INNER JOIN imob_fatura ON imob_repasse.id_fatura_id = imob_fatura.id ') It returns exacly what I am looking for, returns all Repasse joined with Fatura. Can't see what is wrong. Models are set as this: class Fatura(models.Model): datavencimento = models.DateField(null=True, blank=True) valorfaturado = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True) class Repasse(models.Model): id_contrato = models.ForeignKey(Contrato, on_delete=models.SET_NULL, blank=True, null=True) ##RELATIONSHIP## id_fatura = models.OneToOneField(Fatura, on_delete=models.SET_NULL, null=True, blank=True) ##RELATIONSHIP## valorrepasse = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True) Can't see what is wrong. I beleave raw SQL woud be brute force...Could it be any setup wrong? Why does django cant resolve the keyword 'fatura' ? -
How to override the behavior of "View on site" button in admin panel?
#model class Example(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, blank=True) def __str__(self) -> str: return self.name def get_absolute_url(self): return '/example/{}/'.format(self.slug) The default behavior of "view on site" button is to open the page in the same tab and under same domain. What I want is to open the page in new tab and under another domain, because the domain of django site is admin.domain.com and the main site is domain.com. I want it to redirect to the domain.com. I can do this: from core.settings import BASE_URL # BASE_URL = 'domain.com' #model class Example(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, blank=True) def __str__(self) -> str: return self.name def get_absolute_url(self): return '{}/example/{}/'.format(BASE_URL, self.slug) But there are many such models. Another option is to override the method used for resolving the model and object. #orignal path( "r/<int:content_type_id>/<path:object_id>/", wrap(contenttype_views.shortcut), name="view_on_site", ), #override path( "r/<int:content_type_id>/<path:object_id>/", wrap(customized_shortcut), name="view_on_site", ), Yet, the target _blank is remaining to be solved. Is there any built-in way to deal with this? And what else could be done? -
How to make a range datetime filter in django orm?
There is a function that gets the date, I need to filter the model by the date that is between date_start and date_end. I tried using gte/lte/range[] but it doesn't work correctly. Model: class ModeratorAbsent(models.Model): created_by = models.ForeignKey(User, models.SET_NULL, null=True) moderator = models.ForeignKey(Moderator, models.CASCADE) date_start = models.DateTimeField() date_end = models.DateTimeField() absent_type = models.ForeignKey(AbsentType, models.SET_NULL, null=True) deleted = models.BooleanField(default=False) class Meta: db_table = 'moderators_absent' default_permissions = () Custom function: def check_moderator_absent(self, moderator: Moderator, day: datetime, absent_types: [str]) -> bool: moderator_absents = ModeratorAbsent.objects.filter(moderator=moderator, absent_type__name__in=absent_types, deleted=False) if moderator_absents.exists(): return True return False Database data: db data Example: start = (day.combine(day.date(), day.min.time())) # 2022-03-16 00:00:00 end = (day.combine(day.date(), day.max.time())) # 2022-03-16 23:59:59.999999 moderator_absents = ModeratorAbsent.objects.filter(moderator=moderator, date_start__gte=start, date_end__lte=end, absent_type__name__in=absent_types, deleted=False) My version looks terrible: The function will accept different dates in the loop and I would like to filter the data by date right away, but now I have to get all the data from the model every time moderator_absents = ModeratorAbsent.objects.filter(moderator=moderator, absent_type__name__in=absent_types, deleted=False) for absent in moderator_absents: range_dates = map(lambda x: x.date(), self.__dates_service.create_days_from_range_dates(absent.date_start, absent.date_end)) if day.date() in range_dates: return True return False -
Default value in django models
I created a model with these feilds. I want to set the start_date and end_date to a default date whenever the attendance is registered however, when I migrate I get this error django.core.exceptions.ValidationError: ['“26/06/2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] the model in model.py class Attendance(models.Model): ATTENDANCE = ( ('absent', 'Absent'), ('present', 'Present') ) student_id = models.CharField(max_length=100, null=True) course_id = models.CharField(max_length=100, null=True) date = models.DateField(auto_now_add=True, null=True) time = models.TimeField(auto_now_add=True, null=True) attendanceState = models.CharField(max_length=20, null=True,choices=ATTENDANCE) start_date = models.DateField(default=2022-2-27) week_num = models.CharField(max_length=2, blank=True) end_date = models.DateField(default=2022-6-27) def __str__(self): return '{}'.format(self.student_id) def save(self, *args, **kwargs): #print(self.start_date.isocalendar()[1]) if self.week_num == "": self.week_num = self.start_date.isocalendar()[1] super().save(*args, **kwargs) -
Django: Downloaded image won't open
I am currently working on a Django app that allows me to download an image while only storing the image as a temporary file. While I am able to download the image, the file will not open. For example, Windows Photos says that "It appears we don't support this file format". Is there something wrong with the code that would cause this problem? Views.py def download_png(request, study): Names(study) #Function to retrieve (name) variable Retrieve(study) #Function to retrieve (data) variable BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pngfilename = str(name) + "_" + str(current_time) + ".png" filepath = BASE_DIR + '/polls/graphics/' + pngfilename temp, filepath = tempfile.mkstemp(suffix='.png') with open(temp, 'w') as f: f = df2img.plot_dataframe(data) df2img.save_dataframe(fig=f, filename=filepath) response = HttpResponse(temp, content_type=mimetypes.guess_type(filepath)) response['Content-Disposition'] = "attachment; filename=%s" % pngfilename return response -
Django Not Found: /polls/style.css how can i fix it?
hi i changed my code to style.css but the change site was not it confused me maybe i am doing something wrong look at my code below and draw your own conclusion, I hope for a good answer Console Log: PS C:\Users\kostia_admin\PycharmProjects\pythonProject32\mysite> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\kostia_admin\PycharmProjects\pythonProject32\mysite\static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). June 17, 2022 - 17:16:44 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [17/Jun/2022 17:16:46] "GET / HTTP/1.1" 200 3536 Not Found: /polls/static/polls/images/style.css [17/Jun/2022 17:16:46] "GET /polls/static/polls/images/style.css HTTP/1.1" 404 2895 Not Found: /polls/style.css [17/Jun/2022 17:16:46] "GET /polls/style.css HTTP/1.1" 404 2835 index.html(I think there's a mistake here. ): <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/static/polls/style.css"/> <link rel="stylesheet" href="/polls/style.css" type="text/css" /> <title>Shop</title> </head> <body> <header class="header"> <div class="header-content"> <div class="header-logo"> <h1 class="logo">SunRise Donate shop</h1> </div> <nav class="header-navigation"> <a href="https://sunmc.ru/">About</a> <a href="https://sunmc.ru/main/different/" class="link-button">Diferent<i class="material-icons-outlined"></i></a> </nav> </div> </header> <main> <div class="responsive-container"> <div class="grid"> <div class="grid-column"> <a class="product" href="#"> <div class="product-image"> <img src="https://reallyworld.ru/images/privileges/hero.webp" /> </div> <div class="product-content"> <div class="product-info"> <h2 class="product-title">HERO</h2> <p class="product-price">$ 5</p> </div> </div> </a> … -
Django fake model instanciation - No testunit
I want to know if I can **instanciate an empty fake model just with id of database record. I found way to create mockup model, but I want a production-friendly solution. Explanation of my issue : I want to list users settings for users who choose to be displayed on public mode : user_displayed_list = UserPublicProfile.objects.filter( displayed = True, ).only( 'user_id', 'is_premium', ) user_settings_list = [] for user_displayed in user_displayed_list: # I have to send user Instance to the next method : user_settings = self.get_user_settings(user_displayed.user) user_settings_list.append(user_settings) # But ’user_displayed.user’ run an new SQL query I know I can improve my queryset as : user_displayed_list = UserPublicProfile.objects.filter( displayed = True, ).select_related( 'user' ).only( 'user', 'is_premium', ) But It makes an useless join because I need only the user id field in get_user_settings(): The get_user_settings() method (it could help to understand context): def get_user_settings(self, user) user_settings = UserSettings.objects.get(user = user) return user_settings In real project, this method run more business feature Is there a way to instanciate a User model instance with only id field filled ? I don't want to use a custom empty class coded for this purpose. I really want an object User. I didn't find anything for that. … -
Authentication error 401 for jwt token in DRF tests
I have a problem getting jwt authorization for get method in test. my tests: lass ImageViewsTests(APITestCase): def setUp(self): self.test_user = User.objects.create_user(**TEST_USER) TEST_IMAGE['created_by'] = self.test_user self.temp_image = Image.objects.create(**TEST_IMAGE) self.token = RefreshToken.for_user(self.test_user) def test_images_list(self): url = reverse('jwt-create') client = APIClient() client.credentials(HTTP_AUTHORIZATION=f'JWT {self.token.access_token}') response = self.client.get('/image/', data={'format': 'json'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, TEST_IMAGE) Tests return AssertionError: 401 != 200. Token is returned correctly but does not work in header. For example everything is fine in Postman. postman you did something else like this and I also get no authorization def test_images_list(self): url = reverse('jwt-create') client = APIClient() resp = self.client.post(url, {'email':TEST_USER['email'], 'password':TEST_USER['password']}, format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) client.credentials(AUTHORIZATION=f'JWT {resp.data["access"]}') response = self.client.get('/image/', data={'format': 'json'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, TEST_IMAGE) Im using Djoser jwt DRF. Where am I making a mistake? -
Save list of forms Django
i've managed how to display a list of determined forms, without using formsets. But now i'm strugling to save the data from the form. This is my template: {% extends 'base.html' %} {% block main %} <div class="container"> <div class="container-form"> <form method="POST" enctype="multipart/form-data" action="{% url 'adjust_values' contract.id %}"> {% csrf_token %} {% for form in items_forms %} {{ form }} {% endfor %} <button type="submit" class="btn-confirm">Confirm</button> </form> </div> <div class="container-descript"> <h2 class="h2-containter">Adjust your prices!</h2> <img src="https://i.ibb.co/pX0bq35/Illustration.png" class="img-form"> </div> </div> {% endblock %} This is my views.py @login_required def adjust_values(request, id): contract = get_object_or_404(ClientContract.objects.filter(user=request.user), pk=id) contract_items = contract.items.all() items_forms = [] for item in contract_items: items_forms.append( ItemForm(request.POST or None, instance=item) ) my_forms = all([form.is_valid() for form in items_forms]) form = ItemForm() if my_forms and form.is_valid(): for form in items_forms: form.save(commit=False) form.save() else: print(form.errors) context = {'contract': contract, 'form':form, 'items_forms': items_forms} return render(request, 'item_formset.html', context) Now i really do not know what i need to do to save the data from the forms. Is there any way to save the data using this structure for iteration trough forms? -
Set the column collate directly from the django model field CharField
My tables default collate are utf8mb4_general_ci but sometimes I need only few columns to be utf8_general_ci. Is there a library or a workaround to set the db columns collate directly from the model fields like this: name = models.CharField(max_length=255, db_index=True, collate='utf8_general_ci') -
Anyone knows how to configure organization pages in richie lms?
I have configured successfully RICHIE LMS in my local machine successfully but it was showing me an error when I want to add any organization or course page in there. It was showing me "ypu have to create parent page and revese the parent page id to current page". Anyone configure richie in local machine?If so please help me with that.Thanks in advance. -
Show blogpost suitable to the current category
I want to filter my database based on the menuItem or category of my blog posts. With self.request.path I get something like '/py/' what represents one of my categories. By now I do this way and it works fine, but is there a better way? Should I create for each category a different app and write it's own IndexView with fix queryset filter? If there is a better solution to my problem than I would happy to know :) Here my CategoryIndexView: class CategoryIndexView(ListView): model = Post template_name = 'blog/category_index.html' # context_object_name = 'category' def get_queryset(self): category = self.request.path[1:-1] if category.lower() == 'ml': query_set = Post.objects.filter(category=0) elif category.lower() == 'py': query_set = Post.objects.filter(category=1) elif category.lower() == 'kt': query_set = Post.objects.filter(category=2) elif category.lower() == 'cpp': query_set = Post.objects.filter(category=3) else: query_set = Post.objects.filter(category=0) return query_set Here a snippet of my urlpatterns: urlpatterns = [ path('about/', genViews.about, name='about'), path('imprint/', genViews.imprint, name='imprint'), path('admin/', admin.site.urls), path('',genViews.HomeView.as_view(), name='home'), path('ml/',blogViews.CategoryIndexView.as_view(), name='machine_learning'), path('py/',blogViews.CategoryIndexView.as_view(), name='python'), path('kt/',blogViews.CategoryIndexView.as_view(), name='android'), path('cpp/',blogViews.CategoryIndexView.as_view(), name='cpp') ] -
Creating a printful order using the API with Django python
i am trying to create order with printful API, i don't understand where i am wrong. the error that comes out of me is: {"code":400,"result":"Invalid request: missing order element","error":{"reason":"BadRequest","message":"Invalid request: missing order element"}} this is the code, for those who have already integrated it what is the variant_id and how can I find it? Someone help me please import requests import json @login_required def test(request): # variabili per connessione token = "4XYO4WBEGWtpQoTtRBh1xF4ulQnt8dLKfyjXpxFt" url = "https://api.printful.com/" header = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'} # dati ordine payload = { "recipient": { "name": "John Smith", "address1": "Via milano 55", "city": "Arese", "state_name": "Milano", "country_code": "IT", "zip": "20020" }, "items": [ { "variant_id": 1, "name": "Digital Tech", "quantity": 1, "retail_price": "40.00", } ] } crea = requests.post(url + 'orders', params = payload, headers = header) ottieni = requests.get(url + 'store/products', headers = header) context = {'test': ottieni.json(), 'crea': crea.text} return render(request, 'test.html', context)