Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Object of type <> is not Json seralizable
I'm new to django rest framework and need some help. I have ApiView: class SomeApiView(APIView): def get_url(self, some_id): return generate_url(Choices.BOOK, some_id) def get(self,request): id = request.query_params.get("some_id") result_url = self.get_url(id) return Response({'result_url': result_url}) here when sending request I get next error: Object of type Choices is not Json serializable. Choices looks like this: class Choices(Enum): BOOK="book" MOVIE="movie" GAME="game" how can I fix this error? Thank you in advance -
I need to create unit tests for my urls in a django project
I have this url which returns the json data of my models but I don't know how to create a unit test for a url like this path("list/", views.json_list, name="json_list"), -
Similar tools like Devexpress for Django
Would like to know if there exists any tools similar to Devexpress gui for Django projects. I found the following link which was posted more than 10 years ago. Maybe currently any solution would be available now? -
Django form in form
I wonder if it is possible to make form in form by using django. For example: class Category(models.Model): title = models.CharField(max_length=200) icon = models.ImageField(upload_to="icons", default="icons/dot.png") def __str__(self): return self.title def get_posts(self): return Post.objects.filter(category__title=self.title) class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=400) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title While I was working with forms based on these models I was splitting CategoryForm and PostForm into two forms (category had to be made before post to make user able to choose new category during making new post) and then into two views. class PostForm(forms.ModelForm): class Meta: model = Post exclude = ('author',) class CategoryForm(forms.ModelForm): class Meta: model = Catergory fields = '__all__' def newPostView(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.save() return redirect('home') form = PostForm() context = {'form':form} return render(request, 'blog/post_form.html', context) def newCategoryView(request) ... ... ... I'd like to make one newPost form which will have Category form implemented - I mean I'd like to be make it possible to choose category from already made categories or make new one if its needed without using another view How can I make it … -
ModuleNotFoundError: No module named 'my_script'
I wanna connect PSQL to django, but store my password not in settings, so I thought I should keep the password in another file, than I import file with password to settings: ... from my_frst_site.local_settings import db ... DATABASES = { 'default': db,} ... my file with password: db = {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'poll_db', 'USER': 'app_manager', 'PASSWORD': 'TWENTY04', 'HOST': 'localhost', 'PORT': '5432', } Now the file structure looks like this: structure of files When I enter command py manage.py check --database default I got error: File "C:\Projects\MY_APP\my_frst_site\my_frst_site\settings.py", line 13, in from my_frst_site.local_settings import db ModuleNotFoundError: No module named 'my_frst_site.local_settings' Anybody know how to fix this problem? -
Django Forms not displaying in html in Django 3
Here i am using Django3 and Python 3.7 I am not able display my form fields while trying to add a custom field initially but as soon as i click Save custom fields button the fields as displaying Here is my views.py class EavAttributeCreateView(CustomAdminMixin, CreateView): model = ClientAttribute form_class = EavAttributeForm template_name = "core/eav_attribute_form.django.html" def form_valid(self, form): print("*** in form valid... ***") try: self.object = form.save(commit=False) self.object.order = form.cleaned_data.get("order", "0") self.object.client = self.request.user.client self.object.type = self.kwargs.get("type") self.object.save() except ValidationError as e: form._errors = e.message_dict return self.form_invalid(form) messages.success(self.request, 'The attribute "{0}" was successfully saved.'.format(self.object.slug)) return redirect(self.get_success_url()) def get_context_data(self, **kwargs): context = kwargs context["eav_type"] = self.kwargs.get("type") context["special_datatypes"] = { "enum": ClientAttribute.TYPE_ENUM, } return context def get_success_url(self): return reverse("entity_attribute_list", kwargs={"type":self.kwargs.get("type")}) Here is my forms.py class EavAttributeForm(forms.ModelForm): description = forms.CharField(max_length=256, required=False, label=u"Hint", help_text="User-friendly custom field name.") datatype = forms.ChoiceField(choices=Attribute.DATATYPE_CHOICES) type = forms.CharField(max_length=20, required=False, widget=forms.HiddenInput) order = forms.FloatField(required=False, initial="0", help_text=u"The fields are ordered according to this number, from the lowest to the highest.") enum_group = ChoicelessTypedMultipleChoiceField(required=False, label="Choice values", coerce=enum_value, widget=forms.CheckboxSelectMultiple) class Meta: model = Attribute fields = ["type", "name", "description", "required", "order", "datatype", "enum_group", "in_enquiry_form", "is_auto_filter"] exclude = ("in_enquiry_form", "is_auto_filter") def clean_enum_group(self): ..... ..... Here is my template.html <div class="row"> <div class="span10 offset1"> <!-- START … -
[ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]
hi guys I am a novice to django,and I have been making a CRUD with Products having categories,sub categories,colors,size.When I am trying to make a new "category" the data isnt getting displayed on webpage heres the error: below is the serializer of Categories and the foreign key and the insert_cat function when I am trying to insert a data into webpage it comes blank I am not sure where I am going wrong,please help -
Django server only listening to socket server and ignoring routes
Here is my WSGI.py file in django, im importing the folder called "webSocket" that contains the views.py file where the server code for the socket is written from django.core.wsgi import get_wsgi_application from webSocket.views import server import socket import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'b2b_backend.settings') application = get_wsgi_application() # make the app run with socketio application = socket.WSGIApp(application, server) here is my urls.py file in root folder of django, the routes are working fine before adding the socket server to the project from django.urls import include, path urlpatterns = [ path('users/', include('database_models.b2b_user.urls')), ] here is my socket server file in the webSocket folder views.py file import socket import threading SERVER = "localhost" PORT = 8000 HEADER = 64 ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected.") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) print(f"[{addr}] {msg}") if(msg == DISCONNECT_MESSAGE): connected = False conn.send("test".encode(FORMAT)) conn.close() def start(): server.listen() while True: conn, adrr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, adrr)) thread.start() print(f"[ACTIVE CONNECTIONS]", {threading.active_count() - 1}) print(f"[STARTING] server is starting on {SERVER}:{PORT}") start() what is the problem: when running the django server, it starts … -
In django, can the .using('db') keyword take a variable?
Example.objects.using('db').raw() Instead of db could we have a variable that would correspond to the appropriate database? -
Cookiecutter requirements instalation problem
I'm learning Django(just started) using Django Crash Course book and for going on I have to install cookiecutter. There are a template there: gh:roygreenfeld/django-crash-starter. I activate venv, install cuckiecutter template, and when I try to install requirements, I get a bunch of errors. I have tried several templates, all gave me some errors. The example from the textbook gives this: Using cached wrapt-1.14.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (77 kB) Building wheels for collected packages: Pillow, django-allauth, ipdb, pytest-sugar, django-test-plus, factory-boy, django-coverage-plugin, termcolor Building wheel for Pillow (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mikhail/programming/exercises/python/django_crash_course/everycheese/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jj_zmz6q/Pillow/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jj_zmz6q/Pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-ipb4dz0c cwd: /tmp/pip-install-jj_zmz6q/Pillow/ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for Pillow Running setup.py clean for Pillow Building wheel for django-allauth (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mikhail/programming/exercises/python/django_crash_course/everycheese/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jj_zmz6q/django-allauth/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jj_zmz6q/django-allauth/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-_r7vlqar cwd: /tmp/pip-install-jj_zmz6q/django-allauth/ Complete output (6 lines): usage: setup.py [global_opts] … -
How to save file in creating folder when data inserto the data base django
I want to save file in automatically created folder related with Employee id_number. I add following code in models.py from django.db import models class Employee(models.Model): id_number = models.CharField(primary_key=True, null=False, blank=False, unique=True, max_length=15) full_name = models.CharField(max_length=255, null=False, blank=False) name_with_initials = models.CharField(max_length=255, null=False, blank=False) surname = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=15, null=False, blank=False) dob = models.DateField(null=False, blank=False) gender = models.CharField(max_length=10, null=False, blank=False) email = models.EmailField() address = models.CharField(max_length=255, null=False, blank=False) class EmployeeAttachments(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) cv = models.FileField(upload_to=f'employee/attachments/', max_length=100) i want to save cv file in ex:- media->employee->attachments->emp001->emp001.pdf can any one tell me how to do this in django, django-rest-framework -
Editing the 1st Row using Django Forms is not working, but working for the rest rows. How to rectify it?
I have a Django Form which has a problem. It is not editing the 1st row of the table of the database fetched in the template and working fine from 2nd rows onwards. the issue seems to be with the dynamic URL: Suppose in this HTML table :- as I hit the edit button for 1st row, no new URL is generated, i.e. same old URL say http://xxx.xx:xx/djangoapp/state_wise is returned, which just refreshes the page :- but while I hit the edit button for the 2nd row and onwards, the URL changes dynamically as http://xxx.xx:xx/djangoapp/edit_data_from_db/8086/? and the edit form appears as : the forms.py file is as: class details_to_database(forms.ModelForm): class Meta: model = GroupDetail BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('ABC', 'ABC'), ('DAMU', 'DAMU')) fields = ["unit_type", "state_name", "unit_name", "district_name", "block_name", "village_name", "village_covered", "number_of_groups", "number_of_farmers"] labels = { "unit_type":"Unit Type", "state_name":"State Name", "unit_name":"Unit Name", "district_name":"District Name", "block_name":"Block Name", "village_covered":"Village Covered (Yes/No)", "number_of_groups":"Number of groups", "number_of_farmers":"Number of farmers"} widgets = { "unit_type":forms.Select(attrs={"class":"form-control", "id":"unit_type_id"}, choices=UNIT_CATEGORIES), "state_name":forms.TextInput(attrs={"class":"form-control", "id":"state_name_id"}), "unit_name":forms.TextInput(attrs={"class":"form-control", "id":"unit_name_id"}), "district_name":forms.TextInput(attrs={"class":"form-control", "id":"district_name_id"}), "block_name":forms.TextInput(attrs={"class":"form-control", "id":"block_name_id"}), "village_name":forms.TextInput(attrs={"class":"form-control", "id":"village_name_id"}), "village_covered":forms.Select(attrs={"class":"form-control", "id":"village_covered_id"}, choices=BOOL_CHOICES), "number_of_groups":forms.NumberInput(attrs={'min': '1',"class":"form-control", "id":"number_of_groups_id"}), "number_of_farmers":forms.NumberInput(attrs={'min': '1',"class":"form-control", "id":"number_of_farmers_id"}) } The model.py file is as: BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('ABC', 'ABC'), … -
Why does gevent give "Too many open files" error during load testing?
I have a setup consisting of nginx, gunicorn, and django. All these run through docker containers. In django, when a request comes, I save image files that are sent through request. Since my code is IO bound, I wanted to use gevent, however, during load tests it gives "Error at ...[Errno 24] Too many open files:" unless i make worker-connections 2, which is too low. I've researched this error, some people suggest increasing ulimit -n, but by default the container has 1048576 limit. It doesn't allow for more. I've also tried using eventlet instead of gevent, but the error is the same. Error message Error traces back to this part: with open(path, "wb") as f: f.write(imgfile) Any suggestions? -
Image persistence issue in Heroku [duplicate]
I have deployed my Django backend in Heroku, and connected to the Heroku PostgresSQL database. However, I noticed that the images are not persistent; after a while, the images disappear. It must be noted that other features are persistent, and it is only the images that disappear. Does anyone know why this is the case? I have included the settings.py in my Django backend for reference purposes. from pathlib import Path from decouple import config import os import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # import config to anonymise secret key SECRET_KEY = config("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #ALLOWED_HOSTS = ["localhost","https://ever-green-production.herokuapp.com"] ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'stockmarket.apps.StockmarketConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'corsheaders', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', #registration endpoint 'rest_framework', 'rest_framework.authtoken', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #handling of static files 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
" Invalid or incomplete introspection result" error when i load the graphql endpoint for my django project
I have a Django project where I am using Graphql but after writing out only one mutation, the /graphql does not run properly, throwing the following error. { "message": "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was returned alongside: null.", "stack": "r@https://cdn.jsdelivr.net/npm/graphiql@1.0.3/graphiql.min.js:1:24583\nur@https://cdn.jsdelivr.net/npm/graphiql@1.0.3/graphiql.min.js:1:326896\nwindow.GraphiQL</</s/value/<@https://cdn.jsdelivr.net/npm/graphiql@1.0.3/graphiql.min.js:7:48325\n" } How can I fix this ??? Here is my main schema import graphene import accounts.schema class Query(graphene.ObjectType): pass class Mutation(accounts.schema.Mutation, graphene.ObjectType): pass schema = graphene.Schema() Here is my account schema file import graphene from graphene_django import DjangoObjectType from .models import CustomUser class CustomUserType(DjangoObjectType): class Meta: model = CustomUser class CustomUserInput(graphene.InputObjectType): full_legal_name = graphene.String(required=True) title = graphene.String(required=True) email = graphene.String(required=True) phone_number = graphene.String(required=True) physical_address = graphene.String(required=True) password = graphene.String(required=True) confirm_password = graphene.String(required=True) role = graphene.String(required=True) class CreateUser(graphene.Mutation): user = graphene.Field(CustomUserType) class Arguments: user_data = CustomUserInput(required=True) def mutate(self, info, user_data=None): user = CustomUser( email=user_data.email, full_legal_name=user_data.full_legal_name, title=user_data.title, phone_number=user_data.phone_number, physical_address=user_data.physical_address, password=user_data.password, confirm_password=user_data.confirm_password, role=user_data.role ) if user.password != user.confirm_password: raise Exception("Passwords do not match!") else: user.set_password(user_data.password) user.save() return CreateUser(user=user) class Mutation(graphene.ObjectType): create_user = CreateUser.Field() And my model.py file which I used to build out the schema. from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): TITLES = ( ('Mr', 'Mr'), … -
Display SQL Query result into a Django Form
I have a simple BookStore web page that it must return a query result that contains books information. I want to display that into a form and add checkbox before each item so the client can check the number of books they want. First Question is how I pass an sql query into a django form (Form must be a Charfield with disable value set to true so no can edit it just be able to see it it also uses the widget textarea). This is my Form.py from django.forms import ModelForm from django import forms from .models import Books class Login_Form(forms.Form): username = forms.IntegerField(label='User Name',widget=forms.TextInput, required=True) password = forms.CharField(label='Password',widget=forms.PasswordInput, required=True) class Book_L(forms.ModelForm): class Meta: model = Books fields = "__all__" This is the Model.py the model i want to display is the Books model: rom django.db import models class Admins(models.Model): adminid = models.IntegerField(db_column='AdminID', primary_key=True) # Field name made lowercase. adminlogin = models.CharField(db_column='AdminLogin', max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. usersecret = models.CharField(max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) class Meta: db_table = 'Admins' class Books(models.Model): uid = models.AutoField(db_column='UID', primary_key=True) # Field name made lowercase. bookname = models.CharField(db_column='BookName', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. author = models.CharField(db_column='Author', max_length=255, … -
sendgrid SENDGRID_ECHO_TO_STDOUT
Iam looking to use this pkg to send emails in my django app: https://github.com/sklarsa/django-sendgrid-v5 and I see the field: SENDGRID_ECHO_TO_STDOUT and the description says: will echo to stdout or any other file-like object that is passed to the backend via the stream kwarg. I literally do not get what this means. My understanding was that if I set this to True, the email WONT be delivered but will be saved as a file and will output 1 in the terminal ? However when I see this:https://simpleit.rocks/python/django/adding-email-to-django-the-easiest-way/ I think the guy manages to send emails even when this flag is set to True? Is that correct? Sorry if this is a daft quetsion - I just do not understand this flag. Should the flag be set to True or False in production? -
Send a file to a specific user from the admin page in django
I am on a django project where I want to be sending different work to each of my employees from the admin page, but no one will see other people's work, each person will see their own work in their profile page... Can anyone please assist me on what I should do... -
Getting "No module named django.core.management" inside vscode
I am running my django app in docker. I have attached this docker container to vscode. Then, I start debugging application, but manage.py, I get following error: No module named django.core.management Inside vscode's terminal, I tried following: # pip list | grep django django-annoying 0.10.4 django-bulk-update 2.2.0 django-ckeditor 5.5.0 django-codemirror2 0.2 django-crequest 2018.5.11 django-extensions 1.7.3 django-filter 1.1.0 django-formtools 1.0 django-haystack 2.4.1 django-js-asset 1.2.3 django-jsonfield 1.4.0 django-model-utils 2.5 django-redis 4.3.0 django-smtp-ssl 1.0 django-user-agents 0.4.0 djangorestframework 3.3.3 So it seem like django is installed in container's python. To double check, I tried following in vscode's terminal: # python Python 2.7.16 (default, Oct 17 2019, 07:35:32) [GCC 8.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django <module 'django' from '/usr/local/lib/python2.7/site-packages/django/__init__.pyc'> >>> django.core Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'core' Q1. Does this mean that django is installed, but somehow django.core isnt there? Also, this is what I get in vscode's terminal: # which python /usr/local/bin/python But, manage.py has this line at the top: #!/usr/bin/env python Q2. Is my app running against different python from the one I am accessing from vscode's terminal? Also the … -
{'category_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]}
I am new to django postgresql and I have been making a CRUD with Products having categories,sub categories,colors,size.When I am trying to make a new "category" the data isnt getting displayed on webpage heres the error: below is Products model below is what I have written in categories.views ,it's show function -
Why is the data on my heroku website different from data on local dev?
New to django I tried setting up a postgreSQL db and it works fine. I use Retool to access the db and I can see the data I am adding when I modify my website locally through the admin site, but data is not there when I access my 'production' website hosted on heroku. My process: I add a new model I go to myWebsite/admin I add a new entry to my website and save. I check the postgreSQL and I can see my entries I deploy my website to heroku I log in to admin I can see the model I created, but no entries. The 'production' db is using the same connection details. -
Generating all third-party Django apps endpoints with drf-yasg
Is there a way for generating all third-party apps endpoints with drf-yasg? So I have installed social_django app and want to include all URLs it provides to swagger UI My urlpatterns urlpatterns = [ re_path('admin/', admin.site.urls), re_path('', include('user.urls')), re_path(r'^$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), re_path(r'', include('social_django.urls', namespace='social')), re_path(r'accounts/', include('django.contrib.auth.urls')), ] Schema schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) Those are that defined by me, but I also want to see here /login/facebook/ , /login/google-oauth2/ etc. Or for example simple /admin/ that Django provides. How can I do this? -
navigation bar not perform well in my Django project
I had created a horizontal navigation bar on top of my page. I use code on w3school and tryied javascript snippet from stackoverflow post I found months ago. I'm using Django. I met 2 issues I can't resolve or understand. I paste my code here. One navigation.html: <div id="id_topnav" class="topnav"> <a href="{% url 'myapp:index'%}">Home</a> <a href="{% url 'myapp:help'%}">Help</a> <a href="{% url 'myapp:test'%}">Test</a> </div> I got a style.css: body { margin: 10; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: red; position: fixed; top: 0; width: 100%; } .topnav a { float: left; display: block; color: orange; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover:not(.active) { background-color: blue; color: black; } .topnav a:focus { background-color: pink; } In my home page, {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'main/style.css' %}"> {% include "myapp/navigation.html" %} ......and other lines below myapp\static\main\style.css My first issue is, when I changed colours in style.css, any colour in .topnav or .topnav a section, I didn't see changes on any of my page. After changing, I use py manage.py collectstatic to update the resource and py manage.py runserver 127.0.0.1:8000 to restart my server. I don't see any change of colour. … -
Filter field M2M in Django ORM
My models: class Tag(models.Model): tag_name = models.CharField( 'Tag Name', max_length=255, null=True ) class Book(models.Model): name = models.CharField( 'Name', max_length=255, null=True ) tag = models.ManyToManyField( 'Tag', related_name='tags', blank=True ) I wont filtering Book's model. In db i have several rows: Tag | id | name | |-----|------| | 1 |tag_1 | | 2 |tag_2 | | 3 |tag_3 | Book | id | name | tags | |-----|-------|------| | 1 |book_1 |tag_1| | 2 |book_2 |tag_2| | 3 |book_3 |tag_3| | 4 |book_4 |tag_1, tag_2, tag_3| How can i filtering book models, if i take new model Book with tag=tag_1, tag_2 and i want find in Book models all model with tag include tag_1 or tag_2. I want get queryset like this(for tag=tag_1, tag_2): [(id=1, name=book_1), (id=2, name=book_2), (id=4, name=book_4)] -
django queryset filter by list - get elements of list that are not found
Let's assume, there is a django model Data with a charfield named hash and a list of hashes called all_hashes. Now it is clear, one can use filter expression to get all objects in Data which are within the list of hashes by using the __in syntax like: all_hashes = ['45df...','ab23...', ... ] filtered_data = Data.objects.filter(hash__in=all_hashes) So if one wants to know which hashes have been found one could just do filtered_hashes = [obj.hash for obj in filtered_data] And you can get the hashes, which have not been found, like new_hashes = set(all_hashes) - set(filtered_hashes) Of course you can also directy get new_hashes by looping one by one through the list of all_hashes and individually try to retrieve a matching object from database however this sounds like it will cause a lot of queries and should be avoided. The question is - is there any more direct way to identify for which items in a list no matching object could be found - maybe something that looks like: objects_existing = Data.objects.exist(hash__in=all_hashes) => [true, false, ...]