Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set the DestroyAPIView method not real delete my instance?
I have a model, like bellow: class BModel(models.Model): name = models.CharField(max_length=11) status = models.CharField(default="is_active") # if delete: deleted a = models.ForeignKey(AModel) def delete(self, using=None, keep_parents=False): pass # there I want to set the BModel's status to `deleted` Serializer: class BModelSerializer(ModelSerializer): class Meta: model = BModel fields = "__all__" Its Views is bellow: class BModelListAPIView(ListAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() class BModelDestroyAPIView(DestroyAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() My requirement is when use Django-Rest-Framework delete my BModel, I want to set the BModel's status field to deleted, not real delete the instance. How to access it? when I tried to write a delete method to my Model, there comes the default delete method: def delete(self, using=None, keep_parents=False): I have some questions about this: Is this is for the BModel's instance? Whether should through the delete method to access my requirement? -
how to access Item's database in the above code, so that I can create, update, or delete the items
class Hotel(models.Model): name = models.CharField(max_length=50) def get_absolute_url(self): return reverse('Hotel:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Menu_time(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE,) period=models.CharField(max_length=50) def __str__(self): return self.period class Item(models.Model): period = models.ForeignKey(Menu_time, on_delete=models.CASCADE,) item=models.CharField(max_length=50) how to access Item's database in the above code, so that I can create, update, or delete the items -
django datefield is not store in MYSQL database correctly
I am using django and MYSQL. Below is my models.py: enter code here from django.db import models from django.utils import timezone import datetime from django.utils.translation import gettext as _ from bootstrap4_datetime.widgets import DateTimePicker from django import forms class Post(models.Model): WEEKDAYS=( ('Mon','Monday'), ('Tue','Tuesday'), ('Wed','Wednesday'), ('Thu','Thursday'), ('Fri','Friday'), ) TIMES=( ('morning','上午'), ('afternoon','下午'), ('night','晚上'), ) CUSTOMERS=( ('中兴','ZTE'), ('比特大陆','BITMAIN'), ('松果','PINECONE'), ('飞思卡尔','FREESCALE'), ('大唐','DATANG'), ) weekday = models.CharField(max_length=50,default='Mon',choices=WEEKDAYS) time = models.CharField(max_length=50,default='morning',choices=TIMES) customer = models.CharField(max_length=50,default='ZTE',choices=CUSTOMERS) pub_date = models.DateField(_("Date"), default=datetime.datetime.now().date) class Meta: ordering = ('-pub_date',) def __unicode__(self): return self.pub_date Here is database record: 13 2018-01-02 00:00:00.000000 中兴 morning Mon 14 2018-01-08 00:00:00.000000 中兴 morning Mon The database table shows the full time ,but I think datefield will only return format:YY-MM-DD。How to do to store date in YY-MM-DD format. Thanks! -
are routers in django Restframework necessary to use?
i have a stupid question about routers in DRF. so when i set url patters correctly and url endpoints are directing me to specific object.is this necessary to use routers?I am confused about this topic.better question: what is routers and why we should use it? -
django listbox add or remove dynamically into another listbox
i would like to create similar output as attached in question I have 3 models ModelA Stores all my master data ModelB Stores all my child data ModelC Should store master and child data based on my selection of pk(ModelA) and adding child data (ModelB) from listbox to another listbox. I have attached a image for your review. something similar i need Attached Reference -
django template url - add variable to string
Im trying to add a variable to the end of a string and am getting issues with reverse match, from what I gather the below should work {% for type in type_links %} <li><a href="{% url 'sites:site_list' 'all_'|add:type.id %}">{{ type.subnet_type }}</a></li> {% endfor %} I should have a url that has "all_1" for example in it. however I am getting a reverse url error Reverse for 'site_list' with arguments '('',)' not found. 1 pattern(s) tried: ['sites/site_list/(?P<display_filter>[\\w\\-]+)$'] is this correct way to add a variable to end the of the string? Thanks -
Transactions not working in Django using MySQL backend
I am regularily getting integrity errors for the following code snippet: class StatsManager(Manager): @transaction.atomic def create(self, **kwargs): kwargs.setdefault('date', date.today()) try: obj = self.get_queryset().get(**kwargs) except self.model.DoesNotExist: obj = super().create(hits=1, **kwargs) # line 28 else: obj.hits = F('hits') + 1 obj.save() return obj Here is the error message: IntegrityError at /emploi/cours-particuliers-en-physique-chimie-en-classe-de-superieur-1-evry-14skb.html (1062, "Duplicate entry 'EMP_VIEW-1903259-2018-01-08' for key 'statEvent'") And the traceback: File "/home/www/aladom_v6/www/stats/models/managers.py" in create 26. obj = self.get_queryset().get(**kwargs) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/models/query.py" in get 380. self.model._meta.object_name During handling of the above exception (Stats matching query does not exist.), another exception occurred: File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django_mysql/monkey_patches.py" in execute 35. return orig_execute(self, sql, args) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute 101. return self.cursor.execute(query, args) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute 250. self.errorhandler(self, exc, value) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler 50. raise errorvalue File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute 247. res = self._query(query) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in _query 411. rowcount = self._do_query(q) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/cursors.py" in _do_query 374. db.query(q) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/MySQLdb/connections.py" in query 277. _mysql.connection.query(self, query) The above exception ((1062, "Duplicate entry 'EMP_VIEW-1903259-2018-01-08' for key 'statEvent'")) was the direct cause of the following exception: File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/www/.virtualenvs/aladom/lib/python3.4/site-packages/channels/handler.py" in process_exception_by_middleware 243. return super(AsgiHandler, self).process_exception_by_middleware(exception, … -
Celery Task call continuassly run for minutes until the server is stop manually
The celery task call is running for minuteness (load server) I have to force stop the server. I change the Structure of Django Layout: config - settings - local.py - base. by celery.py urls.py apps -app_setA -app1 -app_setB -app1 -app2 -app_not In celery.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('TP') app.autodiscover_tasks() in setting.local CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Celery worker call(on windows): celery -A config worker -l info -P eventlet Call celery task: task_comp.delay(path) Task in tasks.py @task(name=task_comp) def task_comp.delay(path) print('inside task') -
getting error on installing package pyldap-2.4.45 on pypy3 environment
cc -pthread -shared build/temp.linux-x86_64-3.5/Modules/LDAPObject.o build/temp.linux-x86_64-3.5/Modules/ldapcontrol.o build/temp.linux-x86_64-3.5/Modules/common.o build/temp.linux-x86_64-3.5/Modules/constants.o build/temp.linux-x86_64-3.5/Modules/errors.o build/temp.linux-x86_64-3.5/Modules/functions.o build/temp.linux-x86_64-3.5/Modules/schema.o build/temp.linux-x86_64-3.5/Modules/ldapmodule.o build/temp.linux-x86_64-3.5/Modules/message.o build/temp.linux-x86_64-3.5/Modules/version.o build/temp.linux-x86_64-3.5/Modules/options.o build/temp.linux-x86_64-3.5/Modules/berval.o -L/usr/lib -L/usr/lib64 -L/usr/local/lib -L/usr/local/lib64 -R/usr/lib -R/usr/lib64 -R/usr/local/lib -R/usr/local/lib64 -lldap_r -o build/lib.linux-x86_64-3.5/_ldap.pypy3-510-x86_64-linux-gnu.so cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ cc: error: unrecognized command line option ‘-R’ error: command 'cc' failed with exit status 1 ---------------------------------------- Command "/home/synerg-root/SAFE_V2/my-safe-pypy-env/bin/pypy3 -u -c "import setuptools, tokenize;file='/tmp/pip-iqwhlb2g-build/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-z13bd00v-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/synerg-root/SAFE_V2/my-safe-pypy-env/include/site/python3.5/pyldap" failed with error code 1 in /tmp/pip-iqwhlb2g-build/ -
How to create Dependent dropdown in Django forms?
I want to create dependent dropdowns. For example, if someone selects book from the first dropdown, second dropdown should have chapter listed under that book. I have achieved it using HTML / Jquery / AJAX. But i am now interested to achieve same using Django forms. If anyone have idea, please share it. Thank you in advance. -
IOError: [Errno 13] Permission denied: '40c0f5.xyz'
I have built a Django application and deployed this application on apache2 server using wsgi. pep_web/ |-- media |-- out_put_files |-- outputStr |-- pep_learn |-- PepStructure |-- Peptide_Descriptor |-- prediction |-- protocol |-- stepbystep `-- Structure_Descriptor "Peptide_Descriptor" APP of Django Project need to write some temporary file. But its showing an error: IOError: [Errno 13] Permission denied: '67fa042e47b74bd69fed5bfdf140c0f5.xyz' and programe get aborted due to this error. I have tried with "chmod" method for directory permission but nothing has worked sudo chmod -R 0755 /home/bic/pep_web and sudo chmod -R 777 /home/bic/pep_web complete error log is given bellow: raceback (most recent call last): File "/home/bic/pep_web/Structure_Descriptor/Structure_bassed_Descriptor_generation.py", line 161, in <module> Str_DS_class().main_process(args.pep, args.DesOut) File "/home/bic/pep_web/Structure_Descriptor/Structure_bassed_Descriptor_generation.py", line 114, in main_process Str_DS_class().structure_gen(my_pep) File "/home/bic/pep_web/Structure_Descriptor/Structure_bassed_Descriptor_generation.py", line 73, in structure_gen pep = Peptide(seq, nterm = "charged", cterm = "neutral") File "/home/bic/pep_web/Structure_Descriptor/fragbuilder/peptide.py", line 43, in __init__ self._molecule = self._assemble_peptide(self._residues) File "/home/bic/pep_web/Structure_Descriptor/fragbuilder/peptide.py", line 221, in _assemble_peptide file_out = open(temp_xyz, "w") IOError: [Errno 13] Permission denied: '67fa042e47b74bd69fed5bfdf140c0f5.xyz' -
The view didn't return an HttpResponse object when I run new_topic(), though there is a return
def new_topic(request): """add new topic""" if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) The error I got: The view learning_logs.views.new_topic didn't return an HttpResponse object. It returned None instead. And I have searched many related problems as well as tested them, yet they did not work.Could you please give me some help,thanks. -
Django merging 2 model instances issue with m2m fields which specifies an intermediary model
I'm using a script to automate merging 2 Django model instances (so it can be used for any kind of model in my system). But there is a problem when it comes to the part that handle m2m fields which specifies an intermediary model (using through parameter when this field defined), I get the error: AttributeError: Cannot use remove() on a ManyToManyField which specifies an intermediary model. Use <MyModel>'s Manager instead # Migrate all many to many references from alias object to primary object. for related_many_object in get_all_related_many_to_many_objects(alias_object): alias_varname = related_many_object.get_accessor_name() obj_varname = related_many_object.field.name if alias_varname is not None: # standard case related_many_objects = getattr(alias_object, alias_varname).all() else: # special case, symmetrical relation, no reverse accessor related_many_objects = getattr(alias_object, obj_varname).all() for obj in related_many_objects.all(): getattr(obj, obj_varname).add(primary_object) #This line raises the AttributeError getattr(obj, obj_varname).remove(alias_object) Here is the function that return all m2m field of the object which need to be merged: def get_all_related_many_to_many_objects(obj): return [ f for f in obj._meta.get_fields(include_hidden=True) if f.many_to_many and f.auto_created ] I have 2 question about this case: Is there any built-in functions that allows me to distinguish m2m fields which specifies intermediary model from m2m fields which doesn't? (Because with the normal m2m fields this add() function … -
Tooltips show on hover but don't disappear using mpld3
I have designed the Django application in which back end(i.e python) will make the plot in javascript. The front end is designed in javascript. Frontend will send the ajax request at specific interval of time and back end(python) will send the plot(which is in javascript) to front end. I am using pythom mpld3 library to design the plot.My code to make plot is as below: def draw_plot(ue_info,selected_parm): rp_x = [-1.0,0.0,1.0,-1.0,0.0,1.0,-1.0,0.0,1.0,-1.0,0.0,1.0] rp_y = [1.5,1.5,1.5,0.5,0.5,0.5,-0.5,-0.5,-0.5,-1.5,-1.5,-1.5] Cluster = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1,1,1,1]) fig = plt.figure() ax = fig.add_subplot(111) scatter = ax.scatter(rp_x,rp_y,c=Cluster,s=50) fig.patch.set_visible(False) ax.axis('off') ax.set_autoscale_on(False) ue_offset = 0.2 for ue in ue_info: try: i = rand.uniform(rp_x[int(ue_info[ue]["pr_rp_id"])]-ue_offset,rp_x[int(ue_info[ue]["pr_rp_id"])]+ue_offset) j = rand.uniform(rp_y[int(ue_info[ue]["pr_rp_id"])]-ue_offset,rp_y[int(ue_info[ue]["pr_rp_id"])]+ue_offset) if float(ue_info[ue][selected_parm]) < 20.0: ues = ax.scatter(i,j,s=50,c='green',marker='+') if float(ue_info[ue][selected_parm]) < 21.0: ues = ax.scatter(i,j,s=50,c='orange',marker='+') else: ues = ax.scatter(i,j,s=50,c='red',marker='+') ueLabel = "<ul>"+"<li>"+"UE:"+ue+"</li>" for info in ue_info[ue]: ueLabel = ueLabel+"<li>" +info+":"+ue_info[ue][info]+"</li>" tooltip = mpld3.plugins.PointHTMLTooltip(ues,[ueLabel]) mpld3.plugins.connect(fig, tooltip) except: print "One of the UE is removed while drawing the plot..." tooltip = mpld3.plugins.PointLabelTooltip(scatter) mpld3.plugins.connect(fig, tooltip) plt.text(-1.0, 1.7, "RP0", fontsize=8) plt.text(0.0, 1.7, "RP1", fontsize=8) plt.text(1.0, 1.7, "RP2", fontsize=8) plt.text(-1.0, 0.7, "RP3", fontsize=8) plt.text(0.0, 0.7, "RP4", fontsize=8) plt.text(1.0, 0.7, "RP5", fontsize=8) plt.text(-1.0,-0.3, "RP6", fontsize=8) plt.text(0.0, -0.3, "RP7", fontsize=8) plt.text(1.0, -0.3, "RP8", fontsize=8) plt.text(-1.0,-1.3, "RP9", fontsize=8) plt.text(0.0, … -
django DateField not work
I am using django and MYSQL. Below is my models.py: enter code here from django.db import models from django.utils import timezone import datetime from django.utils.translation import gettext as _ from bootstrap4_datetime.widgets import DateTimePicker from django import forms Create your models here. class Post(models.Model): WEEKDAYS=( ('Mon','Monday'), ('Tue','Tuesday'), ('Wed','Wednesday'), ('Thu','Thursday'), ('Fri','Friday'), ) TIMES=( ('morning','上午'), ('afternoon','下午'), ('night','晚上'), ) weekday = models.CharField(max_length=50,default='Mon',choices=WEEKDAYS) time = models.CharField(max_length=50,default='morning',choices=TIMES) pub_date = models.DateField(_("Date"),default=datetime.datetime.now().date) class Meta: ordering = ('-pub_date',) def unicode(self): return self.pub_date enter image description here The database table shows the full time ,but I think datefield will only return format:YY-MM-DD。 Thanks! -
Django: Writting in Active Directory
I've been working on a webapp for userauthentication. This includes: Log-in Register Passwort reset ...when you are not logged-in and: Log-out Profile (shows all data of the user) Passwort change ...when you are loggen-in And I want to create and edit a user in my active directory form my webapp. For know I can log-in as an existing user (LDAP Backend is done with django-auth-ldap) in my webapp, but I can't write in my AD (Register and Edit don't work). I am inexperienced and need help what I should do. Do I have to write a function and how do I bind it with the AD? Someone suggested me to use python-ldap3 because it's better for LDAP configurations. Any advise would be helpful and if you need code from me don't hesitate to ask. If you have an example feel free to share it :) Thank you guys! -
Create custom template tag in Django?
I have next models in my Django project. models.py: class Document(models.Model): name = models.TextField(blank=True, null=True) class DocumentClosure(models.Model): parent = models.ForeignKey( Document, on_delete=models.CASCADE, related_name="parents", related_query_name="parent", db_column='parent_id', blank=True, null=True ) child = models.ForeignKey( Document, on_delete=models.CASCADE, related_name="childs", related_query_name="child", db_column='child_id', blank=True, null=True ) level = models.IntegerField( default=0, blank=True, null=True ) Next models create 2 table in database with "Closure Table" architecture. DocumentClosure store information about ancestors and descendants. I want to show tree in template as it make django-mptt application. I started with next code. Now I need to rewrite get_children() method based on my current models. Can someone help me with this method?! template: <ul> {% recursetree documents %} <li> {{ node.name }} <ul class="children"> {{ children }} </ul> </li> {% endrecursetree %} </ul> custom_tag.py: from django import template register = template.Library() @register.tag def recursetree(parser, token): bits = token.contents.split() if len(bits) != 2: raise template.TemplateSyntaxError(_('%s tag requires a queryset') % bits[0]) queryset_var = template.Variable(bits[1]) template_nodes = parser.parse(('endrecursetree',)) parser.delete_first_token() return RecurseTreeNode(template_nodes, queryset_var) class RecurseTreeNode(template.Node): def __init__(self, template_nodes, queryset_var): self.template_nodes = template_nodes self.queryset_var = queryset_var def _render_node(self, context, node): bits = [] context.push() for child in node.get_children(): # get_children() initialized in models.py file | rewrite this method bits.append(self._render_node(context, child)) context['node'] = node context['children'] = mark_safe(''.join(bits)) … -
add django manytomany field in html template that look exactly like from the admin page
Greeting, I'm trying to add a django form in my html template where its manytomany field looks exactly like THIS, I've done,it before but after a while I'm trying to add it again, it doesnt seem to be working. Can anyone point me to the right direction thanks, below is my code : model.py class Project(models.Model): user = models.ManyToManyField(Employee, blank=True) form.py : class EditProjectForm(forms.ModelForm): prefix = 'edit_form' class Meta: model = Project fields = '__all__' view.py : def project_setting(request, project_id): form = EditProjectForm(request.POST or None, request.FILES or None, instance=selected_project, prefix='settings') context = { 'form': form } return render(request, 'setting.html', context=context) Html : <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" /> <link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css" /> <!--USER--> <div class="col-lg-6"> <div class="field"> <label>User :</label> <select name="settings-user" id="id_settings-user" multiple="multiple" class="selectfilter" data-field-name="Employee" data-is-stacked="0"> <option value={{ form.user }}></option> </select> </div> </div> -
Resize/Crop an Image using Celery in django in Django Admin and outside
I want to create multiple copies of an image and resize them using celery after the original image was sent. def save_model(self, request, obj, form, change): updated = change super().save_model(request, obj, form, change) if not updated: logo = CompanyLogo(logo=form.cleaned_data['logo'], company=obj) logo.save() # Send Celery task to create resize images task_company_logo.delay(form.cleaned_data['logo']) called by task method def crop_image(path): image = Image.open(os.path.join(settings.MEDIA_ROOT, path)) image.show() I have the following error: 'InMemoryUploadedFile' is not JSON serializable I understand the error, because I send the all image obj from the form, I just want to get the path to the original image. -
How to access each field of wagtail Freeform in HTML pages ?
I have created wagtail FreeForm by extending WagtailFormBlock given below.I can create different form using wagtail admin interface. File name: blocks.py from wagtailformblocks.blocks import WagtailFormBlock class MyForm(WagtailFormBlock): class Meta: app_label = 'demo' This is the models.py file in which I have created page and assigned form to this page. File name: models.py from wagtail.wagtailcore.models import Page from wagtailformblocks.models import BaseForm from wagtail.wagtailcore.fields import StreamField class FormType(BaseForm): class Meta: verbose_name = "Form Type" class ImagePage(Page): template = 'wagtail_demo/image_page.html' content = StreamField([ ('my_forms', MyForm()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('content'), ] This is my image_page.html page where I want to render the form fields. File name: image_page.html {% load wagtailcore_tags %} {% with blocks=self.content %} {% for block in blocks %} {{ block }} {% endfor %} {% endwith %} It shows all the fields of the associated form with this page. I want to access each fields of the associated form individually (e.g.: field name etc.) because sometimes I need to add fields before the submit button using javascript. How can I do that ? -
local variable 'result' referenced before assignment only in production
I have a problem that even if it has been answered multiple time here, I couldn't find the solution to my problem; it is working properly on local but since I uploaded my app on heroku it give me an error local variable 'result' referenced before assignment I tried global but I get on local and production name 'result' is not defined I tried nonlocal but it gives me SyntaxError: no binding for nonlocal 'result' found And without, on local it work properly but on produciton I get the error.. Why that ? the problematic code .: class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk}) def has_member_responses(self): try: x = Project.objects.get(id = self.id).team_id.members.all() for i in x: #global result result = 1 if i.response_set.exists(): result = result * True else: result = result * False return result except AttributeError: pass -
No Post matches the given query. Django
Hello everybody I am a newbie in Django and I have started to lear how to create a blog, everything is working fine but when I click post on address http://127.0.0.1:8000/blog/ I am receiving this redirection to address >> http://127.0.0.1:8000/blog/2018/01/07/Django/ Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/2018/01/07/Django/ Raised by: blog.views.post_detail No Post matches the given query. this is a code for views.py: from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.objects.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] -
WYSIWIG editor for Django that automatically highlights links
I have a site where users can post stuff and mainly links with comments. I want the links to be automatically highlighted as links. I realised I can't do this with plaintext Field. So, I'm looking for a WYSIWIG editor that allows this. I don't want my users have to select the links and manually make them links. I tried CKEditor widget and it's not highlighting links by default. How do I accomplish this? -
__str__ example in django tutorial not working
I can't get the str to work in django tutorial when printing the object texts. This is the code in the models.py: from django.db import models import datetime from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return (self.question_text) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return str(self.choice_text) class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) In the python shell, I write the following: from first_app.models import Question, Choice When I invoke the str function, I get this: Question.objects.all() <QuerySet [<Question: Question object>, <Question: Question object>, <Question: Ques tion object>]> I even tried print function and got the same result: print(Question.objects.all()) <QuerySet [<Question: Question object>, <Question: Question object>, <Question: Ques tion object>]> -
Showing json field in Django admin
I have an Django model as follows: class BodyHeight(models.Model): seats = models.ForeignKey(to=Seats) name = models.CharField(max_length=127, null=True, blank=True) key = models.CharField(max_length=100, null=True) data = models.TextField(null=True, blank=True) class Meta: verbose_name_plural = "Body heights" def __str__(self): return self.name And in the data field I store the json data, as follows: {"url": "https://some_url=/BE?category=COMMERCIAL, "images": ["url_to_some_image"]} And I want to show in the Django admin panel only the url from that field. Now I have: class BodyHeightAdmin(admin.ModelAdmin): search_fields = ('name', ) list_display = ('id', 'name', 'key', ) list_display_links = ('id', 'name', 'key', ) admin.site.register(BodyHeight, BodyHeightAdmin) That is without the data field. If I add the data field in list_display it shows than whole json (ugly format), but I want only the url. Any idea how to do that?