Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - logout view customisation fail
I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view: Method 1: from django.contrib.auth import views as auth_views from boutique.models import Category app_name = 'users' urlpatterns = [ ... path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}), # I also tried this: # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}), # I also tried this: # path('logout-customised-url/, auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}), # This is working tho it wouldn't be automatically redirect to this path when logged out Method 2: ... path('logout/', views.NewLogoutView.as_view()), # NewLogoutView code below: views.py from boutique.models import Category from django.contrib.auth.views import LogoutView class NewLogoutView(LogoutView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context Still not working, I guess the two methods are trying to do exactly the same thing... Is there any workaround? Thanks! -
Rest Framework deserialize one field and serilize model object
Hi I want to deserialize only using 1 field. However, I want to serialize it as an object depending on the model. Suppose I have: #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() class Query(models.Model): name = models.CharField() product = models.ForeignKey(Product) ... #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class QuerySerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Query fields = '__all__' I want to POST/deserialize something like this on the QuerySerializer: { "name": "Query 1", "product": "Banana", ... } and I want something like this in return for serializer: { "name": "Query 1", "product": { "name": "Banana", "amount": 1, "description": "Banana description" } ... } I know a way is overriding to_internal_value but I do not like it since it messes up with ValidationErrrors. -
Add for loop inside a django view
this is my django view.What it basically does is, it gets the checked data from Html view.But I have to loop through each data in the view, or in template so that I can get not only the name of subtest but also it's fields.Subtest is the name of my model,and name is it's field def create_test_bills(request): if request.method == 'GET': selected = request.GET.getlist('selected') for i in range(0,len(selected)): a = selected [i] print(selected) print(a) sub_test = Subtest.objects.filter(name=a) return render(request,'report.html',{'sub_test':sub_test}) -
Access Django custom user profile field
I added a custom user profile field "role" with the following models.py. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): ROLE_CHOICES = ( (792, 'Student'), (172, 'Teacher'), (864, 'Supervisor'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.IntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() What is the best way to return the int value assigned to the "role"? For example if the current logged in user is assigned the role of "Teacher", I want to be able to use the 172 value elsewhere like in views.py -
AH01630: client denied by server configuration issue
After I changed something in my file(s) in my Linux server, my whole layout in website collapsed. This is how it looks myawsdjapp.com And below is the error log. [Mon Feb 17 12:52:23.636400 2020] [authz_core:error] [pid 7845:tid 140639593273088] [client 121.131.97.11:49904] AH01630: client denied by server configuration: /home/djtu/django_project/staticblog, referer: https://www.myawsdjapp.com/ Weird thing is, I don't have folder named 'staticblog'. Here's my ls command result. $ ls -la /home/djtu/django_project/ total 228 drwxrwxr-x 8 djtu www-data 4096 Feb 16 19:58 . drwxr-xr-x 7 djtu djtu 4096 Feb 17 12:33 .. -rw-r--r-- 1 djtu djtu 6148 Feb 15 14:56 .DS_Store drwxr-xr-x 6 djtu djtu 4096 Feb 15 14:56 blog -rw-rw-r-- 1 djtu www-data 167936 Feb 16 19:58 db.sqlite3 drwxr-xr-x 3 djtu djtu 4096 Feb 17 11:59 django_project -rw-r--r-- 1 djtu djtu 634 Feb 15 14:56 manage.py drwxrwxr-x 3 djtu www-data 4096 Feb 15 14:56 media -rw-r--r-- 1 djtu djtu 13994 Feb 15 14:56 posts.json -rw-r--r-- 1 djtu djtu 624 Feb 15 14:56 requirements.txt drwxrwxr-x 4 djtu djtu 4096 Feb 16 20:22 static drwxr-xr-x 5 djtu djtu 4096 Feb 16 18:55 users drwxrwxr-x 5 djtu djtu 4096 Feb 15 16:58 venv And this is my virtual host setting file. I used certbot. <IfModule mod_ssl.c> <VirtualHost … -
putting finditer() output into an array
I'm trying to find the index of all "TRN" in a string, which I've done, but then i want to put all the indexes into an array, which I can't seem to do. import re string = 'a string with TRN, then another TRN' for match in re.finditer('TRN', string): spots = match.start() print(spots) Output is: 14 32 The output i want is: [14, 32] I've tried putting it into array and append the output like this, but the result is NONE NONE. import re into_array = [] string = 'a string with TRN, then another TRN' for match in re.finditer('TRN', string): spots = match.start() x = into_array.append(spots) print(x) Output is: None None any help would be greatly appreciated. -
Django - Handle Multiple different Level Nest Model
I have some question about django nested model. As i know, to handle nested data structure, i must de-serialize every data, then create the object that will connected with ForeignKeyField. I could handle this by override the .create() method by separate every nested data by .pop() and create each object model separately. Here is the example how i handle 2 level nested data (based on documentation: DRF Documentation) def create(self, validated_data): child_data = validated_data.pop('child_data') parent_obj = ParentModel.objects.create(**validated_data) for data in child_data: ChildModel.objects.create(parent_id=parent_obj, **data) return parent_obj I have some trouble here. I have multiple multi level data structure, maybe like data below: "data_a": [ { "data_a_1": [ { "data_a_1_1": [ { "data_a_1_1_1": "example_a_1_1_1", "data_a_1_1_2": "example_a_1_1_2" } ] }, { "data_a_1_2_1": "Example a-1-2-1", "data_a_1_2_2": "Example a-1-2-2" } ] "data_a_2": [ { "data_a_2_1": "Example a-2-1" }, { "data_a_2_2": "Example a-2-2" } ] } ] My question is: What is the best way to handle dynamic data structure like this? It will take a long hardcoded script to handle multiple multilevel data structure by override .create() as i mention above. Any other best practice to handle mentioned data-strucure? -
Wagtail-ModelTranslation Template Fragment Caching
I've implemented a multilingual site using wagtail and wagtail-modeltranslation but I'm having a problem with template fragment caching. The cache works but is not respecting the separate languages. Whichever language is accessed first after a save, is the one that will be served for all languages. I've tried two ways of setting the cache key to no avail. First from the django docs, second trying to explicitly include the language code in the template First: {% cache 604800 about_copy LANGUAGE_CODE %} ... HTML ... {% endcache %} Second: Using a simple template tag from django.utils.translation import get_language @register.simple_tag(takes_context=True) def get_lang(context, *args, **kwargs): return get_language() {% cache 604800 about_copy get_lang %} ... HTML ... {% endcache %} My save method is as follows: def save(self, *args, **kwargs): """Create a template fragment key. Then delete the key.""" key = make_template_fragment_key("about_copy") cache.delete(key) return super().save(*args, **kwargs) This does clear the correct fragment regardless of not including any language related arguments Any help would be greatly appreciated. Thanks! -
Why there is raise a mistake about {%endfor%} in line 9?
{% extends 'base.html' %} {% block title %}Последние статьи{% endblock %} {% block content %} {% if latest_articles_list %} {% for a in latest_artcles_list %} <a href="#">{{a.article_title}}</a> {% endfor %} {% else %} There are no latest articles {% endif %} {% endblock %} -
Python rq.worker not honoring Django's LOGGING config
I am trying to run a standalone script outside of a Django app that interfaces with a Redis queue and uses the Python rq module. Everything is working fine but somewhere in either upgrading to Python 3.8 (from 2.7) or upgrading from Django 2.2 (from 1.11) or from rq to 1.2.2 (from 0.13) rq stopped honoring the Django LOGGING config. Here is what my Django settings.py file looks like: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(asctime)s [%(process)d] [%(levelname)s] pathname=%(pathname)s lineno=%(lineno)s %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S" }, "simple": { "format": "%(asctime)s [%(name)s] %(levelname)s - %(message)s" } }, "handlers": { "null": { "level": "DEBUG", "class": "logging.NullHandler" }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "simple" } }, "loggers": { "django.request": { "handlers": ["console"], "level": "ERROR", "propagate": True }, "api": { "handlers": ["console"], "level": "DEBUG", "propagate": True }, "worker": { "handlers": ["console"], "level": "DEBUG", "propagate": True }, "rq.worker": { "handlers": ["console"], "level": "ERROR", "propagate": True } } } And here is what my worker.py looks like: import django django.setup() import os import logging import redis import multiprocessing from rq import Queue, Connection from rq.worker import HerokuWorker logger = logging.getLogger("worker") if __name__ == "__main__": redis_url = os.getenv("REDISTOGO_URL", None) if … -
Is it a security risk to place protected media beside public media in Django app?
First of all, this is not a duplicate, as all other related questions are outdated and do not answer this specific question. In my Django 2.2 app I need to store public media files, as well as private media files. I have researched all possible options, and have concluded that an easy option might be using the following media urls: (Base url, ‘/media/) Public: ‘media/public’ Private ‘media/private’ With the following Nginx location config: location: media/public Internal Alias: media/public Location: media/private Internal Alias: media/private With the following view config: Def publicView(request): // view config // [“x-send-redirect”] // etc.. @login_required() Def PrivateView(request): // view config // [“x-send-file”] //etc.. Is the above secure? Is having both public and private inside media a security issue? Is it frowned upon to place a path like ‘media/private’ in a location block in nginx? (Please ignore syntax errors, I am posting this from cellphone) Thank you. -
Bulk insert in Django Rest Framework JSONAPI
I'm implementing a DRFJSonAPI API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.html However, I got stuck on trying to implement a bulk insert, it seems that the JSONAPI specification doesn't mention anything about it I found only this referring to it as an experimental feature: https://springbot.github.io/json-api/extensions/bulk/ and it doesn't seem to be implemented by DRF JSONAPI I've tried several approaches, from the basic of having a new @action defined on my viewset, to even just adding the DRF api_view and going from there. But what it looks like is that my serializer doesn't understand correctly the data and returns an empty dictionary. My serializers: from rest_framework_json_api import serializers, relations, views class VideoScriptRowSerializer(serializers.ModelSerializer): included_serializers = { 'video': 'videos.serializers.VideoOnDemandSerializer', } class Meta: model = VideoScriptRow fields = ( 'video_id', 'index', 'character', 'guessed', 'is_locked', 'loop', 'text', 'time_start', ) class VideoOnDemandSerializer(serializers.ModelSerializer): script_rows = relations.ResourceRelatedField( queryset=VideoScriptRow.objects, # queryset argument is required required=False, many=True, ) included_serializers = { 'script_rows': 'videos.serializers.VideoScriptRowSerializer', } class Meta: model = VideoOnDemand fields = ( 'title', 'workflow_status', 'initial_offset', 'video_offset', 'video_input', 'thumbnail_url', 'transcript_uri', 'created_at', 'script_rows', ) read_only_fields = ('created_at', 'workflow_status') My views: from rest_framework_json_api.views import ModelViewSet, RelationshipView class VideoScriptRowViewSet(ModelViewSet): queryset = VideoScriptRow.objects.all() serializer_class = VideoScriptRowSerializer class VideoOnDemandViewSet(ModelViewSet): permission_classes = [IsAuthenticated] queryset = VideoOnDemand.objects.all() serializer_class = VideoOnDemandSerializer Based on DRF … -
Django Datepicker and Autocomplete not rendering when used together
i am using Django, bootstrap_datepicker_plus and django-autocomplete-light. I had no issues when i used the 2 libraries separately, but when i attempt to use them both in the same form, for some reason, only the autocomplete widget is working, while the datepicker widget is not. I am not sure why, maybe it is due to conflicting libraries, but are there any solutions for this issue? I tried to search online but could not find any solution that would help me. Any help is appreciated and welcomed! The code is below: forms.py class SalesTaskPlaceHolder(forms.ModelForm): class Meta: model = SalesTask fields = ['title', 'description', 'priority', 'status', 'rnd_project', 'salesExtra', 'rndExtra', 'start_date', 'due_date'] exclude = ['task_id'] widgets = { 'salesExtra': autocomplete.ModelSelect2Multiple(url='sales-extra-autocomplete'), 'rndExtra': autocomplete.ModelSelect2Multiple(url='rnd-extra-autocomplete'), 'start_date': DatePickerInput(), 'due_date': DatePickerInput(), } def __init__(self, *args, **kwargs): self.id = kwargs.pop('id',None) super(SalesTaskPlaceHolder, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Title of your task' self.fields['description'].widget.attrs['placeholder'] = 'What is this task about?' self.fields['status'].widget.attrs['placeholder'] = '0-100' self.fields['salesExtra'].label = 'Sales Personnel' self.fields['rndExtra'].label = 'RnD Personnel' self.fields['rnd_project'].queryset = RndProject.objects.filter(customerRequirement__sales_project=self.id) views.py class SalesExtraAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = SalesExtra.objects.all() if self.q: qs = qs.filter(user__username__istartswith=self.q) return qs class TaskCreateView(LoginRequiredMixin, CreateView): model = SalesTask form_class = SalesTaskPlaceHolder template_name = 'rnd/task_create.html' def get_form_kwargs(self): kwargs = super(TaskCreateView, self).get_form_kwargs() kwargs['id'] = self.kwargs['id'] return kwargs def … -
Api Post always has user as null even though there is a logged in user
I am trying to have an api for my answers app. When a post is created, the user is always set to null. I am not sure of why that is. How do I auto-add some fields to the saving object, like the authenticated user, user IP address? Here is my serializer: User = get_user_model() class UserPublicSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'is_staff', 'photo_url' ] class AnswerCreateUpdateSerializer(ModelSerializer): user = UserPublicSerializer(read_only=True) class Meta: model = Answer fields = [ 'object_pk', 'content_type', 'answer', 'user' ] read_only_fields = ['user'] And the api create view: class AnswerCreateAPIView(CreateAPIView): queryset = Answer.objects.all() serializer_class = AnswerCreateUpdateSerializer And the model is: class AnswerAbstractModel(BaseAnswerAbstractModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_answers", on_delete=models.SET_NULL) answer = FroalaField() submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True) ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True) class Answer(AnswerAbstractModel): class Meta(AnswerAbstractModel.Meta): db_table = "answers" I beg your pardon for my ignorance of the django world. I am trying hard to figure it out though. That said, what should be the approach here? -
Many-to-many relationship between Django User, Permissions, and another entity
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations. Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each. So, imagine a schema like this: Users>---UserOrg---- Permissions relate to services provided by the company, and in general look like: “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc. Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization. From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each organization. I’m fairly new to Django, so I'm not sure if this is even doable. How would I start? -
How can i update user model extended via "OneToOneField"
I have some issues with updating my database, in my serializer i use extended via OneToOneField django user model with two extra fields with user image and his motto. So i think the problem with instance in my serializer, but i can't figure out how to do that. #core.models class MangaUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_image = models.ImageField(upload_to='upicks') user_motto = models.CharField(max_length=256) #api.serializers class UserSerializer(serializers.ModelSerializer): #mangauser_set = serializers.SerializerMethodField() user_image = serializers.ImageField(source='mangauser.user_image') user_moto = serializers.CharField(source='mangauser.user_motto') class Meta: model = User fields = ['id', 'username', 'email', 'password', 'user_image', 'user_motto'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance #api.view class GetUserInfo(APIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get(self, request, *args, **kwargs): # serializer to handle turning our `User` object into something that # can be JSONified and sent to the client. serializer = self.serializer_class(request.user, context={"request":request}) return Response(serializer.data, status=status.HTTP_200_OK) def put(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) #response ValueError at /api/v1/userinfo/ Cannot assign "{'user_motto': 'js говно'}": "User.mangauser" must be a "MangaUser" … -
Script timed out before returning headers: wsgi.py; Django app on elastic beanstalk
I am deploying a Django app, but in the past 2 days I randomly started receiving the Script timed out before returning headers: wsgy.py with the following logs: [Sun Feb 16 03:02:30.697009 2020] [mpm_prefork:notice] [pid 20719] AH00163: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 configured -- resuming normal operations [Sun Feb 16 03:02:30.697031 2020] [core:notice] [pid 20719] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Sun Feb 16 03:03:33.906331 2020] [mpm_prefork:notice] [pid 20719] AH00169: caught SIGTERM, shutting down [Sun Feb 16 03:03:34.352673 2020] [suexec:notice] [pid 29207] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Sun Feb 16 03:03:34.368938 2020] [so:warn] [pid 29207] AH01574: module wsgi_module is already loaded, skipping [Sun Feb 16 03:03:34.371217 2020] [http2:warn] [pid 29207] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Sun Feb 16 03:03:34.371234 2020] [http2:warn] [pid 29207] AH02951: mod_ssl does not seem to be enabled [Sun Feb 16 03:03:34.371790 2020] [lbmethod_heartbeat:notice] [pid 29207] AH02282: No slotmem from mod_heartmonitor [Sun Feb 16 03:03:34.371850 2020] [:warn] [pid … -
Error Using CheckConstraint in Model.Meta along with Django GenericForeignKey - Joined field references are not permitted in this query
I am trying to restrict GFK to be pointed to objects of a few models only, and I thought CheckConstraint will be a great way to do this, however I get this error class ManualAdjustment(Model): content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(null=True) booking_obj = GenericForeignKey('content_type', 'object_id') # should point to a app1.Booking1 or app2.Booking2 or app3.Booking3 only - trying to enforce this via CheckConstraint class Meta: constraints = [ models.CheckConstraint( check= Q(content_type__app_label='app1', content_type__model='booking1') | Q(content_type__app_label='app2', content_type__model='booking2') | Q(content_type__app_label='app3', content_type__model='booking3'), name='myconstraint_only_certain_models'), ] Error I get on migrate execute_from_command_line(sys.argv) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/commands/sqlmigrate.py", line 30, in execute return super().execute(*args, **options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/commands/sqlmigrate.py", line 64, in handle sql_statements = executor.collect_sql(plan) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/executor.py", line 225, in collect_sql state = migration.apply(state, schema_editor, collect_sql=True) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 827, in database_forwards schema_editor.add_constraint(model, self.constraint) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 343, in add_constraint sql = constraint.create_sql(model, self) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/constraints.py", line 47, in create_sql check = self._get_check_sql(model, schema_editor) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/constraints.py", line 37, in _get_check_sql where = query.build_where(self.check) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1296, … -
On page navigation with anchor tag on dropdown menu
I'm currently building a top navigation bar that shows dropdown on hover on some of the nav-items. It currently looks like this <nav class="navbar navbar-expand-lg"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a href="#information" class="nav-link dropdown-toggle" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About Us </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown1"> <a class="dropdown-item" href="#">Who we are</a> <a class="dropdown-item" href="#">What we do</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#">Events</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact Us</a> </li> </ul> </div> </div> </nav> So what I want to do is having both dropdown on hover working as well as using the dropdown same button(nav-item) to work as a button that navigates the user to specified section. In the above code, it would be "About Us" that will show its following dropdown on hover. And when "About Us" is clicked, it would navigate the user to specified section ("#information"). I can only get one or the other working. If i get dropdown on hover, navigation doesn't work, if i get navigation work, then dropdown doesn't appear on hover. Any help would be much appreciated Thank you. -
Django: How to add static files in shared templates?
I have shared templates that doesn't belongs to any particular app. Here's my project tree: . ├── root_app │ ├── asgi.py │ ├── forms.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 ├── another_app │ ├── admin.py │ ├── api_services.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── manage.py ├── Pipfile ├── Pipfile.lock ├── README.md ├── requirements.txt ├── static │ └── css │ └── styles.css └── templates ├── base.html └── home.html In my settings file I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ ... ... 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATIC_DIR = [os.path.join(BASE_DIR, 'static')] In my base.html template, I'm trying to call the styles.css from static/css/styles.css this way: {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}" /> But the server responds with a not found: "GET /static/css/styles.css HTTP/1.1" 404 What I'm doing wrong? -
how to count matches in different querysets
I want to count different querysets in my template after doing a search over all models but it seems that the different querysets are in a list of lists. my view function: class Search(ListView): template_name='artdb/searchResult.html' def get_queryset(self): # override get_queryset() has to have that name... q=self.request.GET.get('seastr') models=[Person,Activity,Member,Comment] fields=[l._meta.fields for l in models] res=[] for i,j in enumerate(models): sq=[Q(**{x.name + "__icontains" : q}) for x in fields[i] if not isinstance(x,ForeignKey)] res+=[j.objects.filter(k) or None for k in sq] res=[k for k in res if k] if q: return res else: return Person.objects.none() # SELECT ... WHERE headline ILIKE '%Lennon%'; def get_context_data(self,*args,**kwargs): #q=self.request.GET.get('seastr') context=super().get_context_data(*args,**kwargs) context['member']=Member.objects.all() return context context dict: {'page_obj': None, 'view': <artdb.views.Search object at 0x7f415ec88080>, 'is_paginated': False, 'object_list': [<QuerySet [<Person: David Bolander>, <Person: adam something>]>, <QuerySet [<Comment: david bolander comment>]>], 'member': <QuerySet [<Member: 2019-11-21>, <Member: 2020-02-10>]>, 'paginator': None} my template: {% extends "artdb/index.html" %} {% block sr1 %} <ul> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Persons: {{object_list.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Activities: {{activity.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Members: {{member.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> … -
502 error caused my multiple hosts in django
I am trying to allow multiple hosts that are pulled from database. Its working fine locally but in production I am getting 502 error. Here’s my production setting file from .settings import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projectname_settings', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '', } } ALLOWED_HOSTS = [ "mydomain.com", ] + get_allowed_hosts(DATABASES['default']) Allowed_hosts.py def get_allowed_hosts(db_params): connection = None if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2': import psycopg2 connection = psycopg2.connect(user=db_params['USER'], password=db_params['PASSWORD'], host=db_params['HOST'], port=db_params['PORT'], database=db_params['NAME']) elif db_params['ENGINE'] == 'django.db.backends.sqlite3': import sqlite3 connection = sqlite3.connect(db_params['NAME']) if connection is not None: cursor = connection.cursor() sites_query = cursor.execute("SELECT domain FROM django_site") sites_result = cursor.fetchall() cursor.close() connection.close() I am thinking if there’s special nginx setting needed for this kind of setting -
Django ModuleNotFoundError when making migrations
First of all: I am well aware that there are several questions with this exact error but I've read at least 20 of them and none helped me correct this error. This being said, the problem is the following: I created a directory called 'api' inside my Django project to store all the code related to the api. Inside this directory I created an app called 'profiles_app'. There, in the models.py file I defined a UserProfile class to override the default Django UserProfile class. I then added the app to the INSTALLED_APPS variable in the settings.py file and overrid the default UserProfile class with the following line: AUTH_USER_MODEL = 'profiles_api.UserProfile' Finally I tried to make the migrations to see the new table in the database and this is when the error occurred. This is the stack trace: (venv) C:\Users\Juan Pablo\Documents\backend\backend_django>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) … -
Django Unhasable Type List even though im passing in an object ?(many to many field)
I am trying to run a migration script for my django app, but I keep getting TypeError: unhashable type: 'list' even though I am clearly passing in an Object: I get: error line 87, in buildCisc c.exclusions.add(exclus) line 944, in add self._add_items( line 1119, in _add_items target_ids = self._get_target_ids(target_field_name, objs) line 1059, in _get_target_ids target_ids.add(target_id) TypeError: unhashable type: 'list' when I run the following code ... for ex in exclusionList: if len(Course.objects.filter(ID=ex)) > 0: # exclusion course already exsists exclus = Course.objects.filter(ID=ex) c.exclusions.add(exclus[0]) else: # exclusion course does not exsist yet so we must create it first exclus = Course(ID=ex) exclus.save() c.exclusions.add(exclus) #this is line 87 causing the error where c is a Course object create in prior code, and exclusions is a many to many field from Course to itself. if I try using exclus = Course.objects.create(ID=ex) instead that also gives the same error. The error seems to be saying that the exclus that I am passing in to c.exclusions.add is a list, but it is very clearly an object. I even tried switching exclus to exclus[0] to see if it somehow thought it was a list, but this gave me error: Course Object not iterable so it is … -
how h can convert DICOM image to image of type .png in python
i'm working on django project that make operations on DICOM images and i want to convert Dicom to image of type .png so ican render it to frontend . how i can convert this DICOM to .png type?