Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crashign when using validator on model field
Why is django crashing (without error) when setting validators=[...] on my Image and File fields in my model? When I uncomment my import / validators settings everything works fine. It seems the validator is being hit and even setting the attributes on __init__ but then it just crashes after initializing all of the validators. My validator is: import magic from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as _ @deconstructible class MimeTypeValidator(object): def __init__(self, valid_mime_types): self.valid_mime_types = valid_mime_types def __call__(self, value): try: mime_type = magic.from_buffer(value.read(1024), mime=True) if not mime_type in self.valid_mime_types: raise ValidationError(_('%s is not an acceptable file type.' % value)) except AttributeError as e: raise ValidationError(_('This file type of %s could not be validated.' % value)) I'm setting it on my fields by doing: field = models.ImageField(....., validators=[MimeTypeValidator(settings.VALID_IMAGE_MIME_TYPES)] and similarly for file fields. -
Django Rest Framework Example
I am having problems with the example in the documentation. When I try going to the default route "/", I keep getting a 404. The way the documentation example reads, I should be able to get a User list? Here is the urls.py code: from django.contrib import admin from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] I have the rest_framework added to my application, too. I can see the various User related routes when I look at the router object via the manage.py shell, but I keep getting the 404. I am implementing this in an existing new project, but I have yet to actually put anything in the project so I don't think the issue … -
Running django-pdb in post mortem mode for a test command
I'm trying to run a test suite using python manage.py test, but I run into an error which ends like this: return self.cursor.execute(sql) django.db.utils.ProgrammingError: type "hstore" does not exist LINE 1: ..., "options" varchar(255)[] NOT NULL, "conditions" hstore NOT... I'd like to drop into the debugger at this point in order to see the full sql statement. To this end, I've run pip install django-pdb and added the following lines to my settings.py (as per the instructions): # Order is important and depends on your Django version. # With Django 1.7+ put it towards the beginning, otherwise towards the end. INSTALLED_APPS = ( ... 'django_pdb', ... ) # Make sure to add PdbMiddleware after all other middleware. # PdbMiddleware only activates when settings.DEBUG is True. MIDDLEWARE_CLASSES = ( ... 'django_pdb.middleware.PdbMiddleware', ) Then I try to re-run the test with the --pm option: python manage.py test lucy_web.tests.notifications --pm However, this is not recognized: manage.py test: error: unrecognized arguments: --pm I've also tried to run this command with --ipdb instead of --pm, but it seems to not work: I simply get an error message without dropping into the debugger. Any ideas what the issue might be? Is post mortem debugging perhaps not … -
Django displaying blog posts on different pages
I'm rather new to Django and I've been following a tutorial on building a simple blog application. My application works fine so far (using Django 1.8.6). Here are my urls.py, views.py and models.py: urls.py urlpatterns = [ url('admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), blog/urls.py 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'), url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), ] blog/views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) return render(request, 'blog/post/list.html', { 'posts': posts, 'tag': tag }) 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) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'similar_posts': similar_posts}) blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. Now I would like to create 4 … -
How to make my JSON work with a Gijgo grid in Django/Python?
I tried the code below to be able to show my database records in a Gijgo grid. Unfortunately it doesn't work, because Gijgo by default expects JSON data without keys. As far as I know there are two options to solve this problem: Get rid of the keys (model, pk, fields) in JSON, which is accepted by Gijgo Configure Gijgo to understand my JSON structure (couldn't find any information about this approach) Any idea how I can solve this problem? Code demand = Demand.objects.filter(week__number=request.GET["weeknumber"], week__year=request.GET["weekyear"]) response = serializers.serialize("json", demand) return HttpResponse(response, content_type='application/json') [{"model": "demand", "pk": 4, "fields": {"week": 3, "model": 1, "product": 3, "type": 7, "build": 1, "sdna": 1234, "rcna": 234234, "sdeu": 3333, "rceu": 433, "ssd": 53, "src": 63, "notes": "fafd"}}] -
Difference Between Reset Done and reset Complete in Django 2.0 Authentication Views
I'm looking at implementing user authentication to a Django project. I'm reading through the documentation. It mostly seems straightforward, but there's one thing that I don't understand. Apparently the authentication includes eight views: accounts/login/ [name='login'] accounts/logout/ [name='logout'] accounts/password_change/ [name='password_change'] accounts/password_change/done/ [name='password_change_done'] accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete'] When implementing a password reset I assume that what I want to do implement accounts/password_reset/, which forwards the user an email. Then, I need to implement accounts/reset/<uidb64>/<token>/, which is where the user is directed to via the email. What I'm not clear on is what that should do when the user has updated their password successfully. What's the difference between accounts/reset/done/ (or password_resest_complete) and accounts/password_reset/done/ (or password_reset_done)? -
Memcache works on localhost (without anything in settings.py)
My question is "can anybody corroborate or explain?" The following caching logic works as expected on localhost, but fails on heroku (queries every time): from django.core.cache import cache QUEUE_KEY = "queue" def index(request): queue = cache.get(QUEUE_KEY) if not queue: queue = QueueItem.objects.order_by("id") cache.set(QUEUE_KEY, queue) c = {'queue': queue} return render_to_response('index.html', c) -
Django forms - multiple choice field too many values to unpack (expected 2)
im trying to use a query set as the source for a multiple choice field and add a class to it in my forms.py. However I am receive the error too many values to unpack (expected 2) Would anyone know the cause for this? sub_types = SubnetTypes.objects.all() stypes = [] for st in sub_types: stypes.append(st.subnet_type) subnets = forms.MultipleChoiceField( choices=stypes, widget=forms.CheckboxSelectMultiple( attrs = {'class': 'form-control'} ) ) -
Django Url Not Matching
I have three urls: # Better Fund Detail Api url(r'funds$', api_views.Api.as_view()), url(r'funds/(?P<ticker_name>[^/]+)$', api_views.Api.as_view()), url(r'funds/(?P<ticker_name>[^/]+)/(?P<series_name>[.]+)$', api_views.Api.as_view()), When I goto this url: funds/BND/A it should match the third one but it doesn't. Any ideas? -
How to pass variable id from AngularJS to Django for SQL query
I have a table of employees when I click a row it will get the Id of the row and pass it to django sql query. This is my raw sql query in django class GetEmployeeDetailsApi(ListAPIView): queryset = EmployeeTb.objects.raw('SELECT * FROM EmployeTable WHERE EmployeeId = %s', [id]) serializer_class = GetEmployeeDetailsSerializer I already tried another a way to do this by fetching all records then filter it in front-end and it worked, but I do not want to do this because of security reasons, it exposes the whole table when I only need one record. -
django - get a list of joins between two models based on a third model
I have three models that are set up like so: class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey(to=A, null=True, blank=True) class C(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey(to=A, null=True, blank=True) The B-to-A relationship is one-one and the C-to-A relationship is many-one. I have a template where I want to show a list of all B.name, and for each B.name, have a list of C.name where C.a = B.a. What's the simplest way to do that? I know I can just get the list of Bs and the list of Cs, and for each B get B.a and search the list of Cs for the matching C.a, but is there a cleaner way to just get a queryset that combines both? -
user() missing 1 required positional argument: 'request'
I have a problem is that it does not let me use the limit_choice_to what I want is that according to the area that the logged in user belongs to, show me in that field the users that only belong to that area def user(request): if request.user: user = request.user userc = User.objects.get(empresa_area_id=user.empresa_area_id) return userc class Tickets(models.Model): alta = '1' media = '2' baja = '3' prioridades = ( (alta ,'Alta'), (media , 'Media'), (baja ,'Baja'), ) estados = ( (1,'iniciado'), (2,'terminado'), ) ticket_id = models.AutoField(primary_key=True) Usuario_id = models.IntegerField() area_destino_id = models.ForeignKey(Empresa_area,null=True, blank=True, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True) fecha_estimada = models.DateTimeField() tipo_id = models.ForeignKey(Tipo_ticket, null=True, blank=True, on_delete=models.CASCADE) prioridad = models.CharField(max_length=3, choices=prioridades) asunto = models.CharField(max_length=40) mensaje = models.TextField() estado = models.IntegerField(choices=estados, default=1) fecha_fin = models.DateTimeField(null=True, blank=True) consultor_id = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, limit_choices_to =user ) archivo_id = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE) At the moment of running the program, I am sent a user () missing 1 required positional argument: 'request' I would like to know what the problem is and how I can solve it -
Wagtail authentication error (User has a valid ticket but not a valid session) using django-cas server
Wagtail virtual environment has django-cas client [1] configured to allow users to use a django-cas-server [2] to log in, which has its own venv. When the user clicks to sign in, redirect to the CAS login page is done. Afterwards when user tries to login using a valid account (username/password), the Web Browser shows: "Forbidden Login Failed' In the terminal of wagtail, error is displayed: User has a valid ticket but not a valid session [03/Jan/2018 19:47:39] "GET /admin/login/?next=%2Fadmin%2F&ticket=ST-4w5TiBrICCZ1KdUQUtNtgW6coOMBb6FzZnraIi8MOuzjfbhPTabPrxKkiDmag HTTP/1.1" 403 38 Any help/suggestions to overcome this problem will be appreciated. References: [1] django-cas https://github.com/kstateome/django-cas [2] django-cas-server https://github.com/nitmir/django-cas-server -
Adding a Z prior to my query set
I have a few if statements, which identify a datareducecode. Everything is working correctly except for the last one, which is number 7 in the view below: if request.method == 'POST' and selectedaccesslevel == '3': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '5': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '6': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '7': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{coid}"', flat = True) print (datareducecode) I know it's because the values_list where I have 'f"Z{coid}"' to place a Z prior to the coid. I get the following error message: Cannot resolve keyword 'f"Z{coid}"' into field. Choices are: blevel, coid, dlevel, facilitydimension, rlevel, slevel, user My question is how do I get a Z prior to the results of datareducecode for selectedaccess == 7? datareducecode eventually get's saved to the database as datareducecode = list(datareducecode)[0] -
django.core.exceptions.FieldError: Unknown field(s) specified by user
I'm using Django 2.0 I have extended AbstractBaseUser model to create a custom User model. In my accounts/models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=False): if not email: raise ValueError('User must have an email address') if not password: raise ValueError('User must have a password') user = self.model( email=self.normalize_email(email) ) user.is_staff = is_staff user.is_superuser = is_admin user.is_active = is_active user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True, is_active=True ) def create_superuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True, is_admin=True, is_active=True ) class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=250, blank=False, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) groups = models.ManyToManyField(Group, blank=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' objects = UserManager() @property def is_staff(self): return self.is_staff @property def is_active(self): return self.is_active @property def is_superuser(self): return self.is_admin def __str__(self): if self.first_name is not None: return self.get_full_name() return self.email def get_full_name(self): if self.last_name is not None: return self.first_name + ' ' + self.last_name return self.get_short_name() def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): … -
Django migration: all the columns are not generated as the model
For all the tables some of columns are generated and some of columns didn't. Here is my models personalInfo.py from django.db import models # Create your models here. class Students(models.Model): student_name = models.CharField(max_length=100) student_id = models.CharField(max_length=50) student_dept = models.CharField(max_length=30) student_sec = models.CharField(max_length=2) class StudentDetails(models.Model): students = models.ForeignKey(Students, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField student_phone = models.BigIntegerField gpo_box_number = models.IntegerField class Teachers(models.Model): teacher_name = models.CharField(max_length=100) teacher_id = models.CharField(max_length=50) teacher_dept = models.CharField(max_length=30) class TeacherDetails(models.Model): teachers = models.ForeignKey(Teachers, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField teacher_phone = models.BigIntegerField gpo_box_number = models.IntegerField studentAdvising.py from django.db import models from personalInfo.models import Students, Teachers # Create your models here. class Advising(models.Model): student = models.ForeignKey(Students, on_delete=models.CASCADE) teacher = models.ForeignKey(Teachers, on_delete=models.CASCADE) subject_matter = models.CharField(max_length=400) comment = models.TextField starting_time = models.TimeField ending_time = models.TimeField date = models.DateField migration details for personalInfo.py # Generated by Django 2.0 on 2018-01-03 17:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='StudentDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Students', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('student_name', models.CharField(max_length=100)), ('student_id', models.CharField(max_length=50)), ('student_dept', models.CharField(max_length=30)), ('student_sec', models.CharField(max_length=2)), ], ), migrations.CreateModel( name='TeacherDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Teachers', … -
Management Command Testing with Django-Nose Database Issue
I'm working on generating unit tests for my django application, and I'm running into a bit of a snag. I'm working on a unit test that is used by the django application to generate data for the database nightly. This function is called my a manage.py command, and works find used standalone. However, when I use the following test to launch it, I get a missing table issue: # Test case def test_commit_volume_metric_generation(self): args = [ ... ] opts = {} call_command('generate_metrics', *args, **opts) #Output test_commit_volume_metric_generation (project.tests.UrlTestCase) ... Traceback (most recent call last): File "/home/ubuntu/main-site/project/management/commands/generate_metrics.py", line 236, in generate_one_metric project = Project.objects.get(id=project_id) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 381, in get num = len(clone) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 240, in __len__ self._fetch_all() File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, … -
Running python script periodically with crontab. Error
I'm using crontab to run this python script every minute: def cronSendEmail(): print("Hello") return True In the log file: /var/log/syslog Jan 3 23:37:01 brahmh CRON[4627]: (me) CMD (/home/venv/bin/python /home/proj/manage.py crontab run b74d4d1f47748498b81b5bcf863684c3 >> /home/proj/file.log # django-cronjobs for proj Jan 3 23:37:02 brahmh CRON[4626]: (CRON) info (No MTA installed, discarding output) These two statements are logged every minute. Why am I seeing 'no MTA installed, discarding output'? Also the program is not printing 'Hello' to the file.log as expected. Note: This is a django project and I'm using django-crontab to create the crontab jobs. -
Django on Heroku - ProgrammingError at / relation "..." does not exist
I'm getting this error. I know you usually get this error because the databases wasn't properly migrated. When I run heroku local web, the website works fine when I go to localhost:5000. However after I deploy the app to heroku with git push heroku master, the error comes up. In other words, it works in my local environment. But it does not work after deploying to heroku. I have Heroku-Postgres installed as an add-on in heroku. What could be causing this? -
Trying to create a home page with a login form, but getting 'NameError: name 'url' is not defined'
I'm relatively new to django and trying to create a home page that has a login form on it, consisting of username and pw bars. I was trying to recreate what I saw here in my own project: homepage login form Django but I keep getting back NameError: name 'url' is not defined. I am pretty lost on what is causing this. I was initially writing into the project level urls.py but then moved to the app level (accounts) urls.py because that makes sense to me...but I'm not confident about this. Here are my files: project ├── manage.py ├── db.sqlite3 ├── templates ├── accounts | ├──migrations | ├──_pycache_ | ├──admin.py | ├──apps.py | ├──models.py | ├──_init__.py | ├──urls.py | ├──tests.py | └──views.py └── project ├── settings.py ├── urls.py └── wsgi.py project/settings.py from django.urls import reverse_lazy import os ... SITE_ID = 1 LOGIN_URL = reverse_lazy('login') LOGIN_REDIRECT__URL = reverse_lazy('home') LOGOUT_REDIRECT__URL = '/' enter code here project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), path('accounts/', include('allauth.urls')), path('', include('posts.urls')), ] accounts/urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUpView.as_view(), name='signup'), url(r'^accounts/', HomeView.as_view(template_name='../templates/home.html', name='home')), url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', … -
Subclass a views in django-registration-redux
I'm using Django-registration-redux and I want give more data to a view for render my base template. I read the example in doc. My url.py: class MyPasswordChangeView(PasswordChangeView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context['book_list'] = Book.objects.all() #example in doc context_dict = services.get_base_data_for_views(request) return context_dict urlpatterns = [ ... path('accounts/password/change/', MyPasswordChangeView.as_view( success_url=reverse_lazy('auth_password_change_done')), name='auth_password_change'), ... ] I have the extra data in services.py but this code gives error: name 'request' is not defined so context_dict isn't definited. Should I write another function? Thank you -
Get full URL image with object ID - Django Rest Framework
I write a Serializer in Django Rest Framework about Profile have Avatar Image but I want to get full URL Image instead of ID. My Serializers (which return profile_pic_url is ID): class ProfileDetailSerializer(ModelSerializer): profile_pic_url = SerializerMethodField() class Meta: model = Profile fields = [ 'profile_pic_url', ] def get_profile_pic_url(self, obj): request = self.context.get('request') profile_pic_url = obj.profile_pic_url.image return request.build_absolute_uri(profile_pic_url) This code returns this issues: 'ImageFieldFile' object has no attribute 'find' -
Command "python setup.py egg_info" failed with error code 1 When installing Django
Egg_info Error getting this error when attempting to pip install Django. Is there something i am doing incorrectly?? -
Why Django redirects me to my api view after save a record with ajax?
I have a problem, I'm using Django with restframework to develop a school project but when I save a record with ajax this redirects me to the api page and not to the CRUD page, only admins can see the api page(view) so... Can you help me to resolve this? this is my views.py class pacientesList(generics.ListCreateAPIView): queryset = Paciente.objects.all() serializer_class = pacienteSerializer permission_classes = (IsAuthenticated, ) def list(self, request): queryset = self.get_queryset() serializer = pacienteSerializer(queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): serializer.save(user=self.request.user) and this is my ajax code to save data $("#btnGuardarPaciente").click(function() { $.ajax({ url: '{% url "core:pacientes_list" %}', type: 'POST', data: $("form").serialize(), dataType: 'json', success: function(data) { console.log(data); // only to see if this is working alert("Paciente agregado!."); $("#exampleModal").modal('toggle'); }, error: function(xhr, resp, text) { console.log(xhr, resp, text); } }); }); It's working fine, this save the record into db but only the problem is when I click on save button this redirects me to my api page and not to the CRUD page. my html form <form id="savePaciente" action="{% url 'core:pacientes_list' %}" method="post" >{%csrf_token%} <md-form> <input type="text" required name="first_name" class="form-control" id="id_first_name" placeholder="Nombre(s)"> <input type="text" required name="last_name" class="form-control" id="id_last_name" placeholder="Apellidos"> <label for="id_gender">Selecciona el sexo</label> <select class="form-control" name="gender" id="id_gender" required> … -
django: list transfer to template and to JS
In Views.py i create a list variable - mortgages_counter.append(MonthlyPaymentAmount) it is transferred to .html template as: <input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter}}'> in JQuery (separate file i have to check if each element of this list is used). value is transferred to .js file as: var mortgages_counter = $('#mortgages_counter').val(); but according to console it was transferred as a string to Jquery - like ['1234','125'] and its length is 1 because of some reason, also check like access to index [0] gives - ' and [1] - 1 etc. how to operate with this list as with LIST and NOT a string?