Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'module' object has no attribute 'Name'
i am trying to create a basic form using python which has only one field your_name in the table NameForm. But i am getting the error AttributeError: 'module' object has no attribute 'Name'. I dont understand where this error comes from. Could anyone help me with it? I am using django 1.11. models.py from __future__ import unicode_literals from django.db import models class NameForm(models.Model): your_name = models.CharField(max_length=200) views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect from .models import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'name.html', {'form': form}) urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.Name.as_view(), name='name'), ] template/home/name.html <form action="/your-name/" method="post"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"> </form> -
No OCR tool found in python
I have downloaded Mayan EDMS-Electronic Document Management System from GitHub and I configured project using Django server. I had added the required libraries based on requirement. Now the project runs with error ocr.exceptions.OCRError: No OCR tool found When I searched this error, I found Pyocr looks for the OCR tools (Tesseract, Cuneiform, etc) installed on your system and just tells you what it has found. Then I tried to install tesseract using the command -->pip install tesseract-ocr. I got this error Requirement already satisfied: cython in ./venv2/lib/python2.7/site-packages (from tesseract-ocr) (0.28.4) running bdist_wheel running build running build_py file tesseract_ocr.py (for module tesseract_ocr) not found file tesseract_ocr.py (for module tesseract_ocr) not found running build_ext building 'tesseract_ocr' extension creating build creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-l1RrwO/python2.7-2.7.14=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c tesseract_ocr.cpp -o build/temp.linux-x86_64-2.7/tesseract_ocr.o cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ tesseract_ocr.cpp:600:10: fatal error: leptonica/allheaders.h: No such file or directory #include "leptonica/allheaders.h" please help me to solve this issue. Thanks in advance. -
How to reorder dropdowns in django-admin inlines?
I'm trying to give some order to our django admin dashboard. At the moment I am able to order dropdowns by the field name using this code in MyModelAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "program": kwargs["queryset"] = models.ProgramModel.objects.all().order_by('name') return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) So, when I go to the MyModel I see the dropdown alphabetically ordered like in this image: The problem is that if I bring that model as an Inline in a different model, it is not ordered anymore: How can I have that dropdown ordered also in the inline element?? I already tried adding ordering to my MyModel meta class and it works, but I would like this to affect only the admin page and to be completely decoupled from the model. -
customising django auth.view or custom login view
in my Django app i need to provide rest api's for almost all the views. so what i need to do is provide login option by using an api. The default behaviour of auth_views.login is to redirect after login to a redirect url specified, however i need to check if content-type is application/json in the request i need to return the session id instead of redirecting to the redirect url & then the user can use this session id to use other api's? how could i do that. remember i cannot usedjango-rest-framework -
Django - PostgreSQL set statement_timeout
I'm using Django 1.10 and PostgreSQL DB. I'm trying to figure out whether I can set statement_timeout from Django. Seems like I can't do it the same way as for connect_timeout (in settings.py): DATABASES[DEFAULT]['OPTIONS'] = { 'connect_timeout': float(os.getenv('DEFAULT_DB_OPTIONS_TIMEOUT', 5)) } I saw something like this, but I can't find a way to verify it actually works: DATABASES[DEFAULT]['OPTIONS'] = { 'options': '-d statements_timeout=700' } I know I can set it directly from the DB like: set statement_timeout=5000 but I'm looking for a way to do it from Django. -
How to serialize nested model in Django-Rest
I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table. I have two tables job_info and username_userid. Here is my models.class file: class UseridUsername(models.Model): userid = models.IntegerField(blank=True, null=True) username = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'userid_username' class LinuxJobTable(models.Model): job_db_inx = models.AutoField(primary_key=True) mod_time = models.IntegerField() account = models.TextField(blank=True, null=True) exit_code = models.IntegerField() job_name = models.TextField() id_job = models.IntegerField() id_user = models.IntegerField() class Meta: managed = False db_table = 'linux_job_table' Now how can I get all the values from LinuxJobTable and username from UseridUsername for the corresponding user. Heren is my serializable class : class UseridUsernameSerializer(serializers.ModelSerializer): class Meta: model = UseridUsername fields = ('userid','username') class UserSerializer(serializers.ModelSerializer): class Meta: username = UseridUsernameSerializer(many=False) model = LinuxJobTable fields = ('account','mod_time','username') When I try to access it, it gives ' Field name username is not valid for model LinuxJobTable.' error. -
Rendering PagedownWidget in a formset
I'm unable to render the pagedown widget (widget that contains buttons for bold, italics, etc) in forms that are rendered as part of a formset. My model and form are as follows: models.py class Services(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) body = models.TextField(max_length=5000, null=True, blank=True) def __str__(self): return self.user.username forms.py class ServicesForm (forms.ModelForm): body = forms.CharField(widget=PagedownWidget(show_preview=False)) class Meta: model = Services exclude = ('user',) I've included the following template tags in the template in order to render the form. {% block head_extra %} {{ form.media }} {% endblock head_extra %} Essentially, I've gotten this code to work on a regular form, but it doesn't seem to work on a formset. Any thoughts? Do I have to manually render the widget with a template tag? Thanks! -
How to have both Django and another service (for example monitoring server : Zabbix) in Centos server 7 properly
I need to have at least two service running in /etc/httpd/conf/httpd.conf centos server. I create two virtualhost and listen ports needed like as follow: /etc/httpd/conf/httpd.conf has been changed like: Listen 4720 Listen 8000 <VirtualHost *:4720> DocumentRoot /usr/share/zabbix </VirtualHost> <VirtualHost *:8000> WSGIScriptAlias / /var/www/my_project_name/wsgi.py </VirtualHost> WSGISocketPrefix /var/run/wsgi WSGIPythonPath /var/www/.venv/bin/python3.6 After restarting httpd.service via systemctl, Zabbix project is running on port 4720 but I have got an internal error 500 for Django project running on port 8000. I thought apache config needs other changing. -
ModelForm does not validate when foreignkey is blank=true and null=true
I have a form containing foreign key input that sometimes need to be null. when i set blank=true, form validates, but throws error saying can't save null value. when i set blank=true and null=true, the form won't even validate. help me out please models.py class Task(BaseModel): project = models.ForeignKey("projects.Project", blank=True, null=True) staff = models.ForeignKey("staffs.Staff") task_start_date = models.DateField() task_end_date = models.DateField() description = models.TextField(blank=True,null=True) category = models.ForeignKey("tasks.TaskCategory") status = models.CharField(max_length=128,choices=TASK_STATUS,default="pending") is_deleted = models.BooleanField(default=False) thefile = models.FileField( upload_to="uploads/designtasks/", null=True, blank=True) technical_design = models.FileField( upload_to="uploads/designtasks/", null=True, blank=True) class Meta: db_table = 'task' verbose_name = _('task') verbose_name_plural = _('tasks') ordering = ('staff',) class Admin: list_display = ('staff',) def __unicode__(self): return self.description views.py if request.method == "POST": form = TaskForm(request.POST, request.FILES) #import ipdb; ipdb.set_trace() if form.is_valid(): # create task data = form.save(commit=False) # data.thefile = request.FILES['thefile'] # data.technical_design = request.FILES['technical_design'] data.creator = request.user data.updator = request.user data.save() if TaskCategory.objects.filter(name='Design').exists(): if (data.category == TaskCategory.objects.get(name='Design')) and data.project: project = data.project project.is_design_required = True project.save() create_notification(request, "task", data) response_data['status'] = 'true' response_data['title'] = "Successfully Created" response_data['redirect'] = 'true' response_data['redirect_url'] = reverse( 'tasks:task', kwargs={'pk': data.pk}) response_data['message'] = "Task Successfully Created." else: response_data['status'] = 'false' response_data['stable'] = 'true' response_data['title'] = "Form validation error" message = '' message += generate_form_errors(form, formset=False) … -
Django Rest Framework: How to get errors in a list when creating multiple records
I am trying to create a serializer to create multiple products with one payload. Here's my attempt: # models.py class Product(models.Model): sku = models.CharField(unique=True) product_name = models.CharField() # serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): try: product = create_product( **validated_data) except: raise CustomException( detail = { "error" : "Unable to create product" } ) # views.py class ProductCreate(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def get_serializer(self, *args, **kwargs): kwargs["many"] = True return super().get_serializer(*args, **kwargs) So, this works well when the data are clean. Here's a response: [ { "id" : 1, "sku" : "12345", "product_name" : "Product A" }, { "id" : 2, "sku" : "56789", "product_name" : "Product B" }] But if one of the products fails to be created, the error message is simply: # response { "error" : "Unable to create product" } What I'd like is the response to be a list, where each element corresponds to the product element in the request. For example, product A is created, but product B returns an error. [ { "id" : 1, "sku" : "12345", "product_name" : "Product A" }, { "error" : "Unable to create product" } ] How can … -
Django test migration fails for sqllite3 backend
when running following test command: python -W ignore manage.py test --pattern=*p --settings=mysite.settings_test -v 2 I'm getting the following error: Applying app_connections.0046_feefocredential_expire_at...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "[]": syntax error Strangely the migration that fails is just adding a new field: # -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-07-13 14:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_connections', '0045_auto_20180613_0844'), ] operations = [ migrations.AddField( model_name='feefocredential', name='expire_at', field=models.DateTimeField(null=True), ) ] which results in following sql: # python manage.py sqlmigrate app_connections 0046 BEGIN; -- -- Raw SQL operation -- ALTER TABLE app_connections_feefocredential ADD COLUMN fetch_merchant_ids VARCHAR[] NOT NULL DEFAULT '{}'; ; COMMIT; Note the migration for actual db which is postgres works fine, so its likely something to do with sqllite backend generation. Is there any other place that I can check where it fails, as the line in particular that fails is too obscure to say the reason: https://github.com/django/django/blob/bce29f10a2ee991e70133b71e0de2a6cf4260f0f/django/db/backends/sqlite3/base.py#L326 -
Unable to retrieve a single item when through HTTPRequest with Django Rest
I follow the instructions on Django Restframework tutorial here and has configured everything after it, but somehow, I can't use id to retrieve the json for a single item. I expect to get a json representation of a single item when i request localhost:8080/items/[index], but instead of getting the item with the corresponding index I would get json representation of every items in I have. My views.py @api_view(['GET']) def item_list(request): """ List and create items """ if request.method == 'GET': items = Item.objects.all() serializer = ItemSerializer(items, many=True) return Response({'data': serializer.data }) @api_view(['GET']) def item_detail(request, pk): """ Retrieve an item """ try: item = Item.objects.get(pk=pk) except Item.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ItemSerializer(item) return Response(serializer.data) -
LDAPSearch returns 0 objects
I am getting the following result: search_s('CN=ABC - DEF,OU=Process IDs,OU=Service Accounts,DC=homeoffice,DC=Company,DC=com', 2, '(uid=%(user)s') returned 0 objects: Authentication failed for k1a008m: failed to map the username to a DN. My settings.py file: import ldap import ldap, logging from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) AUTH_LDAP_SERVER_URI = "ldap://server1.com ldap://server2.com ldap://server3.com:389" AUTH_LDAP_BIND_DN = "CN=ABC - DEF,OU=Process IDs,OU=Service Accounts,DC=homeoffice,DC=Company,DC=com" AUTH_LDAP_BIND_PASSWORD = "myPassword" AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=ABC - DEF,OU=Process IDs,OU=Service Accounts,DC=homeoffice,DC=Company,DC=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] My views.py file: def logon(request): if request.method == 'POST': form = loginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = LDAPBackend().authenticate(request, username=username, password=password) if user is not None: print("Authenicated!") else: form = loginForm() return(render(request, "logon.html", { "form" : form })) How do I list all users or search for them using wild-cards? -
Django is starting slowly
I have a big Django project. When I start the server, I almost immediately see this: System check identified no issues (0 silenced). July 16, 2018 - 04:29:32 Django version 1.10.6, using settings 'project.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. However, if I go to http://0.0.0.0:8000 it is not available for like good 30 seconds. What happens when I do python manage.py runserver? Does it try to connect to database/redis/etc? or something else? I am trying to find the bottleneck that causing this pause so that I can optimize/remove it. -
DjangoAdmin MultipleSelect widget not showing already selected items
I have two models, Location and Machine class Machine(models.Model): name = models.CharField(max_length=30, help_text='Name of machine') location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.SET_NULL, help_text='ID of machine location') def __str__(self): return self.name class Location(models.Model): name = models.CharField(max_length=30, help_text='Name of Location') def __str__(self): return self.name When opening Location in Django-Admin I want not only to select 1-N available machines (Working) but I also want to see already selected ones (Not working) This is my LocationForm for admin class LocationForm(forms.ModelForm): class Meta: model = Location # Parent Class fields = '__all__' #Select Only Machines without assigned location machines = forms.ModelMultipleChoiceField(queryset=Machine.objects.filter(location__isnull=True), required=False, widget=FilteredSelectMultiple(verbose_name=('Machines'), is_stacked=False)) def __init__(self, *args, **kwargs): super(LocationForm, self).__init__(*args, **kwargs) if self.instance: self.fields['machines'].initial = self.instance.machine_set.all() def save(self, *args, **kwargs): instance = super(LocationForm, self).save(commit=False) self.fields['machines'].initial.update(location=None) instance.save() self.cleaned_data['machines'].update(location=instance) return instance The 'Selected Machines' box is always empty, how to enable showing the selected items? I know the query I just dont know where I should put it. -
How Django bulks create check exist already in bulks objs and instance?
I have a lot of data, that data is pretty dirty, example: A table ORM : id = models.CharField(default='', max_length=50) time = models.DateTimeField(default=timezone.now) number = models.CharField(default='', max_length=20) unique_together = ['id', 'time', 'number'] A table DATA : id time number 1 2018-07-16 00:00:00 1 1 2018-07-16 00:00:00 2 1 2018-07-16 00:00:00 3 1 2018-07-16 00:00:00 4 2 2018-07-16 00:00:00 0 Import Datas (sample) : id time number 1 2018-07-16 00:00:00 1 3 2018-07-16 00:00:00 0 3 2018-07-16 00:00:00 0 4 2018-07-16 00:00:00 0 4 2018-07-16 00:00:00 1 So, When I Do for loop.... objs = [] objs.append(A(**kwargs)) A.objects.bulk_create(objs, batch_size=50000) It will raise two kind duplicate. A Table already exist " 1 2018-07-16 00:00:00 1" Import Datas already exist 3 2018-07-16 00:00:00 0 for two times in objs, so when I bulks create it will raise duplicate, then it will roll back all commit !!! the "1", I can use get or create to solve it but "2", I can't check now I append data exist in the objs or not I tried to use this to check exist or not, but when data row over 1000000, the complexity will be terrible. def search(id, time, number, objs): for obj in objs: if … -
Unexpected keyword argument 'id'
I also tried to change the id to WO_ID at the urls but then I got another error saying TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' views.py from django.shortcuts import render, get_object_or_404, redirect from django import forms from django.views.generic import TemplateView from django.core.serializers import serialize from django.http import HttpResponse from MMS.models import Workorder from MMS import forms from MMS.forms import CreateWorkorder from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from . import forms def workorder_create(request): if request.method == "POST": form = CreateWorkorder(request.POST) if form.is_valid(): CreateWorkorder_item = form.save(commit=False) CreateWorkorder_item.save() return redirect('/workorder/' + str(CreateWorkorder_item.id) + '/') else: form = CreateWorkorder() return render(request, 'workorders/workorder_create.html', {'form': form}) def workorder_edit(request, id=None): item = get_object_or_404(Workorder, WO_ID=id) form = CreateWorkorder(request.POST or None, instance=item) if form.is_valid(): form.save() return redirect('/workorder/' + str(item.WO_ID) + '/') return render(request, 'workorders/workorder_create.html', {'form': form}) def workorder(request, WO_ID=id): workorder = Workorder.objects.get(WO_ID=id) return render(request, 'workorder/workorder.html', {'workorder': workorder}) urls.py from django.conf.urls import url from MMS import views from MMS.views import workorder_create app_name='MMS' urlpatterns = [ url(r'^create/workorder/$', views.workorder_create, name='create_workorder'), url(r'^edit/workorder/(?P<id>\d+)/$', views.workorder_edit, name='edit_workorder'), url(r'^workorder/(?P<id>\d+)/$', views.workorder, name='workorder'), ] -
Access URL of S3 files using Boto
I have some images in my S3 bucket and I want to display them in my django application. import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for l in list: print(l[u'Key']) Using this code I'm getting the names of those images. How do I get the URL of the images, so that I can pass it to HTML pages to display it, using this same approach? -
Django: "fk_name is not a ForeignKey to" - Trying to tie an employee to a manager
I am relatively new to Django and I am trying to create a data model which has users tied to managers. I want to be able to have a drop down to assign managers to individual employees (both through the admin console and not). I am running into an error fk_name 'manager' is not a ForeignKey to when doing so. Here is my code, any help on this is greatly appreciated: Models.py class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user', ) department = models.CharField( blank=True, default='TBD', max_length=50, ) team = models.CharField( blank=True, max_length=50, ) manager = models.ForeignKey(User, on_delete=models.CASCADE, related_name='manager') class Meta: verbose_name = ('user_profile') verbose_name_plural = ('user_profiles') def __str__(self): return self.user.username forms.py class ProfileFormset(forms.ModelForm): department = forms.CharField( label='Department', widget=forms.Textarea(attrs={'rows': 1, 'cols': 15}), ) team = forms.CharField( label='Team', widget=forms.Textarea(attrs={'rows': 1, 'cols': 15}), ) manager = forms.ModelChoiceField( label='Manager', queryset=User.objects.all() ) class Meta: model = UserProfile fields = ('department', 'team', 'manager') def save(self, commit=True): user = super().save(commit=False) user.department = self.cleaned_data.get('department') user.team = self.cleaned_data.get('team') user.manager = self.cleaned_data.get('manager') if commit: user.save() return user admin.py class UserProfileInLine(admin.TabularInline): model = UserProfile fk_name = 'manager' @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): inlines = [ UserProfileInLine, ] list_display = ("user", "manager", "department", "team") -
django cassandra engine saves the datetime fields in UTC. how can i change it?
I'm using django-cassandra-engine to use cassandra in my django application. i have a model that inherits from DjangoCassandraModel that has a DateTime field. timezone.now() shows my local time that is not GMT +4:30 but when i pass this to create an object from my model cassandra saves it in UTC. Is there a way to change this value to my local time. thanks in advanced. -
how to point bluehost DNS to Heroku app
i recently completed a django project and hosted it on heroku, I've purchased a domain name on bluehost. i'm having issues linking the heroku app and the bluehost domain. i've tried configuring the CNAME record to point to the heroku app but its not working. i don't really know what i'm doing wrong. please help. -
Getting VACUUM WARNING while running uwsgi from ini file
I am trying to run nginx and uwsgi. When i try to run uwsgi with below command in my proj virtual environment with proj user i get error. When i run uwsgi, i see they proj.sock is created in /run/uwsgi/proj.sock I changed the /run/uwsgi permissions to drwxrwxrwx to see if problem is permission related. But problem continues. I also checked the /etc/passwd and there is no uwsgi user. The directory info for /run/uwsgi is : drwxrwxrwx 2 root root 60 Jul 16 10:53 uwsgi Run below command : uwsgi --ini /etc/uwsgi/sites/proj.ini Error : [uWSGI] getting INI configuration from /etc/uwsgi/sites/proj.ini<br> * Starting uWSGI 2.0.15 (64bit) on [Mon Jul 16 10:53:02 2018] * compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-28) on 13 July 2018 17:12:50 os: Linux-3.10.0-862.6.3.el7.x86_64 #1 SMP Tue Jun 26 16:32:21 UTC 2018 nodename: localhost.localdomain machine: x86_64 clock source: unix detected number of CPU cores: 2 current working directory: /home/proj detected binary path: /home/proj/Env/proj/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/proj/work/proj your processes number limit is 4096 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with … -
I would like to use the same view to display or update an object through his django form
Someone could help me with this problem ? models.py @autoconnect class Event(models.Model): title = models.CharField(max_length=50, unique=True) slug = models.CharField(max_length=100, default=' ', blank=True) description = models.CharField(max_length=250, blank=True) PrivacityType = ((1, 'Público'), (2, 'Privado')) privacity = models.IntegerField(choices=PrivacityType, default=1, blank=True) EVENT_TYPE = ((1, 'Deporte'), (2, 'Nutrición'), (3, 'Salud')) type = models.IntegerField(choices=EVENT_TYPE, default=1) owner = models.ForeignKey(User) creation_date = models.DateTimeField(auto_now=True) updated_date= models.DateTimeField(auto_now_add=True) start = models.DateTimeField(default=datetime.datetime.now()) end = models.DateTimeField(default=datetime.datetime.now()) address = models.CharField(max_length=250, default='', blank=True) notes = models.CharField(max_length=250, default='', blank=True) def __unicode__(self): return self.title def pre_save(self): self.slug = self.title.replace(" ", "_").lower() forms.py class EventForm(forms.ModelForm): title = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Título'})) description = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Descripción'})) address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Lugar'})) notes =forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Añade tus notas'})) class Meta: model = event_models.Event fields = '__all__' views.py @login_required(redirect_field_name='custom_login') def event(request, event_slug): try: event = events_models.Event.objects.get(slug=event_slug) except event.DoesNotExist: event = None if request.method == 'POST': event_form = events_forms.EventForm(request.POST, instance=event) if event_form.is_valid(): event = event_form.save(commit=False) event.owner = request.user event.save() else: event = events_forms.EventForm(instance=event) return render(request, 'event.html', { 'event': event, 'event_form': getEventform(request), urls.py url(r'^events/(?P<event_slug>\w+)/$', calendar_views.event, name='detail_event'), This is the error that appears. How can i fix it ? NoReverseMatch: Reverse for 'detail_event' with keyword arguments '{u'event_slug': }' not found. 1 pattern(s) tried: [u'calendario/eventos/(?P\w+)/$'] Thanks in advance. -
DRF post url without end slash
In my application , I need to display the REST url(s) without a slash at the end. I have tried below combination but it didnt work. Added APPEND_SLASH=True in the settings.py and on the urls.py file from rest_framework.routers import SimpleRouter router = SimpleRouter(trailing_slash=False) After adding this when I am calling the urls without slash at the end in the postman, it is giving me an 404 error- URL not found. But with slash at the end is working fine. Is there any option to make this url without with slash at the end ? Especially for the post urls -
Checking tree modifications in django-treebeard ORM before saving
I want to double-check if I am correctly interpreting the following section of the django-treebeard docs: django-treebeard uses Django raw SQL queries for some write operations, and raw queries don’t update the objects in the ORM since it’s being bypassed. Because of this, if you have a node in memory and plan to use it after a tree modification (adding/removing/moving nodes), you need to reload it. Here's my understanding: If I've loaded a node from the database and am working on it in memory, I must use refresh_from_db() before saving. Also, in case the tree is modified between refresh_from_db and save, I should wrap the two calls in an atomic transaction. Is this correct?