Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DynamicRelationField not detected
I am using dynamic-rest. According to the documentation, I have this model with a dynamically generated foreign key: class PscSerializer(DynamicModelSerializer): class Meta: model = PSC name = 'psc' fields = ('id', 'description', 'created', 'modified', 'pscno', 'productno', 'serviceno', 'luns') luns = DynamicRelationField('LunSerializer', many=True) Which produces: Exception Type: AttributeError at /api/v1/pscs/ Exception Value: luns is not a valid field for <class 'pscs.models.PSC'> Sure, luns is not a field in the PSC model, but a dynamic field. What is going on? What am I doing wrong here? -
NoReverseMatch at /blog/ Django 2.0.5
I am following a Django tutorial, and because of different Django version. I had this problem and I could not figure it out. NoReverseMatch at /blog/ 'blog' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 2.0.5 Exception Type: NoReverseMatch Exception Value: 'blog' is not a registered namespace Exception Location: /Users/sumeixu/anaconda3/lib/python3.6/site-packages/django/urls/base.py in reverse, line 84 Python Executable: /Users/sumeixu/anaconda3/bin/python Python Version: 3.6.3 Python Path: ['/Users/sumeixu/djangotest', '/Users/sumeixu/anaconda3/lib/python36.zip', '/Users/sumeixu/anaconda3/lib/python3.6', '/Users/sumeixu/anaconda3/lib/python3.6/lib-dynload', '/Users/sumeixu/anaconda3/lib/python3.6/site-packages', '/Users/sumeixu/anaconda3/lib/python3.6/site-packages/aeosa'] Server time: Thu, 7 Jun 2018 14:32:43 +0000 urls.py(blog): from django.conf.urls import url from django.urls import path from . import views urlpatterns =[ path('',views.list_of_post,name='list_of_post'), path('<slug:slug>/',views.list_of_post,name='post_detail') ] urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls'),name='blog'), ] views.py def post_detail(request,slug): post = get_object_or_404(Post,slug=slug) template = 'blog/post/post_detail.html' return render(request,template,{'post':post}) -
Django Rest Framework serializer is imported in a module and disappears when imported into another
I have a serializer called AgencyGroupSerializer in my serializers.py and I import it to views.py and everything works perfectly. I want to use such serializer in utils.py so I import it but, when I do so, views.py raises an error telling that the serializer doesn't exist in serializers.py when it works perfectly when it is no imported in utils.py. This is how I import the serializer in views.py: from ReservationsManagerApp import serializers, models This is how I import the same serializer in utils.py: from ReservationsManagerApp.serializers import AgencyGroupSerializer And this is the traceback I get: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e036b70> Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/utils/functional.py", line 36, β¦ -
Implementing Multiple User Types with flags in Django Rest Framework
Hey Guys I started working on a project with django rest framework, since it was said to be the best framework for perfectionists with deadlines. So I created a User and Profile Model and also implemented a Model Manager for the creation like so token_generator = default_token_generator SHA1_RE = re.compile('^[a-f0-9]{40}$') class Verification(models.Model): """ An abstract model that provides fields related to user verification. """ has_email_verified = models.BooleanField( default=False ) class Meta: abstract = True class UserProfileRegistrationManager(models.Manager): """ Custom manager for ``UserProfile`` model. The methods defined here provide shortcuts for user profile creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. """ @transaction.atomic def create_user_profile(self, data, is_active=False, site=None, send_email=True): """ Create a new user and its associated ``UserProfile``. Also, send user account activation (verification) email. """ password = data.pop('password') user = User(**data) user.is_active = is_active user.set_password(password) user.save() user_profile = self.create_profile(user) if send_email: user_profile.send_activation_email(site) return user def create_profile(self, user): """ Create UserProfile for give user. Returns created user profile on success. """ username = str(getattr(user, User.USERNAME_FIELD)) hash_input = (get_random_string(5) + username).encode('utf-8') verification_key = hashlib.sha1(hash_input).hexdigest() profile = self.create( user=user, verification_key=verification_key ) return profile def activate_user(self, verification_key): """ Validate an verification key and activate the corresponding β¦ -
Django : Mezzanine Setting
I've applied some migrations to Mezzanine module past year, and now this test is failing : from mezzanine.conf.models import Setting def test_editable_caching(self): """ Test the editable setting caching behavior. """ # Ensure usage with no current request does not break caching from mezzanine.core.request import _thread_local del _thread_local.request setting = Setting.objects.create(name='SITE_TITLE', value="Mezzanine") original_site_title = settings.SITE_TITLE setting.value = "Foobar" setting.save() new_site_title = settings.SITE_TITLE setting.delete() self.assertNotEqual(original_site_title, new_site_title) The fail trace is : Traceback (most recent call last): File "/srv/lib/mezzanine/mezzanine/conf/tests.py", line 227, in test_editable_caching self.assertNotEqual(original_site_title, new_site_title) AssertionError: 'Your Site' == 'Your Site' Your site is the default value of SITE_TITLE in settings.py, so it look like the Setting class doesn't have effect anymore. Have you ever had this problem and solved it ? Thanks in advance ! -
Django + Celery + MySQL
I am working on integration of celery and django and I have a question: How to properly use db connectors/sessions in this case. There is like 50~ different tasks but they usually work like the example i've shown. url_check.py @shared_task(name='check_status_code') def check_status_code(url): r= requests.get(url) return r.status_code mysql_tasks.py @shared_task(name='status_check_results_insert') def status_check_results_insert(results,id): insert_query_1 = Insert into log_table(res_num, url_id) values( ...); insert_query_2 = insert into results_table(res,url_id); setup_queues.py def setup_url_check_queue(): query= 'select url_id,url from xxx.urls' query_results = **execute query in proper way** for url_id, url in query_results: check_status_code.apply_async([url],link=status_check_results_insert.s(url_id)) Goal: 1. Execute query like 'select url_id,url from xxx.urls" 2. For each row from query_results execute 'check_url(url)' task. 3. Save results for each of the row into db(as linked taks). Sometimes there is more than 1 query to execute. 4. Setup django-celery beat to execute 'setup_queues' every 24 hours.(this is done) The problem is I don't want to create connection on every mysql_task, execute queries and close connection. I wanted to use SQLAlchemy , create sessionmaker object in celery.py and then import it to mysql_tasks.py but i feel like it's not the best idea. celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parsing_hub.settings') app = Celery('v_celery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(['v_celery']) engine = create_engine(PROD_DB_PASS['SQLAlchemyURI'], pool_size=15, pool_recycle=720) metadata = β¦ -
How do I perform action after paypal payment is complete?
I copied the code: <body> <div id="paypal-button"></div> <script> paypal.Button.render({ env: 'production', // Or 'sandbox', commit: true, // Show a 'Pay Now' button style: { color: 'gold', size: 'small' }, payment: function(data, actions) { /* * Set up the payment here */ }, onAuthorize: function(data, actions) { /* * Execute the payment here */ }, onCancel: function(data, actions) { /* * Buyer cancelled the payment */ }, onError: function(err) { /* * An error occurred during the transaction */ } }, '#paypal-button'); And onAuthorize, I would like download a file specified in my project folder after the payment has been completed. Is there any way to to do this? So far when I finish the payment the transaction is approved and money is sent and I would like the download action to follow. -
Django pass time value and user value to forms.py
I have a model like this: from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField(default) completed = models.BooleanField(default=False) description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) def summary(self): return self.description[:50] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def __str__(self): return self.title I have a forms.py like this because I don't want the user to be able to determine which user is saving the data and I want the pub_date to be the time now: from django import forms from .models import Task from django.utils import timezone class Taskform(forms.ModelForm): class Meta: model = Task fields = ['title', 'description', 'completed'] My view is like this: @login_required def create(request): form = Taskform(request.POST or None) task = Task() task.pub_date = timezone.datetime.now() task.user = request.user if form.is_valid(): form.save() return redirect('') return render(request, 'home/create.html', {'form': form}) I want to pass the time and the user to the form as it validates but I'm not sure how? -
How to test a celery on_failure and on_retry tasks in a base class
I have this celery abstract class how do i proceed to to test the two methods. Thanks from celery.app.task import Task class BaseTask(Task): abstract = True def on_retry(self, exc, task_id, args, kwargs, einfo): LOGGER.error('{0!r} failed: {1!r}'.format(task_id, exc)) super(BaseTask, self).on_retry(exc, task_id, args, kwargs, einfo) def on_failure(self, exc, task_id, args, kwargs, einfo): LOGGER.error('{0!r} failed: {1!r}'.format(task_id, exc)) csuper(BaseTask, self).on_failure(exc, task_id, args, kwargs, einfo) -
Django Complex Query: combined output
models.py class DeviceType(models.Model): device_type = models.CharField(max_length=200,unique=True) def __str__(self): return self.device_type class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True) mac_address = models.CharField(max_length=200,blank=True,null=True) Above is my models.py file. I want to write a query such that I get the output in the following format: device_type-serial_number-model-brand -
select_related multiple tables
i have 3 models: class book(models.Model): id = models.AutoField(primary_key=True) publisher= models.ForeignKey(Treatment, related_name='weights') def __str__(self): return str(self.weight) def __repr__(self): return str(self.publisher.id) class reader(models.Model): publisher= models.ForeignKey(publisher, related_name='readers') class publisher(models.Model): date = models.DateTimeField() I'm trying to get all the readers who reads specific book, i dont have connection between reader and book, only via publisher table, i tried to get this information with: Book.object.select_related(publisher__readers__id='x') but I'm getting error. It is possible to get information from multiple tables like my model? thanks -
Updating timestamps of a model and its related parent with the same time
Let's say I have the following models: class Blog(TimeStampedModel): summary = models.TextField() text = models.TextField() class BlogComment(TimeStampedModel): author = models.CharField() text = models.CharField() blog = models.ForeignKey(Blog, models.CASCADE, related_name='comments') class BlogTag(TimeStampedModel): name = models.CharField() blog = models.ForeignKey(Blog, models.CASCADE, related_name='tags') All three inherit from the following model, which implements some timestamp handling: class TimeStampedModel(models.Model): last_changed = models.DateTimeField() created_at = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): try: self._meta.get_field('blog') except models.FieldDoesNotExist: self.last_changed = timezone.now() super(TimeStampedModel, self).save(*args, **kwargs) else: now = timezone.now() self.ticket.last_changed = now self.last_changed = now with transaction.atomic(): super(TimeStampedModel, self).save(*args, **kwargs) self.ticket.save() class Meta: abstract = True The basic idea behind the custom save() is that when for example a comment (instance of BlogComment) is updated, it should update the last_changed timestamp of both the comment instance and the related blog entry. Unfortunately, the timestamp setting is not perfect since it overrides the blog's timestamp when its own save is called and the times end up being just slightly different: In [1]: b = Blog.objects.get(id=1) In [2]: comment0 = t.comments.all()[0] In [3]: b.last_changed, comment0.last_changed Out[3]: (datetime.datetime(2018, 6, 7, 12, 54, 12, 516855, tzinfo=<UTC>), datetime.datetime(2018, 6, 7, 10, 22, 09, 201690, tzinfo=<UTC>)) In [4]: comment0.text Out[4]: 'Some text' In [5]: comment0.text = 'test' In [6]: β¦ -
How download file from django admin
In my models.py I have class Part. In this class I have : origin = models.FileField(upload_to='origin_files') So I can upload file to directory "origin_files". How I can download this file using django admin? -
django: how to see that email and username are always stored in lowercase or unique even if not lowercase
I want to store username and email for each user and want them to be unique I have two options: 1) save both the username and email in lowercase so that their uniqueness is checked by the model by default 2) store them whatever way the user provides (can be mix of lower and upper case). Then how to ensure they are distinct. Also when i user the authenticate() to authenticate the username and password. How to ensure that it checks irrespective lower or upper case. -
reorder django dynamic form field
I am not able to reorder django form field which I am generating dynamically. class VideoForm(forms.Form): video_width_height = forms.CharField() video_fps = forms.IntegerField() video_type = forms.ChoiceField(choices=VIDEO_TYPES) #VIDEO_TYPES has been defined above def __init__(self, *args, **kwargs): super(VideoForm, self).__init__(*args, **kwargs) with connection.cursor() as c: c.execute('SELECT companyName from productionCompany') self.fields['production'] = forms.ChoiceField(choices=[(i[0], i[0]) for i in c.fetchall()]) Now, I have tried field_order = ['production','video_width_height', 'video_fps', 'video_type'] But still it shows production field at the bottom of the form. The thing is that it successfully changes the order of static fields like video_fps, video_type and video_width_height. field_order = ['production','video_type', 'video_width_height', 'video_fps'] But the dynamic field is always at the bottom. Any help on this? -
Django: get all models of an app (including abstract)
The method get_models() does not return abstract model classes. Is there a way to get all model classes of an app (including abstract models)? -
Create django app for functionality only
I'm just starting with django even if i'm no new to python, so i'm creating a testing project just to explore django features, workflow and so on. I already made apps (like the usual polls, books, etc), but now i would like to make an app that gives only functionality with no model nor pages (views and templates): a simple app with some function to be called from the main django project or other apps. I used the startapp command to crete all the boilerplate, but i cannot understand where to write my code, since it's not a model nor a template etc. Anyone has already faced this scenario? Thanks in advance to anyone who can point me in the right direction. -
Error when i load and create video in Django
My function in django will receive a video from my site, it's saving normally. I create a function create: def create(self, request): Video.objects.create(file=request.data['file'], creator=self.request.user) return Response('ok') I'll define the function by my way. But when i load a file from disk: request.data['file'] = open('/home/developer/Pictures/teste.webm') it's giving me an error when i create the object: def create(self, request): request.data['file'] = open('/home/developer/Pictures/teste.webm') Video.objects.create(file=request.data['file'], creator=self.request.user) return Response('ok') OutPut: *** TypeError: readonly attribute So i verify the type of my variables. (Pdb) type(request.data['file']) <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> (Pdb) request.data['file'] = open('/home/developer/Pictures/teste.webm') (Pdb) type(request.data['file']) <type 'file'> Ok, i know now the types are different, but how i turn my local file in <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> -
Determine which fields to look for(select2) in a specific django field admin
I have this model class Appointment(models.Model): patient = models.ForeignKey(Profile, on_delete=models.CASCADE) doctor = models.ForeignKey(Profile, on_delete=models.CASCADE) nurse = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField() .... in django admin I define search and autocomplete fields: search_fields = ( 'patient__first_name', 'patient__last_name', 'doctor__first_name', 'doctor__last_name', 'nurse__first_name', 'nurse__last_name', ) autocomplete_fields = ['patient', 'doctor', 'nurse'] I have tried to do this: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'patient': kwargs['queryset'] = Profile.objects.filter(role=PATIENT) if db_field.name == 'doctor': kwargs['queryset'] = Profile.objects.filter(role=DOCTOR) if db_field.name == 'nurse': kwargs['queryset'] = Profile.objects.filter(role=NURSE) return super().formfield_for_foreignkey(db_field, request, **kwargs) But it doesn't work with select2 widget, that applies when i want to add search. Is there a way to filter queryset to a certain field? -
Django 2 and MySQL
I have connected Django to Mysql using the following code: DATABASES = { 'default': { 'NAME': 'polls', 'ENGINE': 'mysql.connector.django', 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'autocommit': True, }, } } I have also downloaded mysql.connector from web and also using brew install mysqlclient and pip.But this gives me the following error: error image Here is the code of models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text def good(self): if self[0]=='C': return 'No' else: return 'Yes' 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 self.choice_text -
Why can't I install m2crypto in pipenv on OSX?
Anyone know what I could be doing wrong. I'm trying to switch from pip3 to pipenv I keep getting this error on osx when trying to install uwsgi and m2crpyot: https://pastebin.com/FZZUpcwa pipenv install -r requirements2.txt Requirements file provided! Importing into Pipfileβ¦ Pipfile.lock (6adb91) out of date, updating to (10e36a)β¦ Locking [dev-packages] dependenciesβ¦ Locking [packages] dependenciesβ¦ Updated Pipfile.lock (10e36a)! Installing dependencies from Pipfile.lock (10e36a)β¦ An error occurred while installing https://gitlab.com/m2crypto/m2crypto/-/archive/0.27.0/m2crypto-0.27.0.zip#egg=4dd1b7f! Will try again. An error occurred while installing lxml==3.6.1! Will try again. π ββββββββββββββββββββββββββββββββ 95/95 β 00:03:30 An error occurred while installing uwsgi==2.0.14! Will try again. Installing initiallyβfailed dependenciesβ¦ Collecting 4dd1b7f from https://gitlab.com/m2crypto/m2crypto/-/archive/0.27.0/m2crypto-0.27.0.zip#egg=4dd1b7f Installing collected packages: 4dd1b7f Exception: Traceback (most recent call last): File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 335, in run use_user_site=options.use_user_site, File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/req/__init__.py", line 49, in install_given_reqs **kwargs File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 748, in install use_user_site=use_user_site, pycompile=pycompile, File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 961, in move_wheel_files warn_script_location=warn_script_location, File "/Users/timo/.local/share/virtualenvs/jm-web-G18c0xlX/lib/python3.6/site-packages/pip/_internal/wheel.py", line 316, in move_wheel_files assert info_dir, "%s .dist-info directory not found" % req AssertionError: 4dd1b7f .dist-info directory not found β€ ββββββββββββββββββββββββββββββββ 0/3 β 00:00:00 and I've run into similar issues before with pip on mac that I could fix is the previous fixes I used when using β¦ -
Storing a form submitted Image in a django ImageField within specific folder
I have a django model form. One of the fields in the form is a ImageField with a set path to a specific folder to store the images. I want to grab the image that is submitted with the form and name of the image. I want the image itself store in the folder and the name to store in the database to be able to grab it whenever I need it. I looked around and there were not usable answers to fixing this problem for me. Here is my code: Models.py: user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='static/images/profile_pics/', height_field=500, width_field=500, max_length=100) bio = models.TextField() views.py: if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): cd = form.cleaned_data first_name = cd['first_name'] last_name = cd['last_name'] profile_pic = cd['profile_pic'] bio = cd['bio'] new_profile = Profile.objects.create( first_name = first_name, last_name = last_name, bio = bio, profile_pic = profile_pic, dob = dob, ) this is what is sent in the request: Here is the directly with the path I want to store the images in. -
Django edit button redirects to create form
My Django edit button always redirects to my Create form and creates a new record. I want an edit function that allows me to edit an existing record. No idea why it keeps returning the create form instead! home.html: {% extends 'base.html' %} {% block content %} {% for task in tasks %} <div class="row pt-3"> <h1>{{ task.title }}</h1> <br> <p>{{ task.pub_date_pretty }}</p> <br> <p>{{ task.summary }}</p> <br> <br> <p>{{ task.user }}</p> <br> <br> </div> <div class="row pt-3"> <a class="btn btn-primary" href="{% url 'edit' task.id %}">Edit</a> </div> {% endfor %} <br> <br> <a class="btn btn-primary" href="{% url 'create' %}">Create</a> {% endblock %} views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Task from django.utils import timezone def home(request): tasks = Task.objects return render(request, 'home/home.html', {'tasks': Task.objects.all().order_by('-pub_date')}) def taskdetail(request, task_id): task = get_object_or_404(Task, pk=task_id) return render(request, 'home/taskdetail.html', {'task':task}) @login_required def create(request): if request.method == "POST": if request.POST['title'] and request.POST['description']: task = Task() task.title = request.POST['title'] task.description = request.POST['description'] task.pub_date = timezone.datetime.now() task.completed = False task.user = request.user task.save() return render(request, 'home/taskdetail.html', {'task':task}) else: return render(request, 'home/create.html', {'error':'All fields are required'}) else: return render(request, 'home/create.html') @login_required def edit(request, task_id): if request.method == "POST": if request.POST['title'] and request.POST['description']: β¦ -
Django Rest Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name
I'm working on my project but getting an error when I go to profile. click login shows the error. Although I have check a lot of i can not find what's wrong. I have two templates profile.html and index.html Can anybody see what I'm missing? My code: page index.html {% load rest_framework %} {% load static %} {% block branding %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li> <a class="nav-link js-scroll-trigger" href="#services">Services</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'profile' %}">Login</a> </li> </ul> </div> </div> </nav> {% endblock %} page profile.html {% load rest_framework %} {% load static %} <head> <title>Users</title> </head> <body> <ul> {% for user in users %} <li>User name : {{ user.username }}</li> <li>User email: {{ user.email }}</li> {% endfor %} </ul> </body> -
Checkbox sits on top of the label instead of to the left of the label
I am using a bootstrap multiselect plugin in my project but for some reason the checkboxes and labels are not inline. please see pic below. This is what I am trying to achienve. Is there a simpler solution to fix this problem? Thanking you in advance.