Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Programmatically render inclusion tag in Django
Django provides the render(…) shortcut function which essentially takes a template name and a context and returns an instance of HttpResponse containing the rendered template string. Is there an official way to do the same thing with an inclusion tag? That is, instead of supplying a template name I would like to supply the name of an inclusion tag that then gets rendered with its own context (i.e. what the tag function returns) plus an optional additional context. For example, let's consider the following tag: # myapp/templatetags/myapp.py @register.inclusion_tag('myapp/mytemplate.html') def my_inclusion_tag(some_paramter): return { 'some_parameter': some_parameter } Then I would like to be able to do something like http_response = render_tag(request, 'myapp.my_inclusion_tag', {'additional_context': value}) where the entire context would be {'some_parameter': some_parameter, 'additional_context': value}. -
Hooking Django (DRF) to an existing database
I think I am looking for as much advise as possible. I have a project that I have inherited. The codebase is absolutely awful. I have a Django project, within this a React app. There's all manner of proxies between to fetch from the API to deliver up content. However, I want to start to re-write the API, as it is awfully put together. Zero documentation. To re-write the API, I would like take a copy of the exisiting database - and then work with this to write a more consistent API. What would be your advise/steps/method to achieve this, and what should I look out for when doing this? N.B. The database is PostgreSQL. -
Django: Better way to aggregate QuerySet results
I have the following code snippet. I first tried to get the count for male / female directly as annotation but I didn't manage to get these. Therefore I wrote the following for loop. However, it still feels that this solution is not as good as it could be. Do you have any other idea how to write better code here? genders = self.get_answers(self.get_super_guests(), QuestionFocus.GENDER) # >>> <QuerySet [Answer: Male, Answer: Female, Answer: Male]> male = female = 0 for gender in genders: if gender.answer == "Male": male += 1 elif gender.answer == "Female": female += 1 print("Gender distribution is Male", male, "Female: ", female) -
ModuleNotFoundError: No module named 'django_popup_view_field'
you see that all is installed but when i runserver i got this error : ModuleNotFoundError: No module named 'django_popup_view_field' [p-amc-dgps-er@192-168-150-254 Invest_App]$ sudo pip install django-popup-view-field [sudo] Mot de passe de p-amc-dgps-er : DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: django-popup-view-field in /usr/lib/python2.7/site-packages (0.5.0) Requirement already satisfied: Django>=1.8 in /usr/lib/python2.7/site-packages (from django-popup-view-field) (1.11.26) Requirement already satisfied: pytz in /usr/lib/python2.7/site-packages (from Django>=1.8->django-popup-view-field) (2018.9) -
Using cookie cutter to create Django project, running error?
my django version:2.1.7 when i running , it Report errors. Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 679, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/compressor/models.py", line 1, in <module> from compressor.conf import CompressorConf # noqa File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/compressor/conf.py", line 7, in <module> from appconf import AppConf File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/appconf/__init__.py", line 2, in <module> from .base import AppConf # noqa File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/appconf/base.py", line 109, in <module> class AppConf(six.with_metaclass(AppConfMetaClass)): File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/six.py", line 833, in __new__ resolved_bases = types.resolve_bases(bases) AttributeError: module 'types' has no attribute 'resolve_bases' error tip: AttributeError: module 'types' has no attribute 'resolve_bases so , I guess it's the version,but i don't find error! emmm... Does anyone know why? or Does anyone have a similar … -
How to pass data saved from a POST method to the GET method using REST API Django (without a model)?
I have created an API that allows me to upload an image using the POST method in POSTMAN. After submission, I want to display that image name after making a GET request. I am not using any model and I don't intend to grab the image from the directory it is stored in; since I will be uploading images in a server later. I have looked at multiple sources. A few examples are this, and this. This is my current code so far but not successful: views.py: class API(APIView): parser_classes = (MultiPartParser,) def get(self, request, *args, **kwargs): name = self.request.GET.get('image') return HttpResponse(name) def post(self, request): #key is 'image', value is the file uploaded in my machine file = self.request.data img_file = file['image'] #store the image data in this variable if img_file: uploaded_file = img_file fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) #saves it to a specific directory name = fs.save(uploaded_file.name, uploaded_file) image = [{"image_name": name}] serializer = ImageSerializer(image, many = True).data return Response(serializer, status = 200) else: return Response("Image isn't uploaded. Please upload", status = 400) serializers.py: from rest_framework import serializers class ImageSerializer(serializers.Serializer): image_name = serializers.CharField() My expected result within GET request should be like this: {'image_name' : 'image_name_from_POST_Request'} But I am getting this … -
Django serverside processing (Sorting, filtering, pagination) the data from backend
I am currently trying to perform serverside processing of table data from django backend before and using it in an angular app. Currently I am only able to fetch all the data from the database but I want to be able to process it and use it the defined datatable rather than doing all this processing from client side Can anyone help with this? -
AttributeError: 'NoneType' object has no attribute 'user' Django
class GeneratePublisherPdf(APIView): #View def get(self, request, *args, **kwargs): reviewer_id = request.GET.get("user") export_date = datetime.date.today() - datetime.timedelta(1) profile = UserProfile.objects.filter(user_id=reviewer_id).first() users = [profile.user.id, ] for up in UserProfile.objects.filter(publisher=profile.user, user__register_type='5'): users.append(up.user.id) if not len(users): result = { "status": False } return Response(data=result) queryset = ProductCertificate.objects.filter(user__id__in=users, created__date=export_date).order_by('-created') users = [profile.user.id, ]...shows error in user here.plz help to solve thiz -
django dict/queryset/list to json
I want to convert this queryset to json. json.dumps() does not work. serialize does not work. json.dumps() + list() does not work how can I convert querset to json? maybe the reason these conversions are not work is in here. I know that Models.objects.all() or Models.objects.all().only() return queryset, Models.objects.all().values() returns list of dict. I want to add a new key-value set to the first queryset, So I use Models.objects.all().values() but when I add a new key-value set, I think, the datatype is twisted. so now the datatype of 'questionRequeestList' is neither 'List' nor 'Queryset' at converting to json. how can I convert this value to json? or how can I add new queryset to another queryset dict? -
Mocking class methods
I have a situation which i could not find on stack-overflow: some_module.py: class SomeModule(): def a(): pass def b(): pass def c(): pass @classmethod def bring_them_altogether(cls): cls.a() cls.b() cls.c() I am writing a unittest and would like to test the method bring_them_altogether() by determining that methods a(), b() & c() are all called once. In my testcase i have this: test.py: @patch('<...>.some_module.SomeModule', autospec=True) def test_bring_them_altogether(self, mock_class): mock_class.bring_them_altogether() self.assertTrue(mock_class.called) # Returns me False I want to know how to write a proper test case for bring_them_altogether() as i seem to be having some issues getting the output i want. On that note, I want to know how to determine that a mocked-method has been called X - number of times. Thank you for pointing me in the right direction -
Django 2.2: regex url match
i need to create a list of urls that one of my middlewares should ignore. i need to ignore /admin/ and any url that comes after it. how can i proceed ? -
Change the color of road in google map
How to change a google map particular road color using django? is this possible? I am side search about it but i don't found any solution for that so any one have good solution for this please post here. -
How can i use a variable as django model
I want to use this function to get a list out of the database: def get_db_list(IN_DICT, **kwargs): off = kwargs.get('off', None) limit = kwargs.get('limit', None) Keyword = {} Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE'] if off == None and limit == None: LIST = IN_DICT['TABLE'].objects.filter(**Keyword) else: LIST = IN_DICT['TABLE'].objects.filter(**Keyword)[off:limit] return LIST Now my problem is, that IN_DICT['TABLE'] gets passed as String: >>> type(Host_Table) <class 'django.db.models.base.ModelBase'> >>> IN_DICT['TABLE'] 'Host_Table' >>> type(IN_DICT['TABLE']) <class 'str'> How would I have to change the type? This example pulls the correct querry, but only from that table: def get_db_list(IN_DICT, **kwargs): off = kwargs.get('off', None) limit = kwargs.get('limit', None) Keyword = {} Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE'] if off == None and limit == None: LIST = Host_Table.objects.filter(**Keyword) else: LIST = Host_Table.objects.filter(**Keyword)[off:limit] return LIST -
i am facing issue while retriving the check box value in python django
Views.py: def export_selectd_data_to_excel(request): if request.method == 'POST': chk_values = request.POST.getlist('chkselect',None)enter code here print(chk_values) return redirect(user_details)enter code here HTML -
Increasing the view by 1 each time some url hits?
Here I want to increase the number of views by 1 each time the detail view is called.How can I do it ? class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() views = models.IntegerField(default=0) views.py class DetailPackage(generics.RetrieveAPIView): serializer_class = PackageDetailSerializer lookup_field = 'slug' queryset = Package.objects.all() urls.py path('<slug>/detail/', DetailPackage.as_view(), name='detail_package'), I am very new to django rest framework.So am I going the right way by using the generics API view for such cases ? -
if user.is_authenticated not getting logged in user django
Entirely new to python and django framework. Trying to build a login/registration system.' After registering, redirects to home but user is not authenticated (returns false always) views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') fullname = form.cleaned_data.get('fullname') password = form.cleaned_data.get('password1') user = authenticate(username=username, fullname=fullname, password=password) messages.success(request, f'Welcome to blaza {fullname}') if user is not None: login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) home.html {% extends 'base.html' %} {% block title %} Home {% endblock %} {% block content %} {% if user.is_authenticated %} Welcome, {{user.username}}! <a href="">Logout</a> {% else %} <P>You are not logged in</P> <p><a href="">Login here</a></p> {% endif %} {% endblock %} It returns false always. "You are not logged". I have tried {% if request.user.is_authenticated %} still not working. -
Add foreign key field and choices charfield to Django user creation form
I would like to modify Django UserCreationForm so that it would support creating my custom user. There are required fields company and role which both should offer some kind of selection to pick the correct choice (there will be only 3 roles but there can be hundreds of companies). I have followed several different examples but so far in vain. Below is the model. How can I command Django to add the extra fields to the user creation form? ROLE_CHOICES = [ ('role1', 'Role 1'), ('role1', 'Role 2'), ('janitor', 'Janitor'), ] class Company(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) class Meta: ordering = ('created',) db_table = "company" def __str__(self): return self.name class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=200, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') role = models.CharField( max_length=100, choices=ROLE_CHOICES, default='janitor', ) phone_number = models.CharField(null=True, blank=True, max_length=20) class Meta: ordering = ('created',) db_table = "custom_user" def __str__(self): return self.username -
Sequences didn't restore from backup file
I have a Postgres DB working alongside Django. Id in product model is: id | integer | | not null | nextval('product_product_id_seq'::regclass) I have exported it in .bak file and restored it in another server. now that id is like: id | integer | | not null | nextval does not appear in the second server. what is the problem? -
Django DetailView with FormView
I want to make a comment page for post objects, where post object is using DetailView and underneath I would like to have CommentForm for adding comments. I followed along : official docs but I got stuck. I'm getting 404 error. So from the beggining, I have two models in models.py: class Post(models.Model): content = models.TextField(max_length=280, validators=[MaxLengthValidator(280)]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='comments') text = models.TextField(max_length=280) date_created = models.DateTimeField(auto_now_add=True) Then I have my views.py: class PostDetailView(DetailView): model = Post context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentForm() return context class CommentCreateView(SingleObjectMixin, FormView): model = Comment form_class = CommentForm template_name = 'social/post_detail.html' def form_valid(self, form): form.instance.author = self.request.user.userprofile return super().form_valid(form) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden('') # It crashes here! self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.object.pk}) class PostDetail(View): def get(self, request, *args, **kwargs): view = PostDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentCreateView.as_view() return view(request, *args, **kwargs) After little debugging I found out that it crashes while executing line self.object = self.get_object() The urls.py path('post/<int:pk>/', PostDetail.as_view(), name='post-detail'), The error itself: Page not found (404) Request … -
how to do atomic increment in django model
How can I create atomic increment in my model class IpadCode(models.Model): """ code = string """ code = models.CharField(max_length=6, blank=True, null=True) submission_index = models.PositiveIntegerField(default=0) CODE_FIELD = 'code' class Meta: verbose_name = 'ipad code' verbose_name_plural = 'ipad codes' @classmethod def increment_counter(self, code): pass def get_code(self): """ :return: return code for this winner """ return getattr(self, self.CODE_FIELD) def __str__(self): return self.get_code() I need to track how much code has been saved and count that so I can later in view redirect users if they satisfy certain criteria. -
How to create a Django Virtual Environment offline?
I am trying to build a Django virtual environment on my PC that is not connected to Internet. I have Miniconda installed on the PC. When I run this command: conda create --name MyDjangoEnv django I get an error "Conda http error" and it says that I cannot connect to https://www.anaconda.com. Do i need to download any packages from the Internet to make it work? -
Managing several services in a docker container
I am building an application where I'm using several technologies ranging from Django, Redis, Celery Worker, Postgres, Go, Vue. How advisable is it to run all this services in a single container running on one instance on AWS. Is it effective and how scalable is this approach. Please I will appreciate a better approach and recommendations. -
How to run command line inside a django view?
[Context] I have a file upload operation in my Django application (on ubuntu server), I have to execute an operation after the user uploaded the file. The tool for that is only available as a npm package (accessible via command line). What is the recommended solution for this? -
django javascript no reload
how can i change url in django with javascript without refreshing this is my code and it doesn't work // script js $(document).ready(function() { // initial $("#contenu").load("{% url home %}"); // au clic $('#lien li a').click(function() { var page = $(this).attr("href"); $("#contenu").load("html/" + page + ".html"); return false; }); }); // urls.py urlpatterns = [ path('admin/', admin.site.urls), path('index', views.index, name='index'), path('index/home',views.home name="home"), path('contact',views.contact), path('about',views.about),] -
Framework for website which is build by using Bootstrap, JQ and JS
Can we post data from html to database using python without using web framework(django)?