Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we update the required model field in Django rest framework/Django forms
DRF I am trying to make update in profile serializers in my models.py But when i am trying to update some other fields like bio or address. It says the phone number is already taken. DJANGO FORMS In case of forms if my user's profile is to be updated. I cannot update only email address as it says the field is required. Questions Is there is any way to bypass the form / drf.serializers validators Why, when I update my user's email( which is required field in my case) says "The username is already taken". -
Is it possible to authenticate using more than two variable in django?
I have created a custom user model in django? there are many fields including email, password and username. Now I want to authenticate using username,password and email while login. How should I do that? -
How can is get the user profile detail to work properly in django
I am trying to include a profile feature in a simple blog site. I have created a profile model using the one to one link for the user field, also created a function view for the profile detail with corresponding template name but i keep getting a 404 error. user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) username = models.CharField(max_length=15, default='Anonymous') dp = models.ImageField(null=True) country = models.CharField(max_length=20, null=True) age = models.IntegerField(null=True) joined = models.DateTimeField( auto_now_add=True) class Meta: ordering = ['joined'] def __str__(self): return self.username def get_absolute_url(self): return reverse('profile_detail', args=[str(self.id)]) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save()``` views.py def profile_detail(request, pk): user = get_object_or_404(User, pk=pk) context = {'user': user} return render(request, 'milk/profile_detail.html', context) profile_detail.html {% extends 'milk/base.html' %} {% block title %} {% endblock %} {% block content %} <h2>{{ user.get_full_name }}</h2> <ul> <li>Username: {{ user.username }}</li> <li>Location: {{ user.profile.country }}</li> <li>Age: {{ user.profile.age }}</li> </ul> {% endblock %} template referencing <a href="#" class="nav-item"><em class="name">{{user.get_username }}</em></a> urls.py path('profile/<int:pk>/', views.profile_detail, name='profile_detail'), -
Django contrib.auth.forms Bug? - get_invalid_login_error never reached
I was just about to subclass the login form of django.contrib.auth.forms: "class AuthenticationForm(forms.Form)" after dealing a bit with the code I was about to customize the user_is.active check in order to display a customized message at my login. I was wondering as I was not able to figure out at what point exactly the user_is.active really gets validated. The clean method does a call to another function called confirm_login_allowed but from my perspective this never gets reached?! I test against this with a user that is not active but I always get back self.get_invalid_login_error instead of confirm_login_allowed error message. Can smb. confirm that this is a bug or at least at what point confirm_login_allowed gets triggered ? def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) def get_user(self): return self.user_cache def get_invalid_login_error(self): return forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) -
Modal is working fine locally but not working in hosted web
This is my code which is working fine on localhost but not working on hosting. {% extends 'layout2.html' %} {% block content %} <div class="container"> <div class="row"> <ol class="col-12 breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'home' %}">Home</a></li> <li class="breadcrumb-item active">Menu</li> </ol> <div class="col-12"> <h5 style="font-size: 30px">Menu</h5> <hr> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-sm"> <!-- card start --> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="../static/images/cake.jpeg" alt="Cake" style="width:100%;height: 185px;"> <div class="card-body"> <h5 class="card-title">Cake <span class="badge badge-danger">HOT</span> <span class="badge badge-light">Rs.250</span></h5> <h2></h2> <p class="card-text">Different varities of cakes. With customized design. You can select you own flavour. Click below to view details and order.</p> <a href="#" data-toggle="modal" data-target="#myModal" class="btn btn-primary" style="width: 100%"> View Details</a> <!-- <button type="button" class="btn btn-info btn-lg" >Open Modal</button> --> <!-- Modal-1 --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Order cake now.</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-4"> <img src="../static/images/cake.jpeg" alt="" style="widows: 100px;height: 185px;"> </div> <div class="col-md-8"> <address > <h6> Product Name: Cake</h6> <h6> Product Flavour: customized</h6> <h6> Product category: Best seller</h6> <hr> <h6> Availible in both veg and non-veg.</h6> <h6> Weight of cake is as per customer reqirement.</h6> <h6> You can place order below.</h6> … -
How to save model data using custom button instead of using Save button in Django admin
I want to add a custom button X along with Save button in admin form and whenever I click the button X I want to save the current data and send an email. I don't want to send email after every save so cannot use post_save signals. I am able to add the custom button. How can I add this functionality for button X? -
How to download the data from postgresql
Now I have a postgresql database on server. I want to change the server so I want all the data from postgresql on server to my PC and able to upload it in another server postgresql database. Is it possible if not suggest me any alternative. -
select2 with multi forms (the same form)
I have a formset in django, I've used select2 for autocomplete, but it only work for the first form, wont affect others, I need to provide id forms dynamically! this my template //increase forms <script> $('#add_model').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('.model_formset').append($('#model_empty_formset').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> //my select2 <script> $(document).ready(function(){ $('#0model').select2() }) </script> <form method="POST">{% csrf_token %} {{ model.management_form }} {% for form in model.forms %} <div class="col-12 row mx-auto p-2 model_formset"> <div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5"> {{form.model_name | add_class:'col-12 text-center' | attr:'id:0model'}} </div> <div class="input-group mx-auto inp col-12 col-sm-10 p-1 col-md-5"> {{form.serial_number | add_class:'col-12 text-center'}} </div> </div> {% endfor %} <div id="model_empty_formset" class="col-12 row mx-auto p-2" style="display: none; border-top:1px solid white;border-radius: 30px;"> <hr class="col-10 bg-light"> <div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5"> {{model.empty_form.model_name | add_class:'col-12 text-center'}} {% if model.empty_form.model_name.errors %} <div class="error col-12 mx-auto"> {{model.model_name.errors }} </div> {% endif %} </div> <div class="input-group mx-auto inp col-12 col-sm-10 p-1 col-md-5"> {{model.empty_form.serial_number | add_class:'col-12 text-center'}} {% if model.empty_form.serial_number.errors %} <div class="error col-12 mx-auto"> {{pcmodel.serial_number.errors }} </div> {% endif %} </div> </div> <div class="col-12 col-sm-7 col-md-3 mx-auto"> <button class=" btn-block mt-1 shadow-lg border-right border-left">insert</button> </div> </form> How can I replace 0 in 0model with form id? -
body { background: rgba(240, 234, 234, 0.897) url("images/background.gif") no-repeat; }
Template code {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} CSS code li a { color: rgb(13, 238, 43); } body { background: rgba(240, 234, 234, 0.897) url("images/background.gif") no-repeat; } There is an background.gif in polls/static/images/background.gif Except the background image, all the styles are presented correctly in the browser. What might be the reasons? Thank you for your help! -
Python Django psycopg2.errors.StringDataRightTruncation: value too long for type character
Im am the following code in my pycharm console, my date is length is clearly less than the mentioned field size, when why this error my code df=pd.read_csv('/home/asif/Documents/Projects/TaxVisor/legal.txt',header=None,names=['type']) for type in df['type']: ... print(type) ... print(len(type)) ... LegalElement.objects.create(type=df['type']) My model: class LegalElement(models.Model): type = models.CharField(max_length=25, null=False) my data(from csv) PTY LTD PTY. LTD PTY. LIMITED PTY. LTD. PTY LTD. PTY LIMITED PROPRIETARY LTD. PROPRIETARY LTD PROPRIETARY LIMITED My DB create table company_registration_legalelement ( id serial not null constraint company_registration_legalelement_pkey primary key, type varchar(25) not null ); my error: Traceback (most recent call last): File "/home/asif/DevProjects/taxvisor/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(25) -
Why can't I push a new blog comment to the Django database (foreign.key model relationship)
I would like to create a new comment object if the user submits his comment. Along with the modelform content I deliver the link to a gif which is rendered outside the form in the html. The view is triggered via an async AJAX call. Currently it throws this error: IntegrityError at /post_comment/ C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py in post_comment comment.save() … ▼ Local vars Variable Value comment Error in formatting: TypeError: __str__ returned non-string (type NoneType) gif None name None post_id None request <WSGIRequest: GET '/post_comment/'> text None views.py def post_comment(request): # Assign search term gif = request.GET.get('gif_src') name = request.GET.get('name') text = request.GET.get('text') post_id = request.GET.get('post_id') comment = Comment( post=post_id, name=name, text=text, gif=gif) comment.save() return render(request, 'post.html', comment) models.py # Comment Model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=200) text = models.TextField() gif = models.CharField(max_length=1000) created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=True) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text forms.py # Blog Post Comment Form class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'text',) Async ajax view call (function($) { $('.comment-button').on('click', function(e) { // Assign the contents var gif_src = $('#giphy-out').children().attr('src'); var name = $('#form-name').text(); var text = $('#form-text').text(); var post_id = $('#post_id_hidden').text(); // Prevent … -
DRF filter of lookups in the HTML Forms
I am using Django 3.05, Django Rest Framework 3.11.0, Python 3.7 Background I have setup a an object level security model to ensure a User can only read/write data to an Organisation or Venue to which they have access. This is controlled through an OrganisationMembership mapping User to Organisation. To create or update an Venue a user must be assigned to the Organisation. This all works via the Django Rest Framework's API when used the way my application will access. It's taken a little setup but gives the desired permissions. However, I am also using the DRF's HTML Forms to test and I cannot find any mechanism to change the QuerySet to restrict access to the Organisation names in the drop down list The drop down list therefore incorrectly shows Top Secret Organisation data to which I am not permitted on the OrganisationMember +-----------+--------------+ | Raw Data | HTML Form | +----------------------------------------------+ + | | | Organisation: v☑︎ Org 2 - I have access (McDonalds) v | | v Org 1 - I have access (Burger King) v | | v Org 3 - I should not see (Top Secret) v | +-------------------------------------------------------------+ Screen grab here 1 Note attributes in … -
Import py file from the root inside Django views
I have a file called functions.py located in the root that I want to import from multiple apps (inside the views). How can I import that file? -
display django form/model choices as individual html buttons
trying to get my html page to display model / form choices as individual buttons that i can then style a different color , red, green, blue etc... can anyone help? models.py class Color(models.Model): """color choice of a user""" COLOR_CHOICES = ( ('RED', 'Red'), ('GREEN', 'Green'), ('BLUE', 'Blue'), ) color = models.CharField(max_length=60, choices=COLOR_CHOICES, default='RED') name = models.CharField(max_length=60) def __str__(self): return self.name forms.py class ColorForm(forms.ModelForm): color = forms.ChoiceField(choices=Color.COLOR_CHOICES,) class Meta: model = Color fields = ('name', 'color') views.py def add_color(request): """add a color request to the database""" if request.method == 'POST': form = ColorForm(request.POST) if form.is_valid(): form.save() return redirect('color_me:colors') else: form = ColorForm() return render(request, 'color_me/add_color.html', {'form': form}) add_color.html <pre> <form method="post"> {% csrf_token %} <p>{{ form.name }}</p> <ul class="list-group"> <button type="button"> {{ form.color.0 }} </button> <button type="button"> {{ form.color.1 }} </button> <button type="button"> {{ form.color.2 }} </button> </ul> {% buttons %} <button type="submit" name="button">Add request</button> {% endbuttons %} </form> </pre> -
Django Change Image Format and Quality
Django project Im trying to compress uploaded images and change their format Currently it only compresses png images but when a jpg image is uploaded it does not change the format nor does it compress the image please help sir models.py import sys from PIL import Image from io import BytesIO from django.db import models from django.contrib.auth.models import User from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.exceptions import ValidationError class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/userpfp/', blank=True) def __str__(self): return self.user.username def compressImageMain(self,image): if self.image: def save(self, *args, **kwargs): if not self.id: self.image = self.compressImage(self.image) super(UserProfile, self).save(*args, **kwargs) def compressImage(self,image): imageTemproary = Image.open(image) outputIoStream = BytesIO() basewidth = 520 wpercent = (basewidth/float(imageTemproary.size[0])) hsize = int((float(imageTemproary.size[1])*float(wpercent))) imageTemproaryResized = imageTemproary.resize( (basewidth,hsize) ) imageTemproaryResized.save(outputIoStream , format='PNG', quality=50) outputIoStream.seek(0) image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.png" % image.name.split('.')[0], 'images/userpfp/png', sys.getsizeof(outputIoStream), None) return image else: pass -
django-channels asgi deploy problems
On localhost(on my pc) everything works fine, no errors, but when I deploy it on ubuntu server, django-channels stop working correctly, the problem is not working consumers.py file, and sure I can't connect to websockets, console error: reconnecting-websocket.js:209 WebSocket connection to 'ws:///' failed: Error during WebSocket handshake: Unexpected response code: 200 CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } asgiref==3.2.7 daphne==2.5.0 Django==3.0.6 channels==2.4.0 channels-redis==2.4.2 I deploy on the server by these steps: https://channels.readthedocs.io/en/latest/deploying.html, when I use this command daphne myproject.asgi:application daphne runs correctly but errors still the same js file: // websocket scripts var loc = window.location var formData = $("#form") var msgInput = $("#id_message") var chatHolder = $("#chat-items") var me = $("#myUsername").val() var wsStart = 'ws://' if (loc.protocol === 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new ReconnectingWebSocket(endpoint) socket.onmessage = function(e){ console.log("message", e) var chatDataMsg = JSON.parse(e.data) chatHolder.append("<li>" + "<div>" + chatDataMsg.avatar + "<span class=\"itwork-Nus-Medium\" style='margin-left: 4px;'>" + chatDataMsg.name + "</span>" + "</div>" + "<div class=\"itwork-Nus-Regular\">" + chatDataMsg.message + "</div>" + "</li>") } socket.onopen = function(e){ console.log("open", e) formData.submit(function (event) { event.preventDefault() var msgText = msgInput.val() var finalData = { 'message': msgText } … -
Uploading images to amazon cloudfront / S3 via python/django
I am uploading images on amazon S3 bucket, via django/python backend and I am using django-storages Image uploading was all working okay, with some minor delay, but now when I am trying to upload, it takes a few seconds, and then process breaks, saying, image didn't upload. I could see images on S3 bucket, however, ( I think because of this delay ) django doesn't update the uploaded file information on DB (Postgres), and frontend says, image didn't upload. So this is kind of break, and I am not sure how to fix this. Please help if anyone has faced similar issues. I have referred to other questions and articles, for example, but don't know if I should go for any optimization or if there is a simple way to fix this problem. -
Heroku django admin panel looks like not normal
Im created a heroku server. I did all setups, urls etc. But when I trying access to django admin panel using https://demoherokutest48.herokuapp.com/admin/ all css contents disappear. I dont know why happening. But all sql tables prefectly transfered to heroku. Only css contents disappeared. Note: I tryed run at local in my pc. Its perfectly worked. I think problem is about at heroku. -
Django-mptt Category - Parent and Childrens
yesterday i used django-mptt for category, i have a question about it. categorys information as you see, i have a parent category with 2 childrens, when i select a children category for my Post... children template details so that Post is count for children but for parent is empty. parent template details did we have a solution for that or i have use ManyToMany field for my Post model and select both of them? -
getting a variable from a Django view using AJAX GET request
I want to send a variable "seconds_left from my django view to my template that will update the timer displayed. I have created a separate view that will will handle calculating the seconds left and send it in a json object. seconds_left is attached to the Answer model, I am using AJAX GET request to get the json objects but I keep getting an error: TypeError at /study/timer_view/1/ Object of type Question is not JSON serializable views.py @csrf_exempt def timer_view(request, order): participant = get_object_or_404(Participant, user=request.user) now = timezone.now() condition = participant.condition.name field1 = condition[0] field2 = condition[1] filed3 = condition[2] == 'S' question_list = Question.objects.filter(field1 = field1, field2 =field2, field3=True).order_by('order') if order == 1: question = question_list[0] elif order == 2: question = question_list[1] answer, created = Answer.objects.get_or_create(participant=participant, question=question) seconds_left= (now - answer.created_at).total_seconds() seconds_left = int(seconds_left) answer.seconds_left=seconds_left completion_time = 30 - seconds_left context = {'question': question, 'answer': answer, 'seconds_left': seconds_left, 'condition': condition} json = JsonResponse(context) return json template.html function updateTimer (){ $.ajax({ type: "GET", url: server_url+ currentPath, success: function (data) { console.log(data); timeLeft = data.seconds_left; } }); document.getElementById("base-timer-label").innerHTML = formatTime( timeLeft); } what is the best way to call that variable to be able to use it in my javascript … -
Send ajax request to django and update html
I am writing a Web Application with Django that through ajax POST request executes on the server some code written in python, and should retrieve on the client side the output as a JSON and update the html partially with javascript. I can send the request to the server and execute the subprocess, also do i retrieve the JSON Data but not updated in the html but shown as a dictionary to the website without the html content. So the last part is not working, and i figured out that for the ajax request when i test it in the view function it returns false. Another Problem is that the subprocess has a File as output so I can not catch the stdout from the subprocess view.py: def call(request): call_form = Call(request.POST) print(request.is_ajax())->returns false? if call_form.is_valid(): purity_arg = call_form.cleaned_data['purity'] chr_sex = call_form.cleaned_data['chromosomal_sex'] command = "cnvkit.py call -m clonal --purity %s --drop-low-coverage %s" % ( purity_arg, chr_sex) process_call = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,cwd=sfs.path('cnv_app/call_CNS/'), universal_newlines=True) stdout, stderr = process_call.communicate() if process_call.returncode and stderr: output_call += stdout + '\n' output_err_call += stderr + '\n' else: output_call += stdout + '\n' process_call.poll() response = {'output_call': output_call, 'output_err_call': output_err_call} return JsonResponse(response) .html: <h2>Call</h2> <p>Given segmented log2 … -
How to act for groups of an existing user - Django
How to act for groups of an existing user - Django I have registered users but in the edition it will be possible to update the user's groups. How can I just update the groups. I know it has a function for this, but I don't remember. Thank you friends. group = Group.objects.get(id=id) group.update(user) -
While hosting my django web application on heroku I am getting error like this
I built my site. It has a static folder that contains files of CSS, js, jquery. When I try to host this I am getting the following error. #error# re mote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'css/all.min.css' failed! remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'webfonts/fa-brands-400.eot' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7fa7eaa6d518>. remote: The CSS file 'css/all.min.css' references a file which could not be found: remote: webfonts/fa-brands-400.eot remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need … -
How to translate only custom error messages in DRF?
In DRF all default error messages are already translated. But I need to translate my own error messages. What did I do: Put all my error messages into _(), where _ is gettext In settings set LOCALE_PATHS to locale folder Ran python manage.py makemessages -l ru That created .po file and here goes the first trouble. In the .po file are my messages and besides that there are a lot of default django messages which I don't want to translate. (I do not want to override the translation, I want to extend it) I translated my messages in the .po file, then I ran python manage.py compilemessages which created .mo file. And here is the second trouble. All my messages are now translated, but default DRF messages (they were not in the .po file, there were Django messages, not DRF) are not already translated, they are only in english (e.g. Authentication credentials were not provided, This field is required, etc.) -
How do I update blog article in django using model forms?
I am creating a blog using django. I am using model Forms for input.I want to edit an existing blog post, but I can't get this to work. models.py class Article(models.Model): title = models.CharField(max_length=60) post = HTMLField() editor = models.ForeignKey(User,on_delete=models.CASCADE) tag = models.ManyToManyField(tags,blank=True) pub_date = models.DateTimeField(auto_now_add=True) article_image = models.ImageField(upload_to='articles/', blank=True) photo_credits = models.CharField(max_length=60,default='unsplash.com') Forms.py class UpdateArticleForm(forms.ModelForm): class Meta: model = mode fields = ['title','article_image','post','tags','photo_credits'] Views.py @login_required(login_url='/accounts/login/') def update_article(request,id): instance = magazineApiModel.objects.get(id = id) if request.method == 'POST': form = UpdateArticleForm(request.POST, request.FILES,instance=instance) if form.is_valid(): form.save() return redirect('index') else: form = UpdateArticleForm(instance=instance) return render(request,'article/update.html',{'form':form}) urls.py url(r'^article/update/$',views.update_article,name='update_article'), I get a 404 error.and if I replace the url with the below I get a Reverse for 'update_article' with no arguments not found. 1 pattern(s) tried: ['article/update/(?P<id>[0-9]+)/$'] url(r'^article/update/(?P<id>[0-9]+)/$',views.update_article,name='update_article'), How can I get this to work ?