Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
slice string after string in Django template
I have a string that looks like this "My string has two sentences. Important: Here is what I need". I'm trying to use django template filters to parse out everything after "Important:" for the above example the result would be "Here is what I need". -
Manager isn't accessible via Account instances
In using django-organizations to give my project organizations, I made a separate app for accounts. Using the code from the docs (https://django-organizations.readthedocs.io/en/latest/cookbook.html#advanced-customization-using-abstract-models) in what I assume is a basic case, I am trying to add them on the admin.py page: from accounts import models as AccountModels @admin.register(AccountModels.Account) class AccountAdmin(admin.ModelAdmin): list_display = ['slug', 'active', ] This gives an error when trying to view the list on admin page for Accounts (at http://localhost:8000/adminaccounts/account/) [ps - the add page renders, but will provide the same error on save]: AttributeError at /adminaccounts/account/ Manager isn't accessible via Account instances Looking at the error, I am not supposed to be calling it on an instance, rather only a Class. But the default admin template is rendering this page, so I am wary of editing that. Is there something I am missing related to setting up an inherited class in an admin class? (the organization-user and organization-owner both display properly adding to my confusion) This is the stack that shows that it is trying to access an instance (but I can't find in the stack trace which line is the error, only that it is in the {{content}} part of the template block): /Users/me/.virtualenvs/myFirst/lib/python3.6/site-packages/django/contrib/admin/utils.py in lookup_field attr … -
autocompleteselect and foreignkey
I am a beginner under django, I currently work on an application to record births the father key of the birth class points to the registration table that records fathers and mothers in my form.py file, the father field is an autoselectfield. And that's my problem: the autoselectfield returns an id while the father field must point to an object of type registration how can i return the object linked to the id. as long as the father field does not point to an object I will not be able to register a new birth in the base Thank you in advance my view.py class EntityCreateView(CreateView): def form_invalid(self, form, error_msg="Erreur lors de la sauvegarde."): messages.error(self.request, self.request.POST) return super(EntityCreateView, self).form_invalid(form) def form_valid(self, form, success_msg="Enregistrement réussi."): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.instance.created_by = self.request.user messages.success(self.request, success_msg) #father_id = form.cleaned_data['father'] form.father = Registration.objects.get(id=form.father) return super(EntityCreateView, self).form_valid(form) class BirthCreateView(EntityCreateView): template_name = 'eregister/birth_detail.html' model = Birth form_class = BirthForm def get_initial(self): if 'from_external_page' in self.kwargs and 'birth_post_form' in self.request.POST: # If we added a birth or a person, we want to restore the initial form birth_post_form = self.request.session['birth_post_form'] del self.request.session['birth_post_form'] return birth_post_form … -
Django 2.0 Annotate an Annotation Queryset
I have a set of inspectors, each with a number of projects that they work on, and get paid for based on their pay_rate. My goal is to roll up the average pay rate of inspectors based on what company they are working for. If an inspector works on more than one job, I want to use his average pay_rate. The following code SHOULD do this, but it does not. i = InspectorProject.objects.all() uniques = i.order_by('inspector', 'project__prime_consultant__name').values('inspector', 'project__prime_consultant__name')\ .annotate(pay_rate=Avg('pay_rate'), bill_rate=Avg('bill_rate')) # the above code works as expected. here's where it gets fishy. companies = uniques.order_by(.order_by('project__prime_consultant__name') .values('project__prime_consultant__name')\ .annotate(avg_pay=Avg('pay_rate'), avg_bill=Avg('bill_rate'))\ The last line there gives me a keyError: 'pay_rate' on the annotation. What this means to me is that the second annotation is not recognizing the attribute/column/field that is created by the first annotation. 1) Why? 2) How do I get around this? I include the bill_rate to be thorough, but the problem is clearly in the second annotation's inability to recognize the first's generated field. Thanks in advance. -
Custom form for django registration password reset not showing in template
I want to make a custom password reset form using the original django registration one as a base that contains recaptcha in it. Here is the relevant code: forms.py from django.contrib.auth.forms import PasswordResetForm from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget class CaptchaPasswodResetForm(PasswordResetForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) urls.py from django.conf.urls import url from landingpage.forms import CaptchaPasswodResetForm from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^password-reset/$', auth_views.password_reset, {'password_reset_form': CaptchaPasswodResetForm}, name='new_password_reset'), url(r'^password-reset-done/$', auth_views.password_reset_done, name='password_reset_done'), ] password_reset_form.html {% extends "base.html" %} {% load i18n %} {% load recaptcha2 %} {% block head %} {% recaptcha_init %} {% endblock %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ password_reset_form.as_p}} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% endblock %} What should happen is that the fields for the form show up in the template due to the tag I added to the url. However, instead the template basically just ignores it when I put the tag in it. When I use 'form', it uses the default password reset form. Is there something I'm missing or doing wrong? -
Django Rest Framework in existing project
I followed the basic steps of installing a django rest framework and add it to the settings.py but it won't run and gives error ModuleNotFoundError: No module named 'rest_framework' Is it that I need to create a new project? I also tried installing by activating and deactivating virtual environment but it is not working anyway -
How to send GET request to API
Summary: I have a job board, a user searches a zip code and all the jobs matching that zip code are displayed, I am trying to add a feature that lets you see jobs within a certain mile radius of that zip code. There is a web API ( www.zipcodeapi.com ) that does these calculations and returns zip codes within the specified radius, I am just unsure how to use it. Using www.zipcodeapi.com , you enter a zip code and a distance and it returns all zip codes within this distance. The format for API request is as follows: https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units>, so if a user enters zip code '10566' and a distance of 5 miles, the format would be https://www.zipcodeapi.com/rest/<api_key>/radius.json/10566/5/miles and this would return: { "zip_codes": [ { "zip_code": "10521", "distance": 4.998, "city": "Croton On Hudson", "state": "NY" }, { "zip_code": "10548", "distance": 3.137, "city": "Montrose", "state": "NY" } #etc... ] } My question is how do I send a GET request to the API using django? I have the user searched zip code stored in zip = request.GET.get('zip') and the mile radius stored in mile_radius = request.GET['mile_radius']. How can I incorporate those two values in their respective spots in https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units> … -
Creating a tree in json with python from model objects
I have a storage model from which I need to get objects in the form of a tree and do it like this: if model == 'Storage': if method == 'Read': try: list_sr = [] storage = Storage.objects.all() for item_sr in list(storage): dict_sr = {} if item_sr.id_parent_id == 0: dict_sr['text'] = item_sr.name dict_sr['id'] = str(item_sr.id) dict_sr['expanded'] = True if item_sr.id_parent_id != 0: dict_sr['children'] = [{'text:' + item_sr.name + ", leaf = True"}] list_sr.append(dict_sr) result = {'expanded': 'true', 'text': 'Storage', 'children': list_sr} jsonFormat = json.dumps(result, indent=4, sort_keys=True, default=str) print('Look' + str(jsonFormat)) ... Output of the dictionary data the result displays the following form: { "children": [ { "expanded": true, "id": "9", "text": "Title 1" }, { "children": [ "{'text:Test 1, leaf = True'}" ] }, { "children": [ "{'text:Test 2, leaf = True'}" ] }, { "expanded": true, "id": "12", "text": "Title 2" }, { "children": [ "{'text:Test 3, leaf = True'}" ] }, { "children": [ "{'text:Test 4, leaf = True'}" ] } ], "expanded": "true", "text": "Storage" } I need to have the data in this form: expanded: true, text: "Storage", children:[ { text: "Title 1", id: '9', expanded: true, children: [ { text: "Test 1", leaf: true , … -
How to fix importError: Could not import settings Django?
I facing this problem right now, and have no clue on how to resolve it. My project was originally on mac, then I copied the project and moved it to ubuntu. I created new virtual environment and installed all the requirements. When I ran python manage.py migrate, I got and error saying importError: Could not import settings. Here is the traceback I got: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/edward/.virtualenvs/crowdview-policies/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/edward/.virtualenvs/crowdview-policies/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/edward/.virtualenvs/crowdview-policies/local/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in __getattr__ self._setup(name) File "/home/edward/.virtualenvs/crowdview-policies/local/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/home/edward/.virtualenvs/crowdview-policies/local/lib/python2.7/site-packages/django/conf/__init__.py", line 98, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'crowdview_config_api.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named crowdview_config_api.settings I tried to look for crowdview_config_api.settings in my froget, but found no mentioning of it. What can be causing this issue? Note: I have another Django project on ubuntu, but it runs in a separate virtual environment. That second project does have that crowdview_config_api.settings mentioning in its manage.py file. -
Django - Update field value after 7 days with Celery
My today Question is how i can change value of field after 7 days using Celery My models: class Episode(models.Model): availability_free_users = models.DateTimeField(default=datetime.now()+timedelta(days=7)) availability = models.BooleanField(default=False) So i want to update availability to true if today date (only date not hour) == availability_free_users -
Populate django template with files
Django can comfortably populate an HTML template with data from models in a database - but I've recently come across a few scenarios where I would like to populate the template with other files' data. In this case, I'm trying to generate my own documentation for a project. Initially, I just wrote it all into one big file, but this is obviously tedious to handle, and quite repetitive. Instead, I would be neat to have some sort of filesystem, where each folder is a section in the documentation, and each subfolder a subsection, etc etc. Can Django do this? I know that one way to do this is to link the files to database objects, then iterate through these objects in the template. I'm not keen on this, because I want any changes/new documentation files to immediately show in the page, without having to go edit around in the db. The only other approach I can think of is to navigate through the folders, adding their contents to page context when a page is loaded. This seems too hacky to me, and will create problems with encoded HTML in the file contents, I imagine. That being said: if there is … -
How to sort the column names according to a single row in a database wish stores priority values
I have this table that i want to sort the column names and get them in django according to page priorities , my table is : --------------------------------- Type | Home | Schedule | AddUser --------------------------------- Admin | 2 | 1 | 3 --------------------------------- I want to get in django as a collection Schedule , Home , AddUser how can i do it in an easy way? -
How can i update the django model fields in real-time?
I want to get users currently playing song information and printing to web page(I can print song to console). But I dont have any idea to how to do it. Thanks. Github Code -
Sending data to django channels groups via django views
So I have the following: views.py def alarm(request): layer = get_channel_layer() async_to_sync(layer.group_send)('events', { 'type': 'events.alarm', 'content': 'triggered' }) return HttpResponse('<p>Done</p>') consumers.py class EventConsumer(JsonWebsocketConsumer): def connect(self): print('inside EventConsumer connect()') async_to_sync(self.channel_layer.group_add)( 'events', self.channel_name ) self.accept() def disconnect(self, close_code): print('inside EventConsumer disconnect()') print("Closed websocket with code: ", close_code) async_to_sync(self.channel_layer.group_discard)( 'events', self.channel_name ) self.close() def receive_json(self, content, **kwargs): print('inside EventConsumer receive_json()') print("Received event: {}".format(content)) self.send_json(content) def events_alarm(self, event): print('inside EventConsumer events_alarm()') self.send_json( { 'type': 'events.alarm', 'content': event['content'] } ) in routing.py application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns, ) ) ), }) where websocket_urlpatterns is websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), url(r'^ws/event/$', consumers.EventConsumer), ] urls.py urlpatterns = [ url(r'^alarm/$', alarm, name='alarm'), ] when I call /alarm/ , only the HTTP request is made and the message is not sent to the websocket The following are the logs: [2018/09/26 18:59:12] HTTP GET /alarm/ 200 [0.07, 127.0.0.1:60124] My intention is to make django view send to a group (use case would be for a server to send notification to all connected members in the group). What setting am I missing here. I am running django channels 2.1.3 with redis as backend. The CHANNELS_LAYERS etc. have all been setup. Reference Links: sending messages to groups in django … -
Django app takes only a part of requested URL
I have a strange issue in my project. When my AJAX sends POST request to uri '/api/login/', Django goes to '/login/' uri. When I try to get a page '/api/login/' using GET method, Django goes to function, that is relevant to '/api/login/'. I can't understand where is a problem. Why POST methods don't see '/api/' substring in the request URL. Do you know where a problem can be? This bug is only on one server. On localhost and on another hosting it works properly. Thank you. -
Django form not displaying date widget
I'm having a hard time getting a date widget to appear in django. Keeping in mind that the project is meant to have zero access to the internet, this is what I have: forms.py: class CreateNewPatient(forms.ModelForm): class Meta: model = models.PatientInfo fields = ['first_name', 'nickname','last_name', 'date_of_birth', 'school_grade', 'sex', 'school'] widgets = { 'date_of_birth' : forms.DateInput(attrs={'class':'datepicker'}), } template with form: {% extends 'base_layout.html' %} {% load bootstrap4 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% block content %} <!--Form Container--> <div class="container"> <form action="{% url 'patientRecords:new_patient' %}" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> </div> {% endblock %} The form is being generated using a bootstrap 4 plugin. That't why there is some weird syntax to generate the form. javascript: <script> $(function () { $(".datepicker").datepicker({ changeMonth: true, changeYear: true, changeDay: true, yearRange: "1990:2030", }); }); </script> I have the javascript placed in the head tag of the base layout template. The .datepicker class tag shows up correctly in the source code on chrome, but no form is generated. I still just … -
MongoDB and relational-database on Django 2.1 and python 3.6
I have been looking all over how to use a relational-database and a MongoDB while using Django 2.1. I tried following Django documentation for multiple databases but changing it out to MongoDB, just like in this question . The problem im facing is when I use the django-mongodb-engine tutorial it uninstalls Django 2.1 and installs Django 1.511 which I can not use because I running processes with Celery 4. I have tried to just install just the Django toolbox with pip install git+https://github.com/django-nonrel/djangotoolbox and MongoDb with pip install git+https://github.com/django-nonrel/mongodb-engine but I end up getting errors when I try to run it. I also know you I had to install a package to get MongoDB to work with python 3 which I did with pip install django-mongodb-engine-py3 when I try to migrate it gives me this error: django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My main question is, has one used both types of databases along with the newer version of Django, and how did you get them all the work with each other? Thank you for your help. -
Adding class to images and videos with Summernote widget in Django 2
I'm looking for a way to add a class, which I could modify in css, to images and videos in both editor forms and html templates displaying the form. I'm using the SummernoteInplaceWidget() from django-summernote package and it's working fine except this feature. I use bootstrap 4 with it. Any ideas? Thanks in advance. -
how to get the object data by a single function in django on the template
****** I want to build a study material content sharing website, here is I am sharing a sample template for the same, All models are related by a Foreign key, I want to get these all models data into Template using a single function.. please share solutions for the same..****** class Institute(models.Model): institute_name = models.CharField(max_length=100, null=True, blank=True) institute_logo = models.FileField(upload_to='pic',null=True, blank=True) institute_code = models.IntegerField(blank=True, null=True) def __str__(self): return self.institute_name SEM_NO_CHOICES = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'), ('11', '11'), ('12', '12') ) COURSE_DURATION_CHOICES = ('sem', 'Semester'), ('year', 'Year') ) YEAR_NO_CHOICES = ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4') ) class Course(models.Model): course_name = models.CharField(max_length=100, null=True, blank=True) course_code = models.IntegerField(null=True, blank=True) institute = models.ForeignKey(Institute, on_delete=models.CASCADE, null=True, blank=True) duration = models.CharField(choices=COURSE_DURATION_CHOICES, max_length = 10, null=True, blank=True, default="") sem_no = models.CharField(choices = SEM_NO_CHOICES, max_length = 10, blank = True, null = True, default="") year_no = models.CharField(choices = YEAR_NO_CHOICES, max_length = 10, blank = True, null = True, default = "") content = models.TextField(null=True, blank=True) is_live = models.BooleanField(default=True) def __str__(self): return '%s' %(self.course_name) class Branch(models.Model): branch_name = models.CharField(max_length=50, null=True, blank=True) branch_code = models.IntegerField(null=True, blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, … -
Django: Access to re_path-variables in template
How can I access to variables in "re_path" (e.g. "username") in template? example: re_path(r'^bio/(?P<username>\w+)/$', views.bio, name='bio'), -
django issue while running manage.py runserver
I have made changes in View.py and URL.py file and getting " Unresolved reference 'Django' less... (Ctrl+F1) Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. is it serious error -
Nested views in Rest Framework
I have a rest API app with users and books with this URL structure (without routers): urlpatterns = [ path('', UserList.as_view(), name="user-list"), path('<uuid:id>/', UserDetail.as_view(), name="user-detail"), path('<uuid:id>/books/', BookList.as_view(), name="book-list"), path('<uuid:id>/books/<int:book_id>/', BookDetail.as_view(), name="book-detail"), ] Serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): books = serializers.HyperlinkedRelatedField( many = True, queryset = Book.objects.all(), view_name = "book-detail", ) And generic views: class BookList(generics.ListAPIView): serializer_class = BookSerializer queryset = Book.objects.all() lookup_field = 'book_id' class BookDetail(generics.RetrieveAPIView): serializer_class = BookSerializer queryset = Book.objects.all() lookup_field = 'book_id' This doesn't work - I get the error: Could not resolve URL for hyperlinked relationship using view name "book-detail" I have tried changing the lookup_field and view-name, but I'm not even sure how to troubleshoot this issue. I looked into drf-nested-routers, but I'm hoping to find a solution without switching to routers if at all possible. -
in Django turtoring book chapter 3, there is {% if latest_question_list %} ,but I get none
{% if latest_question_list %} In my index.html page,I input code as it says in the book. But it shows me latest_question_list in none, I didnt get anything as display. Can someone help me to answer why? Thank you. -
Pulling tags used by a specific Content Type
I am building a custom tagging system on top of Django's contenttypes framework. My models look as follows: class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(verbose_name=_("Slug"), max_length=100) photo = models.ImageField(upload_to="tags", blank=True) status = models.CharField( max_length=10, choices=TAG_STATUSES, default=TAG_STATUS_UNREVIEWED ) language = models.CharField( max_length=7, choices=settings.LANGUAGES, default="en" ) # 7 for zh-hant, for example creator = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, default="4c44d45e-6d25-41e8-846e-2a417822417b", ) site = models.ForeignKey(Site, on_delete=models.CASCADE) parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE ) # null indicates root category usages = models.ManyToManyField( ContentType, through="TagUsage" ) # Tells us which sections are using the tag. We don't want to display 'Forums' tags as tags in 'Tickets', for example, unless they are actually used in both places def __str__(self): return self.slug class Meta: unique_together = ("slug", "site") class TagUsage(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) counter = models.BigIntegerField() # How many items using the tag for the given content type (instead of counting on every request) class TaggedItem(models.Model): # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField() content_object = GenericForeignKey("content_type", "object_id") tag = models.ForeignKey(Tag, on_delete=models.CASCADE) So my question, how do I list the tags that are used in a specific content type? -
Django Admin --Bulk Staff User Creation/Import from CSV file
I have a question. I have to import all of the users that will be allowed in my Django Admin app from an excel/csv file. Can someone please advice, guide me how i can implement this thing in Django Admin Interface. There is a script i can use? All of them will be allowed to login to my Django app and all of them will be automatically made staff users.