Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form validation doesn`t work with invisible reCaptcha
Im trying to implement new invisible reCaptcha with my contact form, but in this case my standart form validation doesnt work. All fields in my form is requierd, however if I type in some incorrect data or miss something - page just reloads with the same data but I will not get standart message with error near field. With reCaptha v2 it works fine. But when trying to use invisible one Im able to press submit button even form is empty. Is there any way to validate form at first? Im using custom decorator to send post request. my settings.py GOOGLE_RECAPTCHA_SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' NOCAPTCHA = True decorators.py from functools import wraps from django.conf import settings from django.contrib import messages import requests def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False messages.error(request, 'Invalid reCAPTCHA. Please try again.') return view_func(request, *args, **kwargs) return _wrapped_view views.py from .decorators import check_recaptcha @check_recaptcha def feedback(request): if request.method == 'GET': form = FeedbackForm() else: form = FeedbackForm(request.POST) if form.is_valid() and request.recaptcha_is_valid: subject = form.cleaned_data['subject'] … -
dJango data model relations
I am new to Django and trying to understand while working on a project. My system has many tables and wants to know how to model if the relationship of tables are selective. Following is an example : Classes Person, Role and License. Person (many people) Role (A,B) License : Driver’s license I am trying to understand how to use Django model for this. I need License model assigned to Person only if Role B or C assigned. I do not want it if Role A is assigned. License is unique to each person only if role B or C is assigned to Person. For role A, I need to assign blanks to license. -
Django performance with `not in` filter with giant list?
I am currently making a school project where I am building a website that lets you rate nearby restaurants (1-5 stars). The only caveat is that I will show users the restaurants based on location (e.g. closest ones first) and that once they have rated a restaurant, it will never be shown to them again. Currently I have something like this in mind class User(models.Model): username = models.CharField(primary_key=True, max_length=20) location = models.SomeGeoPointField ... class Restaurant(models.Model): title = models.CharField(primary_key=True, max_length=20) location = models.SomeGeoPointField ... class Rating(models.Model): for = models.ForeignKey(User, on_delete=models.CASCADE) from = models.ForeignKey(Restaurant, on_delete=models.CASCADE) rating = models.IntegerField() I am having trouble thinking how the query would look like, and if I used a not in to filter out existing ratings, about the possible performance hit -
Django + uWSGI/nginx inside docker container - ImportError: No module named .wsgi
This an ancient Django (v1.3.7) application that I'm migrating over to a Docker setup. The basic framework comes from this dockerfiles repo. I can get the app running fine using Django's built in dev server (./manage.py runserver), but I'd like to have this served using uWSGI/Nginx in production. I can get uwsgi to run without errors when I call it from a bash prompt within the the container like so: uwsgi --http :8000 --wsgi-file /home/docker/code/siteweb/glrimon.wsgi However, when I try to import my wsgi file from the Django shell I get the same import error. Here is the what gets logged when I startup the container (which calls /usr/local/bin/uwsgi --ini /home/docker/code/uwsgi.ini via supervisord): [uWSGI] getting INI configuration from /home/docker/code/uwsgi.ini *** Starting uWSGI 2.0.15 (64bit) on [Tue May 9 13:35:14 2017] *** compiled with version: 5.4.0 20160609 on 05 May 2017 18:06:55 os: Linux-3.16.0-77-generic #99~14.04.1-Ubuntu SMP Tue Jun 28 19:17:10 UTC 2016 nodename: 222b58f8d3ea machine: x86_64 clock source: unix detected number of CPU cores: 8 current working directory: / detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use … -
Django -how to make a combobox depenedent of the choice of other combobox
i have 2 dropdown lists on my form , the second combobox related of the choice of other combobox the source code of forms.py v_type = forms.ChoiceField( choices=VEHICLE_TYPE,widget=forms.Select(attrs={'class':'form-control'})) v_sub_type = forms.ChoiceField(choices=VEHICLE_SOUS_TYPE,widget=forms.Select(attrs={'class':'form-control'})) the data of coices are just into a list variable enter image description here -
ValueError at /url/ The view frontend.views.url didn't return an HttpResponse object. It returned None instead
I am writing a piece of code that will parse a page when user enters the url in the form field in a page: "url.html". When users enters the url in the form field, it comes here in this view(in the instance.web_url). However im getting this error of HTTPResponse object. Here's the code: def url(request): if request.method == 'POST': form_url = WebURLForm(request.POST or None) title = "Search via URL here" instance = form_url.save(commit = False) instance.save() if instance.web_url == "": instance.web_url = "http://www.facebook.com/" print instance.web_url html = urllib.urlopen(instance.web_url).read() soup = BeautifulSoup(html,"lxml") lines = [] # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.get_text() #break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) #break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) #drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) text=text.encode('utf-8') words = text.split(".") count=0 terrorism_level=0 for i in words: print count if not words[count]: words[count] = "this was empty before." json_result = natural_language_classifier.classify('90e7b7x198-nlc-50734',words[count]) classes = json_result['classes'] result = json.dumps(classes, indent=2) if (classes[0]['confidence'] > 0.98 … -
ValueError: Dependency on app with no migrations: customuser
I am trying to start a webproject using the framework django, this is my first web-developement project. After creating the project im trying to start an App that creats Customized users and registration with email validation using django-registration the result that i had after manage runserver is shown in this image : Results on PowerShell this is what my models.py file contains from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): username = models.CharField(max_length=255, unique=True, verbose_name=_("Username")) email = models.EmailField(unique=True, verbose_name=_("Email Address")) favorite_animal = models.CharField(max_length=255, verbose_name=_("Favorite Animal")) -
python if elif else only returning first output without using logic
I have an if elif else block that is only producing output for the if statement even if it should return the other conditions. Even if I change the order of the conditions it always returns the first one. My code is as shown below: for customer in queryset: if feat_list() < 12: customer.Service_Level = Service.objects.get(service_name = 'Silver Package') silver_customers.append(customer.Name) elif 11 < feat_list() <= 15: customer.Service_Level = Service.objects.get(service_name = 'Gold Package') gold_customers.append(customer.Name) else: customer.Service_Level = Service.object.get(service_name = "Platinum Package") platinum_customers.append(customer.name) customer.save() How can I change these statements so that it uses logic not the order? -
Django: Launch a server-side computation and dynamically update the client
I am creating a web application with Django (back end) and JavaScript (front end). The main scenario is the following: a client asks the server to train a neural network (which can take quite a lot: seconds or even minutes, sometimes). Immediately after sending the request, the client shows to the user how the training session is going; it does so by retrieving and displaying the training error, which is actually just a number. For training the network I made this function, which I implemented as a generator: def train(network, trainset): # [setup variables...] while (current_error > target_error): # [continue to train the network...] # [update current_error...] yield current_error On the front end (a simple HTML page) I have a JS script for retrieving data dynamically from a Django view. My Django view goes something like this: def getError(request): # ... generator = train(net, dataset) return StreamingHttpResponse(generator) At the moment I can retrieve the data with an AJAX call but I always have to wait for the server to train the whole neural network before I can see the training errors. My problem is that I would like the user to view the error updates while the server is training … -
Django multi model form, save or update on one model
I have 2 models in 1 form. in this form data can be changed. On 1 model (Sloep_core) there will onle be updates. the other model (Sloep_gegevens) will only do updates, but if the value 'sloepnaam' changed in the form the record must be a insert and not a update. I have tried to put soms code together (with some search actions). I come to the code below but now it is always a insert the code. Is someone have a idea to get it right? model.py: class Sloep_core(models.Model): FSN_nummer = models.IntegerField(unique=True) HT_nummer = models.IntegerField(unique=True, blank=True, null=True) SRNL_nummer = models.IntegerField(blank=True, null=True) sloep_type = models.CharField(max_length=128, blank=True) werf = models.CharField(max_length=255, blank=True) info = models.TextField(blank=True) objects = SloepManager() def __str__(self): return str(self.FSN_nummer) class Sloep_gegevens(models.Model): sloep = models.ForeignKey(Sloep_core, on_delete=models.CASCADE, default='') sloepnaam = models.CharField(max_length=128) thuishaven = models.CharField(max_length=128, blank=True) date = models.DateField(auto_now=True) __original_sloepnaam = None def __init__(self, *args, **kwargs): super(Sloep_gegevens, self).__init__(*args, **kwargs) self.__original_sloepnaam = self.sloepnaam def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.sloepnaam != self.__original_sloepnaam: # then do this force_insert = True else: # do that force_update = True super(Sloep_gegevens, self).save(force_insert, force_update, *args, **kwargs) self.__original_sloepnaam = self.sloepnaam class Meta: ordering = ["date"] def __str__(self): return self.sloepnaam form.py: class SloepGegevensForm(forms.ModelForm): class Meta: model = Sloep_gegevens exclude = … -
Datetime On Django on models?
So I just wanna ask if there is a documentation on the datatype for the Django or you can give me the specific datatype to get a datetime field on models. The latter is preferable because I have a turtle and unstable net which makes surfing a little hard. This is my current class and class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) contact_no = models.CharField(max_length=40) email = models.EmailField() def __str__(self): return self.first_name I want to add a birthday field. -
Django trying to parse gpxfile passed from FileFieldView form
I am allowing a user to upload gpx files, these are then cleaned and then passed to a function to input to the model. The files are validated by a custom clean() method and if any files don't pass then an exception is raised. my form.py: class FileFieldView(FormView): form_class = UploadGpxForm template_name = 'dashboard/upload.html' # Replace with your template. success_url = reverse_lazy('dashboard:index') # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): for f in request.FILES.getlist('gpx_file'): SaveGPXtoPostGIS(f) return self.form_valid(form) else: return self.form_invalid(form) and my SaveGPXtoPostGIS: def SaveGPXtoPostGIS(f): gpx = parse(f) #lot's of other stuff my problem seems to be that when I upload files through the form I get the following error: GPXXMLSyntaxException at /dashboard/upload/ Error parsing XML: Start tag expected, '<' not found, line 1, column 1 thanks for any help, I've been banging my head against this for hours. -
How to make autocomplate?
I have form with 2 fields. First field user_characteristic is СhoiseField and the second field description is simple 'Textarea'. I want autocomplate second field when user select some value from first field. I use JQuery UI autocomplete. Here below you can see my code. Where I did mistake? forms.py: RequirementForm(forms.ModelForm): class Meta: model = Requirement fields = ('user_characteristic', 'description',) widgets = { 'user_characteristic': forms.Select(attrs={'class': 'form-control', 'id': 'user-characteristic',}), } def __init__(self, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['user_characteristic'] = forms.ChoiceField( choices=[(x.user_symbol, x.user_class) for x in UserCharacteristic.objects.all()], ) self.fields['description'].widget = Textarea(attrs={'class': 'form-control', 'id': 'description',}) views.py: def requirement_autocomplete(request): if request.is_ajax(): word = request.GET.get('term', '') user_characteristics = UserCharacteristic.objects.filter(user_class__icontains=word) results = [] for user_characteristic in user_characteristics: user_characteristic_json = { 'id': user_characteristic.id, 'label': user_characteristic.user_class, 'value': user_characteristic.user_class, 'user_characteristic_description': user_characteristic.user_symbol + ' – Варианты использования для роли ' + user_characteristic.user_description } results.append(user_characteristic_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) javascript: $("#user-characteristic").autocomplete({ source: "/requirement_autocomplete/", minLength: 0, select: function( event, ui ){ $("#user-characteristic").val(ui.item.value); $("#description").val(ui.item.user_characteristic_description); return false; } }); -
Django SMTP EmailBackend not working
I'm trying to send email through Django with the default SMTP backend. I configured my settings: EMAIL_HOST = 'mail.mydomain.nl' EMAIL_HOST_USER = 'myusername' EMAIL_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is my company's own email server. When I try manage.py sendtestemail or send_mail in a view I keep getting the following error: smtplib.SMTPRecipientsRefused: {'personalemail@gmail.com': (554, b'5.7.1 <52D95A25.cm-11-1b.dynamic.ziggo.nl[X.X.X.X]>: Client host rejected: Access denied')} I made this small script to test sending from pure Python and it works fine: import smtplib sender = 'me@mydomain.nl' receivers = ['personalemail@gmail.com'] message = 'This script works.' try: smtpObj = smtplib.SMTP('mail.mydomain.nl', 587) smtpObj.login('username', 'password') smtpObj.sendmail(sender, receivers, message) print('Successfully sent email') except Exception as e: print('Error unable to send email {0}'.format(e)) Is there something in Django's SMTP EmailBackend that I am not aware of that could be causing the problem? This is Django 1.11.1 on Python 3.6 . -
Database error when adding an object to a ManyToMany field
so I've been trying to create a list of staff, that is additional people who are allowed to for now, see and modify the project that is created in a generic Django app. The problem is, when creating a project and adding the user that created it to the staff_list field, I get an error OperationalError at /projects/create/ no such column: projectManager_project_staff_list.project_id My Project model: from django.db import models from django.conf import settings from folderManager.models import Folder from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.utils.text import slugify from django.core.urlresolvers import reverse from trackManager.models import Track from django.contrib.auth.models import User class Project (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) #the author staff_list = models.ManyToManyField(User, related_name = "Staff") title = models.CharField(max_length = 100) slug = models.SlugField(unique=True) description = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("projects:project_detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-timestamp", "-updated"] @property def tracks(self): instance = self qs = Track.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type My Project Create view: def project_create(request): form = ProjectForm(request.POST or None) user = User.objects.get(username=request.user.username) ''' tried to see if using a defined user variable instead of request.user … -
Django: cretae new object with unique order
I have a simplified model: class Example(models.Model): name = models.CharField(max_length=255, blank=False, null=False) order = models.PositiveIntegerField(blank=False, null=False, unique=True) class Meta: ordering = ['order'] How I can create a new object with existing order number? If I create a new object with an order number 6 for example, then previous 6 and higher orders should have their order number increased by one (7, 8, etc.). Another question is how I can reorder existing objects? Ideally, I could do it by drag and drop in admin but it should be also possible by typing new order number directly. I have initially thousands of objects and reasonable maximum I can think of now should be less than 100,000. Normally I add new objects programmatically from JSON file and some individual changes can be done in admin. I already tried to implement this with django-admin-sortable but no success so far. Also, I'm not sure if it can handle the case of programmatical insertion. -
passing json var in leaflet "on()" methode
I'm working (with Django framwork) on a map with the leaflet library, I want to show some text in a div when I click on a marker. I've made a JS function to create a div with some text in it: function create_div(text): { div = document.createElement(div); div.id = 'article'; div.textContent = text; document.body.appendChild(div); } and then I call this function in the "on" methode given by leaflet because I want to call it when I click on a marker : var articles = {{ list_json | safe }}; for (var i = 0; i < {{ nb_of_articles | safe }}; i++) { var text = articles[i].fields.text; //I put the text of the i-th marker in text. var lat = articles[i].fields.lat; var lon = articles[i].fields.lon; var marker = L.circleMarker([lat,lon]); marker.on('click', function(e) {create_div(text);} ); marker.addTo(mymap); } It kinda work but it put the text of the last object in all the div associate with my marker. For example if I have article[0].fields.text = "hello" article[1].fields.text = "world" I get "world" in the divs, regardless of the marker I click on. I would like "hello" in the div when I clik on the first marker, and "world" in the div when I … -
Image Management API using Django Rest Framework (ImproperlyConfigured Error)
I was learning about DRF and went through the tutorial, making a pastebin style snippets app. I wanted to make an Image management app, processing (list and detail) requests such as GET,PATCH,PUT,DELETE etc. I made some changes to process images files rather than text field, and ran the server. But on accessing the API through browser, following error was shown ImproperlyConfigured at /api/photo/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://127.0.0.1:8000/api/photo/ Django Version: 1.10.7 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Exception Location: /home/dhruv/.virtualenvs/djangodev/lib/python3.5/site-packages/rest_framework/relations.py in to_representation, line 386 Python Executable: /home/dhruv/.virtualenvs/djangodev/bin/python Python Version: 3.5.2 Python Path: ['/home/dhruv/Assignment/tutorial', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/dhruv/.virtualenvs/djangodev/lib/python3.5/site-packages'] urls.py urlpatterns = [ url(r'^api/photo/$', views.PhotoList.as_view(), name='myphoto-list'), url(r'^api/photo/(?P<pk>[0-9]+)/$', views.PhotoDetail.as_view(), name='myphoto-detail'), url(r'^users/$', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) view.py class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer class PhotoList(generics.ListCreateAPIView): permission_classes … -
Sending Django query to Ajax call
I need to reference a database where I grab all the data that match a parameter which is inputted by the user. There can be up to 10 objects in the call and I need to grab multiple values from those objects. Is there a way I can send a filtered query to ajax and display the values? Ajax: <script> $("#id_iden").on('change', function(){ if ($(this).val() !== ""){ var qn = $(this).val() $.ajax({ url: "/ship/ajax-shipping/", data: { 'quote': qn }, dataType: 'json', success: function(data){ if (data.i){ #tried i.item and i[0[ $("#id_item").val(data.jax) } } }) } }) </script> View: def ajax_shipping(request): id_quote = request.GET.get('quote', None) quote = HomeTable.objects.filter(id=id_quote).values_list('quote_num_id', flat=True) items = IItemDetails.objects.filter(quote_num_id=quote).values_list('item', 'quan', 'shipped') data = { 'i' : items, } return JsonResponse(data) Is there a way I can show the values of a query with ajax? Thanks! -
Django returns 403 error on POST request with Fetch
I have a graphql server implemented using graphene-django. I can make queries to it using jquery like this: function allIngredients() { return 'query{allProducts{edges{node{name}}}}' } var query = allIngredients(); $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.post("/graphql", {query: query}, function(response) { console.log(response); }) However, when I try this call with Fetch, I get a 403, because of the CORS issue. I solved the same problem in jQuery by adding ajaxSetup... before the call. Looking at the docs fetch('/graphql', { method: "POST", headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ csrfmiddlewaretoken: '{{ csrf_token }}', query:`{allProducts{ edges{ node{ id name orderPrice sellPrice } } }`}) } ) .then(function(response) { if (response.status >= 400) { throw new Error("Bad response from server"); } return response.json(); }) I tried adding csrfmiddlewaretoken to the body in the similar way as I did in jQuery example, no luck. I tried adding credentials: 'include' as [the docs say][2], again no luck. I tried with credentials: 'same-origin' and combining this options differently, again the same result. Web is unusually quiet about this, what am I doing wrong? -
How to reinitialize scripts inside django admin when new inline object is added?
I have two models with foreignkey relationship. Inside admin panel one of them displays like inline object and has a django-leaflet map inside. Inlines added with 'Add another' button have empty input instead of a map. So i need to initialize scripts again, how would i do that? -
Celery daemon spawning multiple processes for single worker with systemd
I'm trying to use django with celery & celerybeat to run periodic tasks. I have my celery process setup with systemd as [Unit] Description=my celery daemon After=network.target [Service] PIDFile=/var/run/celery/celery.pid Type=forking User=myuser Group=www-data RuntimeDirectory=celery RuntimeDirectoryMode=0770 WorkingDirectory=/opt/myapp/ ExecStart=/opt/myapp/.virtualenv/bin/celery multi start worker1 \ --app=myapp \ --concurrency=1 \ --schedule=/var/run/celery/celerybeat-schedule \ --pidfile=/var/run/celery/celery.pid \ --logfile=/opt/myapp/log/celery.log \ --loglevel=INFO \ --beat ExecStop=/opt/myapp/.virtualenv/bin/celery multi stopwait worker1 \ --pidfile=/var/run/celery/celery.pid \ --logfile=/opt/myapp/log/celery.log \ ExecReload=/opt/myapp/.virtualenv/bin/celery multi restart worker1 \ --pidfile=/var/run/celery/celery.pid \ --logfile=/opt/myapp/log/celery.log \ [Install] WantedBy=multi-user.target This all works fine.. but I notice it spawns 3/4 processes despite there being only 1 worker, and concurrency being set to 1. Why is this? My goal is to have 1 worker running that will queue tasks up, rather than perform them synchronously for now. -
Access variables in the Redirect in django
Templates are rendered in login based on groups.How can I access these variables in my template.For example how can I access these variables in redirect like the context in render? Here is my code. Views.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) all_requests= Retest.objects.all() projector_requests = Eventprojector.objects.all() classroom_requests = Eventclassroom.objects.all() lab_requests = Eventlab.objects.all() mikesystem_requests = Eventmikesystem.objects.all() extensioncable_requests = Eventextensioncable.objects.all() auditorium_requests = Eventauditorium.objects.all() graphicshall_requests = Eventgraphicshall.objects.all() u = User.objects.get(username=username) if user is not None: if user.is_active: login(request, user) if user.groups.filter(name='Rep').exists(): return redirect('/rep') elif #..........(other groups) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) else: return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) return render(request, 'retest/login.html') def rep(request) return render(request, 'retest/home.html', {}) urls.py url(r'^$', views.login_user, name='login_user'), url(r'^rep$', views.rep, name='rep'), -
Reverse for 'edit_article' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['edit-article/(?P<pk>\\d+)$']
I urgently need to perform a task to edit the article from a blog. I want to get the id of the article to be edited and update the record based on that id. I get the following error in code. Reverse for 'edit_article' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['edit-article/(?P\d+)$'] Here's my code: def edit_article(request, pk): activity = Customer.objects.get(pk = pk) if(request.method == 'POST'): form = activityPostForm(request.POST, request.FILES, instance = activity) if(form.is_valid()): title = request.POST.get('title', '') description = request.POST.get('description', '') image = request.FILES['image'] activity.title = title activity.description = description activity.image = image activity.save() return redirect("/blog") else: form = activityPostForm() return render_to_response("edit-article.html", {"form" : form}) url: url(r'^edit-article/(?P<pk>\d+)$', views.edit_article, name = "edit_article"), template: {% for activity in activities %} <label class = "label"> Title: </label> <div class = "activity-title"> {{ activity.title }} </div> <label class = "label"> Description: </label> <div class = "activity-description"> {{ activity.description }} </div> <label class = "label"> Image: </label> <div class = "activity-image"> <img src="images/{{activity.image}}" style="width:300px;height:300px;"/> </div> <a class="edit" title = "edit" href="{% url 'edit_article' pk=activity.pk %}"> Edit Article </a> <br><br> {% endfor %} -
Django can't find static files after changing name of folder in project path
I have a Django project that I have been working on and I want to change the name of a folder in the project's file path. My current path to my project looks like this: '/Users/user/Documents/Python/Django Projects/ProjectName/' I want to change the project path to: '/Users/user/Documents/Python/Django_Projects/ProjectName/' When I do this I get the following error message: OSError at / [Errno 2] No such file or directory: '/Users/user/Documents/Python/Django Projects/ProjectName/assets' In my settings.py file I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = (os.path.join(BASE_DIR, 'assets'), ) In the request META the PWD value is unchanged: PWD '/Users/user/Documents/Python/Django Projects/ProjectName' I'm fairly new to programming so I apologise for asking such a simple question, but any help would be greatly appreciated. Thanks