Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-CMS - 'module' object has no attribute 'allowed_elements'
I am following the latest Django-CMS tutorial to install it. After installation, upon trying to create my first page, I get the following error: 'module' object has no attribute 'allowed_elements' Here you can find the entire traceback. And the versions I am using: Django Version: 1.11.16 Python Version: 2.7.15 Django-CMS Version: 3.5.2 -
Transforming a queryset to get the most recent entry, per name
My data looks like this: class Entry(models.Model): name = models.CharField(max_length=100) date = models.DateField(auto_now_add=True) size = models.FloatField(null=True) If I do: qs = Entry.objects.all() I get a queryset with all entries. How would I transform that queryset to get another queryset with the most recent entry per name? -
Django taggit add() in model method not working
I am trying to customize django-taggit and use it in a method within a model. Here is the code: class MyTag(TagBase): pass class MyTagItem(GenericTaggedItemBase): tag = models.ForeignKey(MyTag) class MyModel(models.Model): text = models.TextField() tags = TaggableManager(through=MyTagItem) def save(self, *args, **kwargs): super(MyModel, self).save() self.add_tags() def add_tags(self): _tags = text.split(',') self.tags.add(*_tags) The behavior is that: the tags will be saved to MyTag table, but MyTagItem through table is always null. Not sure where I missed, but it looks like self.add_tags() actually cleared the tags all the time. Any help is appreciated. -
Build an image processing server with python
I want to send a image via app to a server and get some JSON back. The image processing should be done by python algorithms. During my research in found Django, but I really don't know how to realize it with this framework. Because I'm new in backend programming I really don't know if it is better to user Websockets or another solution? The idea is to automatically receive to the client after he sends an image. Best Regards Robert -
Add one or multiple forms sitewide and submit using Ajax
I have one form that appear site wide in footer. I submit this form using Ajax. On some pages can exist also other forms. Usually I use a CBV for create and update. class CreateItem(CreateView): model = Item form_class = ItemForm <form action="" method="post"> {% csrf_token %} {{ form.name }} In this case, I can't use the above. For view on submit, I have: class FooterAddView(View): def post(self, request): if request.is_ajax(): ..... I need some help on the token for Ajax, and load/pass the form sitewide. -
what is the method or class that is generating access token and refresh token in django oauth2_provide
I am trying to create an api that will generate an oauth2_provider access token and refresh token, and it will store in oauth2_provider models. Actually i am using below API to generate both tokens path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), But what i want to do is create an api and store custom generated tokens in that models. for ex: access_token = oauth2_provide. Is there any class names or methods that are acting behind the scenes to generate those tokens? if any are there pls let me know. thanks in advance. -
Filter user details using user ID
When I pass a user ID from front end, I need to fetch all the user Details from the Django rest model to the corresponding view. class UserDetails(viewsets.ModelViewSet): def get_queryset(self): user_id = self.request.query_params.get('user_id',None) //*queryset = UserModel.objects.all()* //instead of getting all the objects from UserModel, I need to get the particular user_id object only return querysest -
Inheritance - Models.py from a installed GitHub-App
I've integrated Django-Scheduler into my project that has a events.py file that creates a "title" in the class "Event". I've added some other variables with Inheritance.For the next Step I need to change Title into a ForeignKey, thats why I've tried this little code: from django.db import models from schedule.models import Event class LessonEvent(Event): title = models.ForeignKey(Student, on_delete=models.CASCADE) Because of the Fact that the original class Event has not Abstrac=True in the Meta Django gives me this Error: lessons.LessonEvent.title: (models.E006) The field 'title' clashes with the field 'title' from model 'schedule.event' . Is there a way to solve this, without touching the code of the django-scheduler app? -
Django Inline : how to get inline properties in change_view() django
Email model class class Email(models.Model) body_message = models.TextField(max_length = 256, null = False) #other fields ForeignKey, subject, to etc. Tabular Inline model. #Inline Email class EmailInline(admin.TabularInline): model = Email And this is my RequestAdmin model that shows inlines. class RequestAdmin(admin.ModelAdmin): inlines = [EmailInline,] #In change_view() i want to print my inlines properties def change_view(self, request, object_id, form_url='', extra_context=None): for inline in self.inlines: #Here i can remove my specific inline self.inlines.remove(inline) #But i want to check my inline_class properties print(inline.body_message) #This line raise exception #i want to print inlines body_message return super(RequestAdmin, self).change_view(request, object_id) Error image which i am getting. Exception Value: type object 'EmailInline' has no attribute 'body_message' Now how i can get my inline properties (body_message) ? -
How can I prevent (massive) sharing of accounts on Django site?
First thought: to check IP's in log of each account to detect sharing and ban it, but this is pretty time-consuming Second: to control devices per account somehow, but I have no idea how to realize that. Suggest some ideas, Thanks -
Location for Django Rest framework exception handler
The DRF Docs say that once an exception handler is set up, it needs to be defined in the settings.py as follows: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' } My Django project layout is like this: backend settings.py connectivity_service utils Custom404ErrorMessage.py The project is called backend and the app name is connectivity_service.The Custom404ErrorMessage.py file contains the function custom_exception_handler which handles the exception. My settings.py looks like this: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'backend.connectivity_service.utils.Custom404ErrorMessage' } However, this gives me the following error message: ImportError: Could not import 'backend.connectivity_service.utils.Custom404ErrorMessage' for API setting 'EXCEPTION_HANDLER'. ModuleNotFoundError: No module named 'backend.connectivity_service'. What am i doing wrong ? -
Extending auth_group_permissions table, auth_permission table and auth_user_user_permissions table in Django
I am having some issue regarding Django Models. I want to extend auth_group_permissions table, auth_permission table and auth_user_user_permissions table. After exploring, i came across monkey patching but most of the answers suggested that it's not recommendable. So, if there is any other way to do it or should i go for monkey patching. Any views or suggestion will be appreciable. -
django 2, list passed to template with different nested objects, how to access each object?
I'm passing a list to the template that looks like this with real data list = [[<Conversation: Conversation object(1)>, datetime.datetime, <QuerySet [{'username: 'admin'}]>]] I want to loop through this in the template and each loop has access to all three items. I'm not sure the ideal way to do this or if I should format my list differently or pull the data in the views first, serialize it and loop through the raw data in the template. {% for l in list %} // Here I should have access to the three objects {{ l.0.id }} //Should print the id of the conversation object {{ l.1 }} // Should print off the datetime stamp {{ l.2.username }} // Should print off admin {% endfor %} Any help with be great. -
Can someone help me in understanding this line of code. This is from django templates
entry.courses.all|join: I can't figure out why join and | are used and why we used all here. I am having a hard time in understanding this soo please help me figure out what this is. can someone suggest me the best way to learn django as fast as possible as most of the tutorials are basic. Thank you -
Django 2.0 NoReverseMatch: not a registered namespace
My goal is to Create hyperlinks which would toss a keyword into a views function which would then pull a query from my db onto the page. GOAL: Press hyperlink which would give me query of a specific major. I was attemping to use the converter, So the goal was, 1 being the first step, 3 being final step. Is this possible? 1) Click the hyperlink -> Major = Accounting 2)URL.py path(<str:Accounting/, views.Major, name=Major) 3)Views.py def Major(request, major): major_choice = professor.objects.filter(Major = major) return render(request, 'locate/major.html', {'major_choice': major_choice}) Index.html <a href="{% url 'locate:Major' 'Accounting' %}">Accounting</a> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:Major/', views.Major, name='Major') ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import professor def index(request): professors = professor.objects.all() return render(request, 'locate/index.html', {'professors': professors}) def Major(request, major): major_choice = professor.objects.filter(Major = major) return render(request, 'locate/major.html', {'major_choice': major_choice}) models.py from django.db import models class professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberofRatings = models.CharField(max_length=50) Major = models.CharField(max_length=50) def __str__(self): return self.ProfessorName -
Django sendmail SMTPDataError
I am getting the below error while trying to use Django sendmail using Outlook SMTP SMTPDataError at /distribute/ (554, '5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. 16.55847:0C0F0000, 17.43559:0000000094000000000000000000000000000000, 20.52176:140F0E852800101064010000, 20.50032:140F0E858817101069010000, 0.35180:0A00E781, 255.23226:6E010000, 255.27962:0A000000, 255.27962:0E000000, 255.31418:0A000000, 16.55847:86000000, 17.43559:0000000068010000000000000000000000000000, 20.52176:140F0E85280010100A00F736, 20.50032:140F0E85881710100A00F836, 0.35180:8C010000, 255.23226:40000730, 255.27962:0A000000, 255.27962:32000000, 255.17082:DC040000, 0.27745:0A001780, 4.21921:DC040000, 255.27962:FA000000, 255.1494:A4010000, 0.37692:05000780, 0.37948:00000000, 5.33852:00000000534D545000000780, 4.56248:DC040000, 7.40748:010000000000010B05000780, 7.57132:000000000000000005000780, 1.63016:32000000, 4.39640:DC040000, 8.45434:824D851FB0676A47B811311E3F17990F00000000, 5.10786:0000000031352E32302E313239342E3032343A5455345052383430314D42303436323A34333038323065332D393530612D346435362D383863332D3037363837616130336664330005000780, 255.1750:0A008984, 255.31418:41010000, 0.22753:0A001986, 255.21817:DC040000, 4.60547:DC040000, 0.21966:4B010000, 4.30158:DC040000 [Hostname=TU4PR8401MB0462.NAMPRD84.PROD.OUTLOOK.COM]') My settings are as below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_HOST_USER = '********' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 587 Please help -
Why BUNDLE_DIR_NAME of webpack is shown wrongly ?
I'd like to use webpack in Django Then, I set up like this. WEBPACK_LOADER = { 'DEFAULT' : { 'BUNDLE_DIR_NAME': 'front/bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'front/webpack-stats.json'), } } However, Request URL indicates strange URL I don't want Taking static off in url will be perfect, How can I do this? -
How to Add a method to the model that takes JSON string and creates new records
I need to Create two Django models: “Patient” and “Embryo”. “Patient” properties: First Name (string) Last Name (string) Telephone Number (string) Email (string) Created At (datetime) “Embryo” properties: Name (string) Analysis Results (text) Created At (datetime) Patient’s Full Name Patient (foreign key) I now need to Add a method to the “Patient” model that takes JSON string and creates new “Embryo” records. Here’s the JSON string: [ { "name": "embryo_1", "analysis_results": "46,XX" }, { "name": "embryo_2", "analysis_results": "47,XY,+21" }, { "name": "embryo_3", "analysis_results": "46,XY" }, ] Below are my models that I created I am not sure how to add a method to the “Patient” model that takes JSON string and creates new “Embryo” records. class Patient(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=35) phone = models.CharField(max_length=18) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) class Embryo(models.Model): name = models.CharField(max_length=45) analysis_result = models.Charfield(max_length=10) created_at = models.DateTimeField(auto_now_add=True) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) @property def patient_full_name(self): return "%s %s" % (self.patient.first_name, self.patient.last_name) -
def(clean) on class based view
Can you confirm that this def(clean) override does absolutely nothing in the context of a class based view? def clean(self): cleaned_data = super(UserAddressForm, self).clean() address1 = cleaned_data.get('address1') address2 = cleaned_data.get('address2') city = cleaned_data.get('city') state = cleaned_data.get('state') city = cleaned_data.get('city') state_other = cleaned_data.get('state_other') country = cleaned_data.get('country') country_other = cleaned_data.get('country_other') zipcode = cleaned_data.get('zipcode') When I was first learning about django, I believed that: a) this function did something and , b) This validation was required for a class based view to confirm that the user inputs didn't contain malicious code. I don't think a) or b) are correct anymore. Can you confirm? Thanks! -
How to add support for html tags in Django blogger app?
I am new to web programming and I am trying to use open source to build my blogger website. Here is the source code, I am using - https://github.com/reljicd/django-blog Here is output I am seeing now - blogger output However, this page doesn't take html tags like >/code> . I have no clue on how to add those styling capability for this page. Any tips will be helpful? Like what part needs to be changed here? -
Django "for" loop by date
I'm doing blog app. I did: {% for entry in entry.all %} <div class="timelinestamp"> ... </div> <br /> <br /> <br /> <br /> {% endfor %} and almost everything works fine. I changed one Entry in my admin panel (The very first Entry...). Since then the order of my post has changed... Can anyone explain me why ? Or tell how to using loop render all Entries sorted by date ? class Entry(models.Model): title = models.CharField(max_length=120) pub_date = models.DateField(null=False) body = models.TextField() image = models.ImageField(upload_to='images/', max_length = 100) def __str__(self): return self.title The pub_date field is NOT primary key in my DB! I'm using Django 2.1 -
Django template variables in .po file
How does one create translation for a string containing template variable? Here's a simple example: I want a text to contain dynamic variable that does not need to be translated, say an integer represented as click_counter. In my template I have a message: <p>{% trans You've clicked the button {{ click_counter }} times. %}</p My .po translation then should adapt to language difference: #: templates/some_template.html:123 msgid "You've clicked the button {{ click_counter }} times." msgstr "Sie haben {{ click_counter }} Mal auf die Schaltfläche geklickt" Obviously this solution does not work, but there is no explanation how to manage this sort of things in Django documentation -
Django stuck after runserver
I am new to Django, and am trying to get the server set up. I have created my project folder (containing manage.py) and after running python manage.py runserver it gets stuck after these messages System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. November 11, 2018 - 18:17:53 Django version 2.1.3, using settings 'MyProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. There is a minute or so pause and then these show up. [11/Nov/2018 18:18:46] "GET / HTTP/1.1" 200 16348 [11/Nov/2018 18:18:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 [11/Nov/2018 18:18:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348 [11/Nov/2018 18:18:47] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564 After that it just stays there, I cannot type anything or do anything. -
How to escape quotes in django sql formatting
I have the following code: # looks like: "('tt1098327','tt3819668','tt0049251')", <type 'str'> ids_as_string = "(-1)" if not ids else ("('" + "','".join(ids).strip("',") + "')") items = list(Item.objects.raw("""SELECT * FROM mturk_imdb WHERE (MATCH(name) against(%s)) AND (imdb_id NOT IN %s)""", (q, ids_as_string ))) The problem with this is that the sql formatter tries to escape the quotes that I have added in for the tuple: DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(\'tt1098327\',\'tt3819668\',\'tt0049251\',\'tt3878722\ What would be the correct way to do the above? -
Django database cache TIMEOUT - make backend delete row
I'm not sure what Django database cache does with expired entries but it seems that they remain in the database. I want Django to delete them after they expire because their size is huge and there can be unlimited number of different keys. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', 'TIMEOUT': 60 * 20, } } I use cache on filtered list of objects and this filter contais number and char fields. Is it possible?