Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML is not applying CSS
I am very new to HTML and CSS. I am trying to link my CSS and JS file to my HTML file, but it is not working. I have looked at many other Stack Overflow questions & answers on this problem, and none of the solutions seemed to have worked. Is there some sort of typo/problem that I am overlooking? website |home |_static |_home |_styles.css |_main.js |_templates |_home |_base.html I have tried moving styles.css around into different folders, using STATIC_DIR, STATIC_ROOT This is the top of my base.html file <!DOCTYPE html> <html lang="en"> <head> {% load static %} <link rel="stylesheet" href="{% static '../home/styles.css' %}"> <script src="{% static 'home/main.js' %}"></script> <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet"> <meta charset="UTF-8"> <title>Title</title> </head> Here are the error messages in Command Prompt: [05/Jun/2019 13:58:15] "GET /home/ HTTP/1.1" 200 1014 Not Found: /home/styles.css [05/Jun/2019 13:58:15] "GET /static/home/main.js HTTP/1.1" 404 1660 [05/Jun/2019 13:58:15] "GET /home/styles.css HTTP/1.1" 404 2304 -
How can I set some initial properties on a ModelAdmin class based on request?
I have this class: class PersonAdmin(admin.ModelAdmin): def get_queryset(self, request): if request.user.is_superuser: .... def delete_queryset(self, request): if request.user.is_superuser: .... basically I keep repeating if request.user.is_superuser. What I want is to set an initial flag so that I can keep reusing that. Why? Because the logic could change to if request.user.is_superuser or ... and I don't want to have to repeat that everywhere. I looked at __init__() and could not really see a way to do what I want. -
Django: How to Create a Dependent Dropdown List
I want to create dependent drop-down menus, but I am unsure as to how to best implement the solution. I am trying to implement the solution presented here:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html Additionally, I would like to implement this solution without creating models as the database I am using is not supported by Django. Despite the work I have already completed, I am not returning any data after selecting a value in the first drop-down menu. Please let me know if there is any other information I may provide to better illustrate my problem. Additionally, I would like the query to be: "new_opportunity?selected_company=selected_company" I do not have any prior experience with AJAX so I am unsure if I am passing the correct URL to my view. Models.py class Location(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Company(models.Model): company = models.CharField(max_length=30) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name Forms.py class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('company', 'location') def __init__(self, *args, **kwargs): self.__init__(*args, **kwargs) self.fields['location'].queryset = Location.objects.none() if 'selected_company' in self.data: try: company = int(self.data.get('selected_company')) self.fields['location'].queryset = Location.objects.filter(company=company) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['location'].queryset = self.instance.company.location_set.order_by('name') … -
How to setup a new ubuntu server with an old django code which already has its migration files?
I have a completely working in-production Django code running on ubuntu server. For some reasons, I have to move all that code to a new server. I have managed with the new ec2 instance n all, and have git cloned my repo to this server. What to do now with the unapplied changes/migrations(Its showing few changes even though I havent changed anything on the old code)? Do I have to delete all migrations and recreate them all? Or just run python makemigrations with the old code. Running this is showing things like: Did you rename schoolpoint.near_distance_points to schoolpoint.first_born_child_points (a IntegerField)? [y/N] y Did you rename schoolmodel.is_hostel to schoolmodel.collab (a BooleanField)? [y/N] Did you rename schoolmodel.monthly_fee to schoolmodel.featured_view_count (a IntegerField)? [y/N] y You are trying to add a non-nullable field 'receipt_id' to formreceiptmodel without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Many of these are occurring. Shall I go find them manually from the code whether it is changed or … -
Reverse for 'set_language' not found. 'set_language' is not a valid view function or pattern name
Please help me! I add multilanguage to my project deploy my django project on Ubuntu but it throw error: Reverse for 'set_language' not found. 'set_language' is not a valid view function or pattern name. But on my localhost all work fine and before that everything worked fine. My Form: <form class="lang-form" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language" onChange="this.form.submit();"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option class="decorated" value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %}> {% if lang.0 == 'uk' %} ua {% else %} {{ lang.0 }} {% endif %} </option> {% endfor %} </select> </form> My urls.py: urlpatterns = [ path('admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ]\ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( url(r'^$', views.index, name='index'), ) -
how to change boolean value given in generics view?
I want to change the default value(false) to true when the url is triggered when the user enter 'http://127.0.0.1:8000/api/message/read/2' I want that the message with id 2 will be change its isRead value to True. Model `` class Message(models.Model): message = models.TextField(max_length=5000) isRead = models.BooleanField('read status', default=False) `` urls.py `` path('message/read/<int:pk>/', ReadMessageView.as_view(), name='read_already'), `` views.py- (not sure what to do here...) `` class ReadMessageView(ListCreateAPIView): serializer_class = MessageReadSerializer `` -
How to write a v-for on django?
I am making a page with django, using Bootstrap Vue and Vuex as a store, and in a part of an html I need to use a v-for to iterate over data on my Vue instance, but none of the ways I tried the v-for gives me a result. I am working inside a <div id="myVue">, and I added delimiters to be [[]] on the Vue instance, so I can access to the data like [[myData]]. Some ways I have tried to do the v-for are <b-list-group v-for="itemName in myFun"> [[itemName]] {{itemName}} itemName </b-list-group> And none of these work. myFun is a computed property that returns the array that I want to iterate over. I know that this property works because I can safely use it outside the v-for by using [[myFun]] and it shows the entire array. The information of the Vue instance is located on a Vuex store, so the computed properties access to the info like computed: { tests(){ return this.$store.state.test; }, } I would like some help to know how to build a v-for that works with Django as I dont know what the problem is. -
FOR OR statement in django template
I want to minimize my code in my template because the items i would like to display are many. The variables to output are the same and im using the same template. The details are below i tried for or statement but the error i get is 'for' statements should use the format 'for x in y': for item in (shoe_list or cup_list) This is the original code {% extends 'base_generic.html' %} {% load static %} {% block content %} <body> <h1 class="titleheadline"> List of items</h1> {% if shoe_list %} {% for item in shoe_list %} <td>{{req.colour}}</td> <td>{{req.size}}</td> <td>{{req.price}}</td> {% endfor %} {% elif support_list %} {% for item in cup_list %} <td>{{req.colour}}</td> <td>{{req.size}}</td> <td>{{req.price}}</td> {% endfor %} {% else %} <p>There are none in stock.</p> {% endif %} </body> {% endblock %} The below are the changes i made which is not working {% extends 'base_generic.html' %} {% load static %} {% block content %} <body> <h1 class="titleheadline"> List of items</h1> {% if shoe_list or cup_list %} {% for item in (shoe_list or cup_list) %} <td>{{req.colour}}</td> <td>{{req.size}}</td> <td>{{req.price}}</td> {% endfor %} {% else %} <p>There are none in stock.</p> {% endif %} </body> {% endblock %} I expect to … -
Fire a function when a user close the website or inactive in django
I am coding a Django website, in which some files are downloaded and shown to the user. Right now I want to know how to delete all these files if a user close the website or inactive for a certain amount of time(Can django time every connection from the user and know if inactive?). So basically I want to know how to call a function in view.py if my Django website is closed/inactive. -
DRF Serializer Validate data in list with context
I am working on a serializer for PATCH request. The request data will be of this format, [{"id":1, quantity:1}, {"id":2, "quantity":1}] I have created a list serializer and I want to validate every object in the list based on the current value of quantity in the database. I have a hacky way to do this, but I would like to know what is the right way. I have created a List serializer and overriding the update method that will loop on the validated data and then make DB queries. class MultipleProductSerializer(serializers.ListSerializer): def update(self, some_business_logic_parameters): for data in self.validated_data: # <- here all the field validation is done # Here I need to do some more validation based on the context of existing value in the database id = data.get('id') product = Product.objects.get(id=id) if data.get('quantity') > product.quantity: raise serializer.ValidationError("error message") The above part works, but I would like to know if I can do it something like this, class MultipleProductSerializer(serializers.ListSerializer): def update(self, some_business_logic_parameters): for data in self.validated_data: if self.validated_data.is_valid(): #<- the validate function should do the DB query and raise exceptions ...update -
how to save a dictionary in the database with Django
how to save a dictionary in the database with Django like: dict = { "me": 10, "You": 9 } ratings = Rating(dict) ratings.save() -
Django search form configuration
I am implementing a search function. I can get it to work fine if I just do an 'if search' in each view and render it on each page but I know there is a better way. I want the search submit button to render a results page. I can see the search request in the URL but why is my search function not being called? I have tried moving the 'action' attribute from the form class to the button class to the form control class. I have tried replacing the action attribute with an href attribute. It does not seem to run my function. path('results/', views.search, name='search'), def search(request): print('here!') eqs = Equipment.objects.all() locs = Location.objects.all() if 'search' in request.GET: search_term = self.request.GET['search'] # searching = Equipment.objects.filter(name__icontains=search_term) searching = sorted( chain(eqs, locs) ) context['search_term'] = search_term context['searching'] = searching return render( request, 'results.html', context = { 'search_term': search_term, 'searching': searchin, } ) <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search"> <button class="btn btn-outline-success my-2 my-sm-0 search-button" role="button" type="submit">Search</button> </form>''' I am not getting any errors, the search field is being captured, but I just stay on the page and the function does … -
Translate a date in the python source in django
How can I translate a date in my views.py? If I try to translate it with gettext it returns me this error: an integer is required (got type str). For translating a date i mean for example from english version (May 30, 2019) to italian one (30 Maggio 2019). I've to return the date in a json response. This is my code: from django.utils.translation import gettext as _ ... @AutoLanguage #It's a middleware that enables i18n date = datetime.date.today() date_translated = _(date) return JsonResponse({'date': date_translated}) -
django-cron, new task every minutes
I create an admin panel for the app we are doing with friends. The aim of django-cron is to write in django database, the number of users and any other data every minutes, to do later some graph. django project is : AdminPanel django app is : blog (no link with what I do, that's the name of tutorial I followed) Settings.py (in AdminPanel) ''' INSTALLED_APPS = [ ... 'django_crontab', ... ] CRONJOBS = [ ('*/1 * * * *', 'AdminPanel.cron.my_scheduled_job'), ('*/1 * * * *', 'blog.cron.Test'), ] ''' crontab -l */1 * * * * /usr/bin/python3 /var/www/AdminPanel/manage.py crontab run f558a935e2e04f99062097b9cbb79614 # django-cronjobs for AdminPanel */1 * * * * /usr/bin/python3 /var/www/AdminPanel/manage.py crontab run 61396363f746a6626e0820bd233c9664 # django-cronjobs for AdminPanel In AdminPanel/cron.py (1st test) import os def my_scheduled_job(): os.system("mkdir HELLO") //doest not work In blog/cron.py (2nd test) from .models import Stat def Test(): Stat.objects.create(users=69, data=42) //does not work, try to create a new entry every minutes and I display it in my adminPanel. I don't know what to do ... Thank you ! -
Understanding Django/REST/JS code functionality
I have the following code in my website: <tr onclick="editUsers(29)" data-id="29"> editUsers: function editUsers(id) { loadUsers(false, id, showUsers, true); } loadUsers: function loadUsers(insert, id, func_call, html_form) { var data = insert ? {insert: true} : {} if (html_form) data.html_form = true; $.ajax({ type: 'GET', url: '/rest/user/' + id + '/', data: data }) .done(function (data) { func_call(data, insert, id); }) .fail(function () { }); } When I click on the row, it should open an interface to edit the selected row/user, but nothing happens. I do get a reply in the console, which looks like it should work, but it doesn't. Can someone explain why it doesn't work? The reply in question:"GET /rest/user/29/?html_form=true HTTP/1.1" 200 3170 I have the same functionality elsewhere in my code, which adds a new user: function addUsers() { loadUsers(true, 0, showUsers, true); } <div class="btn btn-primary pull-right" onclick="addUsers()">Add User</div> The above doesn't work, editing the user doesn't either. -
CORS not working even after configuring using django-cors-middleware
I have configured cors and even after following all the steps, it's still throwing the CORS error in browser (Chrome). I have installed cors using pip install django-cors-middleware. Cofigured in settings. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] at the end of the settings file I have allowed cors to all. CORS_ORIGIN_ALLOW_ALL = True I even tried this ALLOWED_HOSTS = ['localhost', '127.0.0.1'] Where is the configuration missing? My django version is 1.11 -
Django - LoginView: 'AnonymousUser' object has no attribute '_meta'
I want to use Djangos' built-in LoginView. It works fine until I login a user with a correct password (If the password is wrong it works). Then I get this error: 'AnonymousUser' object has no attribute '_meta' I already added AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] to my settings.py and I looked at Django login AttributeError: 'AnonymousUser' object has no attribute '_meta' and on other webpages but they couldn't help me. -
queryset filtering via a list of query values
A beginner django question... Here's a JSON response... "data": [ { "type": "Subject", "id": "0", "attributes": { "created": "2019-01-01T00:00:00Z", "modified": "2019-01-01T00:00:00Z", "subject_code": "A&H", "subject_name": "AH", "subject_short_name": "A & HUM" }, "relationships": { "organization": { "data": { "type": "Organization", "id": "61" } }, "created_user": { "data": null }, "last_updated_user": { "data": null } }, "links": { "self": "http://localhost:8001/v1/subject_owner/0" } }, The above response is coming from a serializer queryset = Subject.objects.all() I have a query which is http://localhost:8001/v1/subject_owner?owner_ids=62,63 So, how do we write a filtering condition for the owner_ids as a list? The response should have only the results where the owner_ids match organization. I have tried few... queryset.filter(organization__in=[owner_id_list]) and queryset.filter(organization=owner_id_list) and obviously they don't work. Any help will be appreciated. -
How can display the label of non-editable fields in django template
I have this field in my model: created_date = models.DateTimeField(null=True, blank=True,editable=False, verbose_name=_("Something to show... ")) In accordance with this document ,I show the value of this field by: form.instance.created_date I see these links: 1,2,3,4 and this docucment of django. But none of them talk about showing the label (Or verbos_name) of non-editable fields in template. Also I test these possible modes: 1. form.instance.created_date.label_tag 2. form.instance.created_date.label 3. form.instance.created_date.name 4. form.instance.created_date.verbos_name ... So ,how can I do this? -
How to set default DateField value as current date?
I am working on a project where a user can enter the date and also can leave the field empty. I am using Abstract User for storing the date using DateField. However when user leaves the field empty, it does not store current date as value but remains empty. models.py import datetime class CustomUser(AbstractUser): date_of_joining = models.DateField(default=datetime.date.today,blank=True,null=True) -
Django Admin Create Form Inline OneToOne
I have the following model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_password_reset = models.DateTimeField(auto_now_add=True) needs_password_reset = models.BooleanField(default=True) image_url = models.URLField(max_length=500, default=None, null=True, blank=True) I am trying to inline this into the admin. I have the following: class UserProfileInline(admin.StackedInline): """User profile inline.""" model = Profile can_delete = False verbose_name_plural = "Profile" class CustomUserCreationForm(UserCreationForm): """Create user form.""" class Meta: model = User fields = ("username", "first_name", "last_name", "email") class CustomUserAdmin(UserAdmin): """Custom user admin.""" add_form = CustomUserCreationForm inlines = (UserProfileInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) This is working fine up to a point; when I go to create user, I can see the inlined profile information. However, when I try to submit the form I get the following error: psycopg2.errors.NotNullViolation: null value in column "user_id" violates not-null constraint Why is the user_id field not getting populated in the inline form? How can I set this attribute to the id of the user created by the form? -
CSS doesn’t work in django site-admin on server
CSS doesn’t work on pythonanywhere server but work properly on local host Admin css files are empty on pythonanywhere server I tried change DEBUG = True/False was changing settings.py PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static'), STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') # пустая папка, сюда будет собирать статику collectstatic MEDIA_URL = '/media/' But doesn’t help -
How add to attributes to model
I have a model where I want to do some procesing and append an attribute before sending it off as json. I've tried to just modify as such: client = Client.objects.all() and then client.newAttribute but that didn't work as it wasn't passed in my json with: return json.dumps(clients, cls=ExtendedEncoder) where clients is a list of client and ExtendedEncoder is class ExtendedEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, Model): return model_to_dict(o) return super().default(o) I am currently trying something new where my model is class Client(models.Model): my_id = models.CharField(max_length=500, unique=True) name = models.CharField(max_length=500) last_update = models.DateField(null=True, blank=True) friend_1 = models.ForeignKey( "self", related_name="friend_1a", on_delete=models.CASCADE, to_field="my_id", null=True, blank=True, ) friend_2 = models.ForeignKey( "self", related_name="friend_2a", on_delete=models.CASCADE, to_field="my_id", null=True, blank=True, ) def _get_time_since_last_update(self): today = date.today() if self.last_update is None: self.last_update = today return str((today - self.last_update).days) time_since_last_update = property(_get_time_since_last_update) but this still isn't getting returned in my json. -
add/remove products to favorites in django
I'm creating a project on mobile comparison and i'm using web-scraping for getting the mobile's data and directly rendering it on web-browser without creating any model an saving. i want to create add/remove favorite functionality. when user click on the heart icon, its should be added as favourite. but i do not know how to do this without having model. please help me to solve it. thanks in advance. -
Failed lookup for key [base_template_name]
django.template.base.VariableDoesNotExist: Failed lookup for key [base_template_name] in [{'False': False, 'None': None, 'True': True}, {'STATIC_URL': 'https://proevent-s3.s3.amazonaws.com/static/'}] COMPRESS_ENABLED = True STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) COMPRESS_ENABLED = True # add filters COMPRESS_CSS_FILTERS = [ 'compressor.filters.cssmin.CSSMinFilter' ] COMPRESS_JS_FILTERS = [ 'compressor.filters.jsmin.JSMinFilter' ]