Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing super class methods in django
I have the following model, a User class User(AbstractBaseUser, PermissionsMixin, Base): email = models.EmailField(db_index=True, unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(db_index=True, null=False, unique=True, max_length=255) A base class class Room(Base): name = models.CharField(db_index=True, unique=True, max_length=255) status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True) members = models.ManyToManyField(User) last_activity = models.DateTimeField(default=timezone.now) And two children class LeagueRoom(Room): league = models.ForeignKey(League, on_delete=models.CASCADE, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True) class ClubRoom(Room): club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True) I want to access the leagueroom_set for the user. I'm not sure how to do this. The user currently has a property room_set, but I wish to access the specific room_set. Can someone help me with this? -
Is there a way I can speed up this code or is this the fastest it'll go?
I have a function that's running in Django. It's supposed to calculate distance of a location based on user location. It works, the only problem is I feel my current implementation may be lacking in performance. It tends to take quite a bit of time. Here's the code: def resolve_near_by_branches(self, info, **kwargs): ul_raw = kwargs.get('user_location') ul_l = ul_raw.split(',') user_location = (float(ul_l[0]), float(ul_l[1])) final_b = [] if kwargs.get('category') is None: es = Establishment.objects.distinct().all() else: es = Establishment.objects.distinct().filter( category__code_name__exact=kwargs.get('category'), ) for e in es: for branch in e.branches.all(): b_l = (float(branch.location.latitude.replace(' ', "")), float(branch.location.longitude.replace(' ', ""))) # if geodesic(user_location, b_l).km < 9000000: final_b.append((geodesic(user_location, b_l).m, branch)) final_data = sorted(final_b, key=lambda x: x[0]) print(final_data) # print([i[1] for i in final_b]) return [i[1] for i in final_data] If you have any suggestions on how I can speed this up, please contribute. -
How to serve another static root in Django for static html pages?
The typical configuration serves two static roots: http://www.example.org/static/ http://www.example.org/media/ This is STATIC_URL and MEDIA_URL. I would like to add a third one to host static files build with Sphinx: http://www.example.org/docs/ I know I could configure this on the level of the web server. Is it also possible to configure this on the level of Django? -
Django request.method == 'POST' returning false
Currently working on my first django web application so still quite rusty. Trying to create a page that allows a lecturer to create a new class, the class is then added to the lecturers list of classes. As far as I can tell, from following a tutorial, the request.method in my views.py should return a POST, but is currently returning GET. Because of this, the new class created is never saved to the database. here is my views.py def create_class(request): if request.user.is_lecturer: print(" ") print("user is lecturer") form = classForm() print(request.method) if request.method == 'POST': print("") print("request method equals post") form = classForm(request.POST) if form.is_valid(): if request.POST.get("create_class"): lecturer = LecturerProfile.objects.get(lecturer=request.user) subject = Class.objects.get_or_create(class_name=form.cleaned_data["class_name"], class_description=form.cleaned_data["class_description"], lecturer=lecturer) LecturerProfile.Classes.add(subject) form.save(commit=True) return index(request) else: print("") print(form.errors) else: print("") print("request method fail") else: return HttpResponse("You are not allowed here") return render(request, 'student_feedback_app/create_class.html', {'form':form}) forms.py class classForm(forms.ModelForm): subject = forms.CharField(max_length=40, help_text="Class Name", required=False) class_description = forms.CharField(max_length=200, required=False, help_text="Class Description") slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Class fields = ('subject', 'class_description',) my create_class.html <!DOCTYPE html> <html> <head> Create a new class <h1> Create a new class</h1> </head> <body> <div> <form id="" method="post" action="/lecturer/classes/"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} … -
Django "LIKE" query for JSONField
I have created model like this: class Customer(models.Model): name = models.CharField(max_length=200) data = JSONField() and data filed has this structure: Customer.objects.create(name='David', data={ fields: [ {id: 1, value: "abc"}, {id: 2, value: "efg} ] }) If we filter objects with exact data.fields.item, we can do like this: Customer.obejcts.filter(data__fields__contains=[{id: 1, value: "abc"}]) If we want to filter objects with data.fields.item but with not exact data.fields.item.value as follows, how can we do this? Thanks very much! Customer.obejcts.filter(data__fields__contains=[{id: 1, value: "b"}]) -
Django email form help, only shows the send button and no other boxes
I have followed many tutorials for django contact forms, idk if this is even the easiest way, im using django to make a site and i need a contact form, and when on the site it only displays the send button. -
geoDjango on heroku
I'm using heroku to develop a django backend. I would like to enable geoDjango to use spatial feature with my models. I followed all the steps that are describe on the django and heroku docs but I'm still getting an error when I want to run manage.py migrate or other request and command on the server: OSError: /app/.heroku/vendor/lib: cannot open shared object file: No such file or directory I did check with bash if it was true and yes there no lib directory in my vendor. I don't know a lot about buildpacks and config on heroku so I don't know where to start to fix this error. Here is my buildspack: https://github.com/cyberdelia/heroku-geo-buildpack.git heroku/python And in my .buildpacks I tried to put: https://github.com/cyberdelia/heroku-geo-buildpack.git#e1b845b https://github.com/heroku/heroku-buildpack-python.git I also tried different forks that were not able to build at all... I did put the paths in my settings: GEOS_LIBRARY_PATH = os.environ.get('GEOS_LIBRARY_PATH') GDAL_LIBRARY_PATH = os.environ.get('GDAL_LIBRARY_PATH') I'm a bit lost so help would be greatly appreciated -
Django: filter queryset based on open and closed hours and current time
In my model I have 2 TimeFields: one for opening hours of the places and another for their closing hours. Now I need to know if place open at the moment or closed. Is there a suitable approach for queryset filtering? -
Multiple querystring parameters
I've created this simple search function: def search(request): if "q" in request.GET: querystring = request.GET.get("q") print(querystring) if len(querystring) == 0: return redirect("/search/") posts = Blog.objects.filter(title__icontains=querystring | tagline__icontains=querystring | contents__icontains=querystring) context= {"posts": posts} return render(request, "kernel/search.html", context) else: return render(request, "kernel/search.html") When I use only one condition, for example: posts = Blog.objects.filter(title__icontains=querystring) it's shown me the correct results. But when I use multiple parameters I have SyntaxError: invalid syntax. How I can resolve? -
How do i style my django admin templates with Materialize Css?
What would be the best way to implement materialize css in my django admin? P.S:I'm new to django, not familiar with overriding/extending admin templates. -
Django annotate join on relations without usage of .values()
I have a calendar with entries and I want to display a more details on each day if the (currently logged in) user has already voted. The following sql query does what I need, but I don't understand how to translate this to the Django ORM select * from entries_entry join ratings_rating as rank on entries_entry.id = rank.entry_id where rank.user_id = ?; Here is the model: class Entry(models.Model): name = models.CharField(max_length=100) publish_at = models.DateTimeField(blank=True) class Rating(models.Model): entry = models.ForeignKey(Entry, on_delete=models.DO_NOTHING, related_name: 'rating') user = models.ForeignKey(User, on_delete=models.DO_NOTHING) value = models.IntegerField(default=1) I have found a solution with FilteredRelation but it seems that has_user_vote is not available in the template. Entry.objects \ .filter(publish_at__lte=timezone.now()) \ .annotate(has_user_vote=FilteredRelation('rating', condition=Q(rating__user=request.user))) If I add .values('id', 'name', 'has_user_vote') it works but then I can't make use of model methods (e.g. for sorl-thumbnail) because .values() transforms the QuerySet to a dict. -
django picture to original size
i am very new to django so i'm looking for a simple answer.i got this slideshow from a website,by the way this code is inside an html file. <div id="carouselExampleControls" class="carousel slide" data-ride="carousel" data-interval="200"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{%static 'images/2.jpg' %}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{%static 'images/3.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{%static 'images/4.jpg' %}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> my problem is that i want to display the images in their original size,this slideshow makes them all one large size. any help is much appreciated. -
DOM manipulation with Django
I am currently working on a web application with Django, which manages well the back of the application. However, the manipulation of the template is complicated because Django only offers the template engine. So I use jQuery which seems to be the most suitable for the dynamic aspect of the page. The problem is that I quickly realize that my templates are not structured, not readable. Having already worked with Angular, which dynamically manages the page (for example with a " ...", if the array is modified, the HTML is updated automatically), I think that I should perhaps all restart with it. Do you have any solutions for me? -
Django: dynamically access queryset data from different models
I'm interested in learning how to display all attributes of a list of querysets that come from different models. Here's an example: models.py class MyModelA(models.Model): attr1 = something attr2 = something class MyModelB(models.Model): attr3 = something attr4 = something class MyModelC(models.Model): attr5 = something attr6 = something views.py Let's say we have three model instances that are stored in a list: all_selected_queries = [mymodela, mymodelb, mymodelc] For each queryset in the list, I want to display all model field titles and data in a template. My approach: # Loop through the list and get the verbose name title of each field ("titel") for z in all_selected_queries: queryset_fields = z._meta.get_fields() for f in queryset_fields: titel = f.verbose_name.title() return titel What challenges me is how to get the fields' values without having to include the actual attribute name (because they are different for each queryset). So instead of explictly calling f.attr1, f.attr2, f.attr3, f.attr4, f.attr5 for each field, I'd like to encounter a solution that works across model boundaries. Thank you very much for your help! -
Creating GUI standalone application for my django website
I created a django website hosted on server which is simply a chat app with database to store user info. I created a gui desktop application for the same chat app. Can anyone please tell me how to send data between gui's over the network and store user data in database I created for the website. I just want to know how to connect to the database hosted on server from my gui application. Correct me if I am wrong. Thank you. -
Sending data to Django backend from RaspberryPi Sensor (frequency, bulk-update, robustness)
I’m currently working on a Raspberry Pi/Django project slightly more complex that i’m used to. (i either do local raspberry pi projects, or simple Django websites; never the two combined!) The idea is two have two Raspberry Pi’s collecting information running a local Python script, that would each take input from one HDMI feed (i’ve got all that part figured out - I THINK) using image processing. Now i want these two Raspberry Pi’s (that don’t talk to each other) to connect to a backend server that would combine, store (and process) the information gathered by my two Pis I’m expecting each Pi to be working on one frame per second, comparing it to the frame a second earlier (only a few different things he is looking out for) isolate any new event, and send it to the server. I’m therefore expecting no more than a dozen binary timestamped data points per second. Now what is the smart way to do it here ? Do i make contact to the backend every second? Every 10 seconds? How do i make these bulk HttpRequests ? Through a POST request? Through a simple text file that i send for the Django backend … -
Combine urls with same prefix but different namespace
I have the following two urls. They have the same "prefix" but a different namespace. Is there a way to combine these urls without loosing the namespace? pattern_1 = path('', include(([ path('<slug:product>/<slug:category>/', include(urlpatterns_1)), ], 'pattern_1'), namespace='pattern_1')), pattern_2 = path('', include(([ path('<slug:product>/<slug:category>/', include(urlpatterns_2)), ], 'pattern_2'), namespace='pattern_2')), -
Using Annotation for more than one value in django
I'm Trying to perform a query that uses annotation. But the problem is I need to annotate for 2 values without having the item showed 2 times in my template .. here are the files for a better understanding. Those are the models I use: class Daily(models.Model): date = models.DateTimeField(auto_now=True) text = models.CharField(max_length=80) # maden = models.IntegerField(default=0) # maden_from_type = models.ForeignKey(Type, on_delete=CASCADE, blank=True, null=True) maden_from_cat = models.ForeignKey(Category, on_delete=CASCADE, blank=True, null=True) da2en = models.IntegerField(default=0) da2en_from_type = models.ForeignKey(Type, on_delete=CASCADE, related_name='da2en_from_type', blank=True, null=True) da2en_from_cat = models.ForeignKey(Category, on_delete=CASCADE, related_name='da2en_from_cat', blank=True, null=True) farm = models.ForeignKey(Farm, on_delete=CASCADE) is_invoice = models.BooleanField(default=False) class Type(models.Model): type_name = models.CharField(max_length=80) def __str__(self): return self.type_name class Category(models.Model): category_name = models.CharField(max_length=80) type = models.ForeignKey(Type, on_delete=CASCADE) def __str__(self): return self.category_name And that is how I tried to execute the annotate in the views: def mezan(request): all_daily = Daily.objects.values('da2en_from_cat__category_name', 'maden_from_cat__category_name').annotate( all_maden=Sum('maden',distinct=True)).annotate( all_da2en=Sum('da2en',distinct=True)) context = { 'all_daily': all_daily, } return render(request, 'mezan.html', context) Finally, when I try to view it in my HTML templates, it duplicates the item if it has value in both annotated fields. {% for item in all_daily %} <tr> <td>{{item.da2en_from_cat__category_name}}</td> <td>{{item.all_da2en}}</td> <td">{{item.all_maden}}</td> </tr> {% endfor %} I need to show it once with the 2 values being displayed. But it is being … -
Get data from Django model and display in a html table using AJAX
I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail. Currently, the furthest I've gotten is a response to the network console: {"products": "[{\"model\": \"products.product\", \"pk\": 2, \"fields\": {\"name\": \"Bag\", \"description\": \"Carries items conspicuously \", \"price\": \"10.99\"}}, {\"model\": \"products.product\", \"pk\": 3, \"fields\": {\"name\": \"iPhone 8 Plus\", \"description\": \"a mobile device from Apple\", \"price\": \"850.00\"}}, {\"model\": \"products.product\", \"pk\": 8, \"fields\": {\"name\": \"Shoes\", \"description\": \"For your feet\", \"price\": \"49.50\"}}, {\"model\": \"products.product\", \"pk\": 9, \"fields\": {\"name\": \"Gloves\", \"description\": \"For your hands\", \"price\": \"2.99\"}}, {\"model\": \"products.product\", \"pk\": 10, \"fields\": {\"name\": \"Blanket\", \"description\": \"Keep warm\", \"price\": \"13.79\"}}, {\"model\": \"products.product\", \"pk\": 11, \"fields\": {\"name\": \"Gown\", \"description\": \"Sleep time\", \"price\": \"25.99\"}}]"} but I want this dictionary to display on my html table via ajax My django model looks like this: class Product(models.Model): def __str__(self): return self.name name = models.CharField(max_length = 200) description = models.TextField() price = models.DecimalField(decimal_places=2,max_digits=100000) my django view: def product_list(request): productData = serializers.serialize("json", Product.objects.all()) return JsonResponse({"products": productData}) my html page body: <body style='text-align:center'> <table class="table table-striped" id="product-table"> <thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead> <tr> <form id="add-product">{% csrf_token %} <td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td> <td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td> <td><a><input type="text" class="form-control … -
Python Django Mysql Expected in: flat namespace
I'm working on a project by using Python(2.7) and Django(1.10) in which I need to use mysql as database, I have installed XAMPP on Mac OSX and created a database. Here's my requirements.txt: asn1crypto==0.24.0 certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 cryptography==2.3 Django==1.10.4 enum34==1.1.6 idna==2.6 ipaddress==1.0.22 MySQL-python==1.2.5 mysqlclient==1.3.6 ndg-httpsclient==0.5.1 passlib==1.7.1 Pillow==5.1.0 pusher==2.0.1 pyasn1==0.4.4 pycparser==2.18 pyOpenSSL==18.0.0 requests==2.18.4 securetrading==1.0.14 six==1.11.0 stripe==1.82.1 urllib3==1.22 When I run my Django application by using this command as: python manage.py runserver It through an error like below: Unhandled exception in thread started by Traceback (most recent call last): File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in class AbstractBaseUser(models.Model): File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/db/models/base.py", line 119, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/abdul/multiEnv/lib/python2.7/site-packages/django/db/init.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) … -
Django POST request not working correctly
I have a Django Project I am currently working on where I want to be able to add a product to a database. I have a few fields where the user enters the details of the product and this is then sent to the create function and should save it to the Database. Unfortunately this isnt happening. This is my first use of Django so I'm not sure whats going wrong here. Here is the code I have so far: My Index.html page: <!DOCTYPE html> <html> <body> <h2>Create product here</h2> <div> <form id="new_user_form" method="post"> {% csrf_token %} <div> <label for="name" > Name:<br></label> <input type="text" id="name"/> </div> <br/> <div> <label for="description"> description:<br></label> <input type="text" id="description"/> </div> <div> <label for="price" > price:<br></label> <input type="text" id="price"/> </div> <div> <input type="submit" value="submit"/> </div> </form> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type = "text/text/javascript"> $(document).on('submit', '#new_user_form', function(e)){ e.preventDefault() $.ajax({ type: 'POST', url:'/user/create', data:{ name:$('#name').val(), description:$('#description').val(), price:$('#price').val(), } success.function(){ console.log('created') } }) } </script> </html> Here is my urls.py code: from django.contrib import admin from django.urls import path from django.conf.urls import include, url from testapp import views admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), path('user/create', views.create_product, name='create_user') ] My views.py code: from django.shortcuts import render from testapp.models … -
Foreignkey filtering spanning across multiple models
I have following four models and a form defined in forms.py. There is a model (CodeVillage) that lists some villages. Model CodePlaces lists a number of places around each village. Model Households contains some details of households living in villages. Model occupations has records for various members of households and their occupations. The occupations_form is used as an inline in admin form for households. I would like the work_place foreignkey in the form filtered so that it shows only places around the village in which a particular household lives. I am unable to figure out how to correctly get the queryset that will pick village from related record in household model, and then pick places from the related record in codeplaces model. Would really appreciate any help in fixing this filter. models.py class CodeVillage(models.Model): village_name = models.CharField(max_length=150, null=True, blank=True) def __unicode__(self): return self.village_name def __str__(self): return self.village_name class CodePlaces(models.Model): village = models.ForeignKey(CodeVillage, blank=True, on_delete=models.SET_NULL, null=True) place = models.CharField(max_length=150) district = models.CharField(max_length=150, null=True, blank=True) state = models.CharField(max_length=150, null=True, blank=True) class Meta: unique_together = (("location","place"),) def __unicode__(self): return '%s (%s)' % (self.location, self.place) def __str__(self): return '%s (%s)' % (self.location, self.place) class Household(models.Model): village = models.ForeignKey(CodeVillage, blank=True, on_delete=models.SET_NULL, null=True) household_number = models.IntegerField(blank=True, … -
ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/var/log/mysite/mysite.log'
The production server is running right now and I just run the python manage.py shell in the VPS terminal but it says : Traceback (most recent call last): File "/usr/lib/python3.5/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/lib/python3.5/logging/handlers.py", line 150, in __init__ BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) File "/usr/lib/python3.5/logging/handlers.py", line 57, in __init__ logging.FileHandler.__init__(self, filename, mode, encoding, delay) File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) PermissionError: [Errno 13] Permission denied: '/var/log/mysite/mysite.log' what can I do? -
Problems with relate_name with Django
I have these models: class Bloque(models.Model): titulo = models.CharField(max_length=200) letra = models.CharField(max_length=1) descripcion = models.CharField(max_length=200) tema = models.ForeignKey(Tema, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=1) updated_at = models.DateTimeField(auto_now=True) class Pildora(models.Model): titulo = models.CharField(max_length=200) descripcion = RichTextField(max_length=2000, config_name='default') slug = models.SlugField(max_length=20) url = models.URLField(max_length=200) tipo = models.ForeignKey(TipoPildora, on_delete=models.CASCADE) identificador = models.IntegerField() pildora_anterior = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) bloque = models.ForeignKey(Bloque, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_related') activo = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) But when i use: bloque = Bloque.objects.filter(tema__asignatura__slug=kwargs["asignatura"], tema__slug=kwargs["tema"], slug=kwargs["bloque"]) print(bloque.formacion_pildora_related) Django says: AttributeError: 'QuerySet' object has no attribute 'formacion_pildora_related' I read the django doc, but I can't find why is this happening :S What could i do? PS: In the case in question %(app_label)s_%(class)s_related refers to 'formacion_pildora_bloque'. I have put fixed names like 'pildoras' or even left it unreported, so that by default it is used as 'set_pillora', but none of this works. Thank you so much all, really. I'm stuck and a little frustrated. -
global name 'doStuff' is not defined
I just started learning django and my project shoppingcart has two users customer and owner.My problem is how to login as a customer and i have tried something like this but an error has occured views.py def customer_login(request): if request.method == 'GET': return render(request,"shoppingcart/customer_login.html") if request.method == 'POST': username=request.POST.get('username','') password=request.POST.get('password','') user = auth.authenticate(username=username, password=password) if hasattr(user, 'customer'): doStuff(user.customer) if user == customer: print "****" login(request,user) return redirect("/shoppingcart/customer_home") message="incorrect username or password" context={'message':message} return render(request,"shoppingcart/customer_login.html",context=context)