Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
a tag is not enter(Django)
I'm making website using Python Framework of 'Django'. I have some problems with Django about tags. If you click the Year-2021 a tag on the http://127.0.0.1:8000/blog/archive/ site, it will not enter the homepage. I'd like to know what's wrong and how to fix it. mysite/urls.py contains: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from bookmark.views import BookmarkListView, BookmarkDetailView urlpatterns = [ path('admin/', admin.site.urls), path('bookmark/', include('bookmark.urls')), path('blog/', include('blog.urls')), ] blog/urls.py contains: from django.urls import path, re_path from blog import views app_name='blog' urlpatterns=[ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(), name='post_month_archive'), # … -
How to leave content unaffected when changing pages Django
So I have a song player/bar that I want to implement into my Django project. It is a Django partial/template component that will give the user all the basic controls such as playing, pausing, volume, and skipping. When you changing pages and urls, obviously, everything in the HTML has to be re-rendered. This creates a problem for my music player since rendering would interrupt the processes of the music player (like playing music). What if there is a workaround to this? Where I can change pages without my player being affected and disrupted. I want my player to be similar to the players of Spotify or Soundcloud, where you literally have to exit the website or reload the page for the players to be interrupted. Thanks. -
Dealing with popups javascript and django
I'm currently struggling to deal with a javascript popup in django. That probably doesn't seem very clear! Let me illustrate. On the first image, i have a form to create a painting. However, i would like to add a new artist (an django model), and link that artist to the painting i'm trying to create. So, i created a popup, which can be seen on the second image. But when i hit the create button, not only does the popup not close, but after i closed it manually, i am forced to refresh the painting-form-page to see the newly created artist appear in the dropdown. First of all, do you see what i'm trying to do (sorry my english isn't very good :) ) ? Second, if you could give me some path to follow to build what i'm trying to do, that would be very much appreciated! Thank you very much! -
print nested inner data in python
I want to print the total_price data in this nested queryset. tried: print(data['quotes_description']['total_price']) but it's throwing me TypeError: list indices must be integers or slices, not str. If any help would be much appreciated. thank you so much in advance. "data": [ { "id": 35, "quotes_description": [ { "id": 51, "total_price": 0, }, { "id": 52, "total_price": 3000, } ], } ] -
Not ImplementedError: subclasses of BaseDatabaseOperations may require a date_trunc_sql() method
I was using Django to build a simple blog site, and tried to use context processors for the Monthly blog archive (such as 2020-12). in models.py class Article(models.Model): time_publish = models.DateTimeField() in context_processors.py def Side_Menu_Context(request): return { 'QS_YM_BlogCount':Article.objects.datetimes('time_publish','month',order='DESC') \ .values('time_publish')\ .annotate(num_of_article=Count('id')), } in setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"static")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'IoTSite.context_processors.Side_Menu_Context', ], }, }, ] in Base_Layout.html which is the base template inherited by all other templates. <aside> <div>Archive</div> <ul> {% for item in QS_YM_BlogCount %} <li><a href="#">{{item.time_publish.year}}-{{item.time_publish.month}} ({{ item.num_of_article }})</a></li> {% endfor %} </ul> </aside> When I run the server and try to access homepage, encountered below error: NotImplementedError at / subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method Request Method: GET Request URL: http://info.yanatm.fun/ Django Version: 2.2.17 Exception Type: NotImplementedError Exception Value: subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method Exception Location: C:\Users\yantian\Anaconda3\lib\site-packages\django\db\backends\base\operations.py in datetime_trunc_sql, line 141 Python Executable: C:\Users\yantian\Anaconda3\python.exe Python Version: 3.7.3 Python Path: ['Z:\\Documents\\IoT\\ec2-user\\IoTSite', 'C:\\Users\\yantian\\Anaconda3\\python37.zip', 'C:\\Users\\yantian\\Anaconda3\\DLLs', 'C:\\Users\\yantian\\Anaconda3\\lib', 'C:\\Users\\yantian\\Anaconda3', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\Pythonwin'] Error during template rendering In template Z:\Documents\IoT\ec2-user\IoTSite\static\Base_Layout.html, error at line 37 subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method 27 </nav> 28 29 <main> 30 {% block main %} 31 {% endblock … -
Page-scope variables in Django
I'm new to Django and Python. What I'm trying to achive is so simple in other frameworks that I am familiar with. But I couldn't find an easy/quick way for it in Django on the internet. I wouldn't use templates for this very basic operation if unnecessary. {% for tweet in tweets.itertuples %} {% if tweet.sent == 'pos' %} {% with color_class='text-success' %} {% endwith %} {% with fa_class='smile' %} {% endwith %} {% elif tweet.sent == 'neg' %} {% with color_class='text-danger' %} {% endwith %} {% with fa_class='frown' %} {% endwith %} {% else %} {% with color_class='text-muted' %} {% endwith %} {% with fa_class='meh' %} {% endwith %} {% endif %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ tweet.unix }}</small> </div> <h2> <i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i> <a class="article-title text-{% if tweet.sent == 'pos' %} 'success' {% endif %}" href="#"> {{ tweet.sentiment }} </a> </h2> <p class="article-content">{{ tweet.tweet }}</p> </div> </article> {% endfor %} the following part doesn't get rendered as I want. <i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i> <a class="article-title … -
Django How to access the url "/admin" (SuperUser) skipping this path("<str:x>", views.xx) in urls.py?
Django How to access the url "/admin" (SuperUser) skipping this path("str:x", views.xx) in urls.py ? -
Django Form not saving for Custom User Model
I have a register user form which is doing all the validation as expected. However, it is not saving. I am not able to figure out the reason. How do I debug it ? Any help ? I am a newbie to forms and formviews any good document with example would really help me. class RegisterForm(forms.ModelForm): phone_number = forms.IntegerField(required=True) password1 = forms.CharField(widget=forms.PasswordInput()) password2 = forms.CharField(widget=forms.PasswordInput()) country_code = forms.IntegerField() #schools = school.objects.all() #school_name = forms.ModelChoiceField(queryset=school.objects.distinct()) MIN_LENGTH = 4 class Meta: model = User fields = ['username','country_code','phone_number', 'password1', 'password2', 'full_name' ] def clean_phone_number(self): phone_number = self.data.get('phone_number') print(phone_number) if User.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError( _("Another user with this phone number already exists")) if len(phone_number) == 10 and phone_number.isdigit(): pass else: raise forms.ValidationError( _("Invalid Phone Number")) return phone_number def save(self, *args, **kwargs): print("saving") user = super(RegisterForm, self).save(*args, **kwargs) user.set_password(self.cleaned_data['password1']) print('Saving user with country_code', user.country_code) user.save() return user Views.py class RegisterView(SuccessMessageMixin, FormView): template_name = 'register-2.html' form_class = RegisterForm success_message = "One-Time password sent to your registered mobile number.\ The verification code is valid for 10 minutes." def form_valid(self, form): full_name=self.request.POST["full_name"] user = form.save() print(user.id) username = self.request.POST['username'] password = self.request.POST['password1'] user = authenticate(username=username, password=password) kwargs = {'user': user} self.request.method = 'POST' print("User created") The print in clean_phone_number … -
VueJS - how can i edit my components in production?
I recently deployed a Django-VueJS application that uses django webpack-loeader to load Vue components in my Django template. I deployed the application to Digital Ocean and everything works. Now i edited the code in one of my components and once i saved, i expected to see the edited component, but instead i will still see the old version of the component before i edited it. I tried to clean my cache but it didn't work, so i guess there is something else i need to do. Here is my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const pages = { 'main': { entry: './src/main.js', chunks: ['chunk-vendors'] }, } module.exports = { pages: pages, runtimeCompiler: true, filenameHashing: false, productionSourceMap: false, publicPath: process.env.NODE_ENV === 'production' ? 'static/vue' : 'http://localhost:8080/', outputDir: '../django_vue_mpa/static/vue/', chainWebpack: config => { config.optimization .splitChunks({ cacheGroups: { moment: { test: /[\\/]node_modules[\\/]moment/, name: "chunk-moment", chunks: "all", priority: 5 }, vendor: { test: /[\\/]node_modules[\\/]/, name: "chunk-vendors", chunks: "all", priority: 1 }, }, }); Object.keys(pages).forEach(page => { config.plugins.delete(`html-${page}`); config.plugins.delete(`preload-${page}`); config.plugins.delete(`prefetch-${page}`); }) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]); // Uncomment below to analyze bundle sizes // config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin); config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://localhost:8080') .host('localhost') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["*"]}) } }; I'm … -
django-tenant-schemas getting confused with default subdomain of url
The url of my application is stagging.domain.com in the database my default schema domain_url is stagging.domain.com and the domains for tenants are: tenant1.stagging.domain.com tenant2.stagging.domain.com But when I try to access the default schema I get this error: No tenant for 'stagging.domain.com' When i try to access the other ones works fine. My guess is that is thinking stagging is a schema -
Django + HTML: If and Else statement in template not working. it always goes to the if, even when user has no profile image, dummy image not shown
Correct me if I am wrong, but i am 99.99% sure that all my codes are correct. Basically in my template, I am trying to set a default image, if user has no profile image, they will be rendered the dummy image, but if they have a profile image, their profile image will show. But somehow, If I have a profile pic, yes my profile pic will show If I dont have a profile pic, nothing will show. There wont be any dummy image The static is loaded correctly, and the else also works, because I tried, but just somehow, the dummy image does not show up for someone that does not have a profile pic. Can anyone explain why? Thanks def account_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: account = Account.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['email'] = account.email context['profile_image'] = account.profile_image.url context['hide_email'] = account.hide_email context['BASE_URL'] = settings.BASE_URL return render(request, "account/account.html", context) MODELS.PY class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):] def get_profile_image_filepath(self, filename): return 'profile_images/' + str(self.pk) + '/profile_image.png' … -
How to implement real-time comment system in a django-react app with channel/celery/redis etc..?
I have a web-app with Django backend and react frontend where inside an organization or company, there are multiple users. Now, I am trying to implement real-time commenting system where if one user types any comment and posts it, another user will be able to see it without refreshing the page. I have seen some examples of asynchronous tasks using celery with redis but couldn't find any with react implementation. What would be a good approach towards achieving the real-time comment system in the react/django app? -
It's possible to perform db operations asynchronously in django?
I'm writing a command to randomly create 5M orders in a database. def constrained_sum_sample( number_of_integers: int, total: Optional[int] = 5000000 ) -> int: """Return a randomly chosen list of n positive integers summing to total. Args: number_of_integers (int): The number of integers; total (Optional[int]): The total sum. Defaults to 5000000. Yields: (int): The integers whose the sum is equals to total. """ dividers = sorted(sample(range(1, total), number_of_integers - 1)) for i, j in zip(dividers + [total], [0] + dividers): yield i - j def create_orders(): customers = Customer.objects.all() number_of_customers = Customer.objects.count() for customer, number_of_orders in zip( customers, constrained_sum_sample(number_of_integers=number_of_customers), ): for _ in range(number_of_orders): create_order(customer=customer) number_of_customers will be at least greater than 1k and the create_order function does at least 5 db operations (one to create the order, one to randomly get the order's store, one to create the order item (and this can go up to 30, also randomly), one to get the item's product (or higher but equals to the item) and one to create the sales note. As you may suspect this take a LONG time to complete. I've tried, unsuccessfully, to perform these operations asynchronously. All of my attempts (dozen at least; most of them using sync_to_async) … -
Django stream function prints live
I have a Django portal which run automation jobs and respond to the User with live output using Ajax. The current setup is, django is just the front end and we have a standalone Python tool to do the automation itself. So front end use Ajax call to Django. Django will run subprocess to execute the automation tool and return STDOUT live to Ajax call. Now we want to transform the automation tool to be an app inside Django so we can Unify many things. I manage to do all transformation so instead of calling a subprocess, you just call a function. I manage to grab the function STDOUT as well with the help of the below article (Generator from function prints)Generator from function prints) it is working fine except it is not live. it just iterate the STDOUT after the function is completed, not during execution. I want to know what is the best practice to do that. -
When posting a form using FormMixin in Detail View in django, it does not post data
I am trying to write comments on a post and which is in DetailView using FormMixin. When iI try to post the comment, it does not post it but just gives the CSRF data in the url bar. here is my View class PostDetailView(LoginRequiredMixin, FormMixin, DetailView): model = Post form_class = CommentCreationForm def get_success_url(self): return reverse('post-detail', kwargs={'pk' : self.object.id}) def get_context_data(self, **kwargs): print("********************") print("Context taken") print("********************") context = super().get_context_data(**kwargs) context['form'] = CommentCreationForm(initial={ 'post': self.object }) return context def post(self, request, *args, **kwargs): print("********************") print("Post taken") print("********************") self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print("********************") print("Valid taken") print("********************") form.instance.author = self.request.user form.save() return super(PostDetailView, self).form_valid(form) this is what i get in url bar http://localhost:8000/blog/post/29/?csrfmiddlewaretoken=MFUjN61oQRLHOoBDKwfpc5vuklTW3nnhmtRXFlflOGeFyhEim1H8OBMsEnmZ6YaT&content=asdafdsf -
How to import node package in django template?
I want to add the wallet connect functionality in my project and there is only npm package for wallet connect and I don't know how can i import that and use that. right now i am getting error: Uncaught SyntaxError: Cannot use import statement outside a module , my node_modules file is inside the static folder right now. *both imports are not happening in following code. import WalletConnect from "static/node_modules/@walletconnect/client/dist/umd/index.min.js"; import QRCodeModal from "@walletconnect/qrcode-modal"; // Create a connector const connector = new WalletConnect({ bridge: "https://bridge.walletconnect.org", // Required qrcodeModal: QRCodeModal, }); // Check if connection is already established if (!connector.connected) { // create new session connector.createSession(); } if more information is required then tell me in comment section, I'll update my question with that information. Thank you! -
Django Error: 'ManyToManyDescriptor' object has no attribute 'all'
i am getting this error. i am trying to loop through posts to display the posts that are part of the collection. relevant info: models.py class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', null=True, blank=True) views.py def collection_detail_view(request, pk): collection = Collection.objects.get(id=pk) posts = Collection.posts.all() #this is the error context = { 'collection': collection, 'posts': posts } return render(request, 'collection_detail.html', context) -
Product filter for Django categories and subcategories
There is a problem, confused in several things. Made some filter for categories, but it filters only for subcategories. When you click on the parent category, it's just a blank page, when you click on the child, everything is filtered well. And I got confused in the url, how do I output both the parent url and the child? I will be very grateful. Sorry for the Russian When i click on parent category pic, When I click on child category pic models.py class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField('Название', max_length=255) slug = models.SlugField('Ссылка', unique=True) def get_absolute_url(self): return reverse('jewel:category_detail', args=[ self.slug]) views.py def cat(request, cat_slug): products = Product.objects.all() main_categories = Category.objects.filter(parent=None) sliders = Slider.objects.all() cats = 0 if cat_slug: category_s = get_object_or_404(Category, slug=cat_slug) products = products.filter(category=category_s) context = { 'products': products, 'main_categories': main_categories, 'category_s': category_s, 'sliders': sliders, } return render(request, 'jewel/category_detail.html', context) urls.py path('category/<slug:cat_slug>/', views.cat, name='category_detail'), -
Perform google search then get result save in django database
i am learning Django tutorial, could you pls advise me how to edit cod to get search result to put into database? Below are my cod and sure that the rest of cod in this tutorial i did correctly and test complete, many thanks class HomeListView(ListView): """Renders the home page, with a list of all messages.""" model = LogMessage def get_context_data(self, **kwargs): context = super(HomeListView, self).get_context_data(**kwargs) return context def log_message(request): form = LogMessageForm(request.POST or None) if request.method == "POST": if form.is_valid(): query = form.save(commit=False) for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0): message = j message.log_date = datetime.now() message.save() return redirect("home") else: return render(request, "hello/log_message.html", {"form": form}) -
Passing context to another view (returns None)
I have two views function and want to pass context to another view. def view_1(request): # code of view_1 context = {'a': a,'b': b} return render(request, view_1.html, context) view_1.html <p>{{ a }}</p> <p>{{ b }}</p> I can see the values in view_1.html def view_2(request): a = request.GET.get('a') b = request.GET.get('b') context = {'a': a, 'b': b} return render(request, view_2.html, context) view_2.html returns all context values as None. How to transfer the context into another view? -
How to get request.user.username in django logger?
I am trying to get the login username in Django logger but no luck and not able to figure out where I am doing a mistake. Please find my code: a)code in settings.py import logging import logging.config LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #########formatter######################### 'formatters': { 'verbose': { 'format': '%(levelname)s - %(asctime)s-- %(module)s - %(process)d - %(thread)d - %(message)s' }, 'simple': { 'format': '[%(asctime)s] : %(levelname)5s : %(message)s:' }, }, #########################Handlers ################################## 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'abc.log', 'formatter': 'simple' }, 'console': { "class": "logging.StreamHandler", "level": "DEBUG", }, }, #################### Loggers ###############(A single Logger can have multiple handler ) 'loggers': { 'django': { 'handlers': ['file','console'], 'level': 'DEBUG', 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG') }, }, } b)code in views.py import logging logger = logging.getLogger("django") c)function in view.py where I am trying to show username. def retrievects1_view(request): if request.user.is_authenticated: logger.info('CTADashboard Page is opened!',request.user.username) logger.debug('My message with %s', 'args', extra={'user': request.user}) print(request.user.username) response = HttpResponse(content_type='application/ms-excel') -----Continue---- **O/p in the log file:** [2021-01-07 18:47:32,780] : INFO : "GET /exportctatot_data/? HTTP/1.1" 200 9728: [2021-01-07 18:47:45,202] : INFO : "GET /gensall/ HTTP/1.1" 200 82259: [2021-01-07 18:47:46,145] : INFO : Home Page is opened!: #**here username is not … -
saving audio file in django
How to save audio file but I'm not using form.py only views, HTML, models? models.py class Message(models.Model): messager_id = models.AutoField(primary_key=True) message_text = models.CharField(max_length=2000) message_title = models.CharField(max_length=2000, blank=True) sender = models.ForeignKey(Doctor, related_name='sender_doctor',on_delete=models.CASCADE) receiver = models.ForeignKey(Doctor, related_name='reciever_doctor',on_delete=models.CASCADE) send_message = models.DateTimeField(blank= True) read_message = models.DateTimeField(blank= True, null=True) mark_as_read = models.BooleanField(default=False) recording = models.FileField(upload_to='audio/', blank= True, null=True) views.py def writemessage(request, id): print("Please Write Message") docid = Doctor.objects.filter(doctor_id = id) print(docid) writemessage = Doctor.objects.exclude(doctor_id = id) cnt = {'writemessage':writemessage, 'docid':docid} if request.method == "POST": message_text = request.POST['message_text'] message_title = request.POST['message_title'] docotname = request.POST['receiver'] receiver = Doctor.objects.get(doctor_id=docotname) sender = Doctor.objects.get(doctor_id=id) send_message = timezone.now() # read_message = timezone.now() recording = request.POST['recording'] message = Message(message_text=message_text, message_title=message_title , receiver=receiver, sender=sender, send_message=send_message) message.save() return render(request, 'message.html') return render(request, 'writemessage.html', cnt) My error is: MultiValueDictKeyError at /message/writemessage/2 'recording' -
How to pass request object to serializer in django rest framework unit test
#model.py file class FileModel(models.Model): file = models.FileField(verbose_name=_('File')) title = models.CharField(max_length=255, verbose_name=_('Title')) start_time_to_creating = models.DateTimeField(verbose_name=_('Start Time To Creating')) created_time = models.DateTimeField(auto_now_add=True, verbose_name=_('Created Time')) time_to_deleting = models.DateTimeField(null=True, blank=True, verbose_name=_('when_it_will_be_deleted')) page_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Page Count')) row_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Row Count')) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('User')) #serializers.py file class FileSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = ['id', 'file', 'title', 'start_time_to_creating', 'created_time', 'time_to_deleting', 'page_count', 'row_count'] #views.py file class FileListByUserView(generics.ListAPIView): queryset = FileModel.objects.all() serializer_class = FileSerializer filter_backends = (DjangoFilterBackend, OrderingFilter) filterset_class = FileFilter ordering_fields = ['created_time', 'title'] ordering = ['-created_time'] def get_queryset(self): user_id = self.kwargs.get('user_id') return super().get_queryset().filter(user=user_id) #urls.py file urlpatterns = [ url(r'^list/(?P<user_id>[0-9]+)/?$', FileListByUserView.as_view(), name='file-list-by-user') ] I serialize my FileModel model with FileSerializer and get it as a response. I want to test this. but I could not give the request object to the FileSerializer serializer that I used in unit test. So the file url does not match the data in the response because I cannot make the absolute url and it falls into error. from rest_framework.test import APIClient class TestBase(TransactionTestCase): reset_sequences = True def setUp(self): super().setUp() self.client = APIClient() def test_list_by_user(self): response = self.client.get(reverse('file-list-by-user', kwargs={'user_id': 1})) self.assertEqual(response.status_code, 200) file_models = FileModel.objects.all() file_serializer_data = FileSerializer(instance=file_models, many=True, context={'request': }).data content = str(response.content, encoding="utf8") … -
Is it possible to implement websockets in DjangoRestFramework?
Is it the right practice to use WebSockets in DjangoRestFramework and if not which technology or framework could be used to do so ? Thanks in advance. -
Access session variables from render funcition of the plugins in Django Cms
I have a view called create_pdf(request), which takes a json from the body of the httprequest, and I have some plugins defined in a page (/input_url). After rendering the page, I save it to pdf in here: pdfkit.from_url(input_url, output) Being the output the folder I want the pdf in. I want to fill the plugins with the info contained in the json, but the only way to access it is by saving the json in a folder and open the file in each of the plugins. Is there anyway to save globally the instance of the json by session and access it from the render function of the plugins? I know I can save the info in a session variable from the view, but I don't know the way to access to it from the render function of the plugin. Thanks for helping.