Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Django-admin-action with conditions
I have my django model Customer which consists of these fields; 'Customer_ID', 'Name', 'Gender', 'Age', 'Nationality', 'Address', 'Account_Type', 'Salary', 'Balance', 'Employer_Stability', 'Customer_Loyalty', 'Residential_Status' and 'Service_Level' where Service_Level = Silver, Gold or Platinum I would like to add a django-admin action that assigns the Service_Level to a customer/ customers depending on the values of the bold features above (Age, Salary etc.). I am not sure how I am supposed to go about it. Help will be appreciated -
how to get number from mysql django query result?
How to get just the number from this django mysql query? cursor1 = connection.cursor() sql = "SELECT sum(nominal) from transaksi_kas_transaksi as t " \ "INNER join datapribadisiswa_datapribadisiswa as d on t.nis = d.SiswaNis WHERE " \ "(t.kode_pem='01') AND (t.tanggal>='%s' " \ "AND t.tanggal<='%s') and ( month(tanggal)=8) and d.SiswaKelas_id=6 GROUP BY t.nis" % ( tahunawal(), tahunakhir()) cursor1.execute(sql) data = cursor1.fetchall() and this is the result ((Decimal('410000'),), (Decimal('410000'),), (Decimal('410000'),), (Decimal('410000'),), (Decimal('615000'),), (Decimal('410000'),), ) how to get number from the result? -
Mysterious error when using django server with grequests
Currently, I am running a vagrant server on Ubuntu 14.04 and I test all my django modules by using the simple python manage.py runserver 0.0.0.0:8000 Since I am connecting to the django webserver using chrome through http://localhost:8000 and the server is running on a VM, I am port forwarding through the usage of the following setting in Vagrantfile config.vm.network "forwarded_port", guest: 8000, host: 8000 Everything runs normally (all modules/views/tests function as expected), however, ever since I started using grequests I get this weird error Exception happened during processing of request from ('10.0.2.2', 63520) Traceback (most recent call last): File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__ self.handle() File "/home/vagrant/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 159, in handle self.raw_requestline = self.rfile.readline(65537) File "/home/vagrant/anaconda3/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 385, in recv_into self._wait(self._read_event) File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 157, in _wait self.hub.wait(watcher) File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 651, in wait result = waiter.get() File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 899, in get return self.hub.switch() File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 630, in switch return RawGreenlet.switch(self) gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7f3b777e8af8 epoll pending=0 ref=0 fileno=34>) Note that I am not using grequests and that … -
Adding/Removing data via Django Tables 2
I want to display a table via Django that enables me to add and remove data from my model. I was thinking of having a little "x" on the right hand side that I click to remove a row and a bottom row of inputs with a "Add" button on the right to submit this data to the DB. I can't find an examples of this, but I have seen that you can include default data, pin rows, and add submit buttons. These could potentially be used to do what I want. Could you give me an example of adding an input field so I can submit data for a Model? -
SNS notifications to Browser
I developed a web application which serves a html page when user visits the link and displays some data according to keywords entered. Now data is being populated on the go, so I want to model something like when a new piece of data is stored(in elastic search) a SNS notification is generated which is shown to the person who is viewing the webpage. I got the SNS notification working, but I am stuck on the part that how do I display this notification on the front end? Can I do something like this that SNS pushes data to the a SQS queue and Javascript polls the queue and picks up the generated notification and displays it or there is a better way? PS:I dont know NodeJS -
django clean_field's skipped while clean() returns errors
I am having some issues with validating a form. The form contains controls that will end up working on three tables. A bit of background...it is a reservation system. A person can select a place to reserve, provide personal details, address. If under age of 10, a guardian detail must be provided as well. If the person is aged 18, an id number should be provided and a few more requirements. As such, I don't want to use ModelForm. Now the form is displaying ok but I am having problem validating it. Here is my forms.py basically: from datetime import date from dateutil import parser class NewCustomerForm(forms.Form): firstName=forms.CharField(max_length=25,required=True,widget=forms.TextInput()) birthdate=forms.DateField(required=True) idnumber=forms.CharField(required=False,max_length=25) #guardian first name, if necessary gfirstName=forms.CharField(max_length=25,required=False) def clean_firstName(self): data=self.cleaned_data['firstName'] #should be given. if len(str(data))<3 or len(str(data))>25: raise forms.ValidationError(_('First name must be between 3 and 25 characters long'),code='invalid') return data def clean(self): ''' Grouped cleaning ''' birthDateOK=False #assume it is incorrect format with the birthdate which decides the requirement of id number and guardian #1. Validate ID number. All above 18 should have a unique ID number cleaned_data=super().clean() birthdate= cleaned_data.get('birthdate') if birthdate: #convert birthdate to date. try: birthdate=parser.parse(birthdate) #continue confirming id and gurdian except: raise forms.ValidationError(_('Birth date is not in correct … -
Failed to retrieve list of Django objects with models.Manager
I have the following structure scenario in my models.py : from django.db import models class SensorManager(models.Manager): def create_sensor(self,numero,pinoFisico): sensor = self.create(numero = numero, pinoFisico = pinoFisico, ativo = False) return sensor class Sensor(models.Model): numero = models.IntegerField() pinoFisico = models.IntegerField() ativo = models.BooleanField() dataUltimoReconhecimento = models.DateTimeField() situacao = None moduloSensor = None #Manager objects = SensorManager() and, in views.py file, i have this: def formSensores(request): sensores = Sensor.objects.all() print sensores return render(request,"speedapp/monitoraSensores.html",{"sensores": sensores}) When I try to use objects in print sensores i get the following stack: [17/Apr/2017 00:38:09] "GET /speedapp/ HTTP/1.1" 200 3649 Internal Server Error: /speedapp/sensores/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Documents/speed_project/speed/speedapp/views.py", line 39, in formSensores print sensores File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 234, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 258, in __iter__ self._fetch_all() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 69, in __iter__ obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in from_db new = cls(*values) TypeError: __init__() takes exactly 1 argument (6 given) [17/Apr/2017 00:38:11] "GET /speedapp/sensores/ HTTP/1.1" 500 15557 As the stack, it seems to be … -
Django sort_by and distinct (solved)
I was having trouble doing this: MY_MODEL.objects.order_by('foo').distinct('bar') This appears to be a Django-Postgres SQL issue. My solution is below: -
How do you implement custom response?
I found that the DRF's return value could be various upon different occasions. So I want to make sure all my JSON return have "code" "message" or other values nested inside in order to keep consistency of my APIs. For example: Success {"code": 1, "status": "success", "message": "", "data": [{"id": 1, "name": "John Doe", "email": "johndoe@gmail.com"}]} Error {"code": -1, "status": "error", "message":"Something went wrong","data": [] } The return will always have "code" "status" "message" "data" inside whatever the result would become. After looked up in Google but couldn't find any work-around over DRF. So I suppose everybody is redefining the APIViews or Mixins (get put post etc. ) to control the response. But I am not very sure if the return should be that widely different without a certain pattern. Or is it cool that DRF's JSON response could be directly adopted as a production case? Hope to have some advice from you guys. Thanks. -
Is this a "correct" database design in Django?
I am building a website where the institution can sign up, create groups and invite members to the institution. While inviting members they will put on their email and the groups they may be preassigned to. By default, there is an 'Administrator' group which have all the rights: like create/delete groups and invite members. Here is what I have done so far on django models: class Institution(models.Model): institution_name = models.CharField(max_length=200, blank=True) def __str__(self): return self.institution_name class InstitutionGroup(models.Model): group_name = models.CharField(max_length=200) institution = models.ForeignKey(Institution) right_to_buy = models.BooleanField(default=False) def __str__(self): return self.group_name class InstitutionMember(models.Model): user = models.ForeignKey(User) group = models.ForeignKey(InstitutionGroup, blank=True, null=True) right_to_buy = models.BooleanField(default=False) institution = models.ForeignKey(Institution) Is this a nice design? Thanks -
Django Cannot Update User Profile Picture
I have created a custom UserProfile model, and want to allow the user to edit his or her profile's fields. The other fields are editable, but the ImageField is not. The code in my views.py is pretty messy. I'm hoping someone can teach me a better way of doing it because it's hacked together with partial understanding. models.py #custom user profile class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=200, default='') city = models.CharField(max_length=100, default='') profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): #if user object has been created, we want to create user profile if kwargs['created']: #returns the instance of our user object user_profile = UserProfile.objects.create(user=kwargs['instance']) #connecting to the post_save signal. Pass in a function that should run post_save.connect(create_profile, sender=User) When the user navigates to the place where they can edit their profile, the view function "edit_profile" is used. Here it is in views.py: def edit_profile(request): #try: # user_profile = UserProfile.objects.get(user=request.user) #except UserProfile.DoesNotExist: # return HttpResponse("invalid user profile!") user_profile = UserProfile.objects.get(user=request.user) profile_form = UserProfileForm(instance=user_profile) if request.method == 'POST': update_profile_form = UserProfileForm(data=request.POST, instance=user_profile) #so we know the user object form = EditProfileForm(request.POST, instance=request.user) if form.is_valid() and update_profile_form.is_valid(): user = form.save() update_profile_form.save() #return redirect(reverse('userapp:profile')) args = {'profile_form': update_profile_form} return … -
ManyToMany Search, Order By Total Connected.
Thank you for your time in reading this question and even more thanks for helping answer. My question. How would I take a list of ManyToMany Ids. [,] ( or objects if needed ) search for those ManyToMany items on the set model return all those that have connections and sort by the count of connections the items has. -- flow / idea -- m2m_objects = (objects) # or ids. q = Model.objects.filter(m2mfield__ids ????) # order by count of objects found. Thank you all so much. -
Running in memory store with Django
I am looking for a way to store IP/Port information with Django and I am wondering of the best approach to do this. The structure looks something like: service["Service-1"] = "192.168.0.1, 81" service["Service-2"] = "192.168.0.2, 82" service["Service-3"] = "192.168.0.3, 83" So far I have thought of the following approaches: Store a dictionary in memory Create a database and update it periodically with information Run a separate process and have it return a dictionary via RPC. I think the first approach is the simplest but I don't know where I would create and maintain the dictionary object because I don't see something like a main function in Django other than manage.py. If I had to maintain this dictionary object for the lifetime of the server, where would be the best place to create the object? The other two approaches I would like to avoid since they are more of a workaround if I cannot get the first approach to work. -
How To Query Postgres Index via Django
I would like to add text search to my web app. I have created a index for three fields in postgres. I can not figure out how you query an index from django views. The index is named 'search_index' and when I try to query search_index I get a field error. views def search(request): # search_index #products = Product.objects.defer('product_description', 'product_keywords', 'shipping_cost', 'promotional_text', 'condition', 'warranty', 'stock', 'sku') #product_count = products.count() query = request.GET.get("q") if query: # product = products.filter( # Q(product_name__icontains=query) | # Q(product_description__icontains=query) | # Q(product_keywords__icontains=query) # ) product = Product.objects.filter(search_index__search=query) # if product.order_by('sale_price'): # product = product.order_by('sale_price') # else: # product = product.order_by('-price') paginator = Paginator(product, 20) page = request.GET.get('page') try: product = paginator.page(page) except PageNotAnInteger: product = paginator.page(1) except EmptyPage: product = paginator.page(paginator.num_pages) index = product.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = {"product": product, "page_range": page_range, "query": query,} template = "search.html" else: template = "search.html" context = { "query": query, #"product_count": product_count, } return render(request, template, context) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=born Django Version: 1.10.6 Python Version: … -
Django Facebook Signs Up but doesn't login
I am using django-rest-framework-social-oauth2 which used to work perfectly. Somehow, my app started to signup through facebook but not login. settings.py LOGIN_REDIRECT_URL = 'after_login' And, 'my_app.social_auth_pipeline.save_profile', social_auth_pipleline.py def create_user(backend, user, request, response, *args, **kwargs): request['user_type'] = ['parent', 'child'] if backend.name == 'facebook': avatar = 'https://graph.facebook.com/%s/picture?type=large' % response['id'] if not Parent.objects.filter(user_id=user.id): Parent.objects.create(user_id=user.id, avatar=avatar) urls.py url(r'^$', auth_views.login, {'template_name': 'home.html'}, name='home'), url(r'^welcome/$', views.after_login, name='after_login'), url(r'^join/$', views.signup, name='signup'), url(r'^(?P<city_slug>[-\w]+)/$', views.city, name='city'), views.py def after_login(request): if request.user.is_authenticated() and request.user.profile.city is not None: return redirect('city', city_slug=request.user.profile.city.city_slug) elif request.user.is_authenticated() and request.user.profile.city is None: return redirect('signup') else: return redirect('signup') So, what happens is that user is redirect to sign up page and asks to be registered instead of city page or, sign up page where if user is authenticated they get "enter city" form if they didn't enter their city while in the backend i can see a user object is added as well as profile object! -
Django URL from HTML search form
In my template I am using an input with the type "search". When an action is performed it returns the page "/search_results.html". The issue I'm having is that it appends /?search=yoursearch to the end of the URL. My URL pattern is url(r'^search_results/(?P<search>\w+)/$, views.SearchView, name='search') So right now if I type localhost:8000/search_results/apple, it will return results that contain the word apple. But if I use the search bar to search apple it returns localhost:8000/search_results/?search=apple, which is not a valid URL. I tried using (?P<search>.*) instead, but it said too many redirects. Does anyone know how to use the value from a search result in Django? Or is there a way to arrange my URL so that I can parse the bit after the equals sign? Thanks -
Stripe Integration Error with Django
I was following a tutorial on django ecommerce and encountered a 404 error while trying to test out the Stripe application. Specifically, I was redirected to 'http://127.0.0.1:8000/your-charge-code' upon submitting a test payment. in views.py def checkout(request): publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': token = request.POST['stripeToken'] try: charge = stripe.Charge.create( amount=1000, currency="gbp", description="Example charge", source=token, ) except stripe.error.CardError as e: pass context ={'publishKey': publishKey} template = 'checkout.html' return render(request,template,context) in checkout.html: {% block strip %} <script type="text/javascript"> Stripe.setPublishableKey('{{ publishKey }}'); function stripeResponseHandler(status, response) { // Grab the form: var $form = $('#payment-form'); if (response.error) { // Problem! // Show the errors on the form $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); // Re-enable submission } else { // Token was created! // Get the token ID: var token = response.id; // Insert the token into the form so it gets submitted to the server: $form.append($('<input type="hidden" name="stripeToken" />').val(token)); // Submit the form: $form.get(0).submit(); } } </script> {% endblock %} {% block jquery %} $(function() { var $form = $('#payment-form'); $form.submit(function(event) { $form.find('.submit').prop('disabled',true); Stripe.card.createToken($form,stripeResponseHandler); return false; }); }); {% endblock %} and in base.html {% block script %} {% endblock %} <script> $(document).ready(function(){ {% block jquery %} {% endblock %} }); </script> What am I … -
Django admin - add user object to context
I have two init methods for counting some objects (part of admin.py): def index(self, *args, **kwargs): extra_context = get_inactive_sites_count() return admin.site.__class__.index(self, extra_context=extra_context, *args, **kwargs) admin.site.index = index.__get__(admin.site, admin.site.__class__) def get_inactive_sites_count(): inactive_sites_count = str(Site.objects.filter(is_active=False).count()) active_sites_count = str(Site.objects.all().count()) print(active_sites_count) extra_context = { 'inactive_sites_count': inactive_sites_count, 'active_sites_count': active_sites_count, } return extra_context I would like to add another counter to extra_context: user_sites_count: str(Site.objects.filter(user=request.user).count() 'user_sites_count': user_sites_count How can I use request.user here? -
Django All Auth Workflow - User Profile
I want to integrate django-allauth to my project. I have created two app for as profile for asking more information according the user type. PrinterProfile(one to one to User) CustomerProfile(one to one to User) Printer Model: class Printer(models.Model): name = models.CharField(_('Name'), max_length=50) address = models.CharField(_('Address'), max_length=200) email = models.EmailField(_('Email'), max_length=75) user = models.OneToOneField(User, related_name='printers_profile') phone = models.CharField(_('Telephone'), max_length=75, blank=True) bio = models.TextField() tag_line = models.CharField(max_length=255, null=True, blank=True) facebook = models.URLField(null=True, blank=True) twitter = models.URLField(null=True, blank=True) google_plus = models.URLField(null=True, blank=True) linkedin = models.URLField(null=True, blank=True) logo = models.ImageField(upload_to='printers_logos/', null=True, blank=True) slug = models.SlugField(max_length=150, unique=True) The View class Printer_Create(LoginRequiredMixin, CreateView): model = Printer form_class = Printercreation_form # form_class = PrinterNewForm template_name = "printers/printer_create.html" # success_url = reverse_lazy('') def get_form_kwargs(self): kwargs = super(Printer_Create, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): self.user = self.request.user form.instance.user = self.user return super(Printer_Create, self).form_valid(form) The Form class Printercreation_form(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(Printercreation_form, self).__init__(*args, **kwargs) self.fields['email'].initial = self.user.email class Meta: model = Printer fields = ( 'name', 'address', 'email', 'phone', 'bio', 'tag_line', 'facebook', 'twitter', 'google_plus', 'linkedin', ) exclude = ( 'user', 'logo', 'slug', ) My goal is after submit this form send confirmation email and create an usable password (since it will has … -
Django: How to save parent, child, grandchild forms on single template
I have three models case (parent), which has a many to one relationship with user, claim (child) which has a many to one relationship with case and basis (grandchild), which has a many to one relationship with claim. I cannot get the claim to save with the case id or the basis to save the claim id, but the case does save with the user. I modeled the below from answer Django: multiple models in one template using forms models.py class Case(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_due = models.DateField() class Claim(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) claim = models.TextField(max_length = 100, null =True, blank = True) class Basis(models.Model): claim = models.ForeignKey(Claim, on_delete=models.CASCADE) basis = models.IntegerField() forms.py class CaseForm(forms.ModelForm): class Meta: model = Case fields = ('date_due',) class ClaimForm(forms.ModelForm): class Meta: model = Claim fields = ('claim', ) class BasisForm(forms.ModelForm): class Meta: model = Basis fields = ('basis',) CaseFormset = inlineformset_factory(User,Case, fields=('date_due',), can_delete = False, extra = 0) ClaimFormset = inlineformset_factory(Case,Claim, fields=('claim',), can_delete = True, extra = 0) BasisFormset = inlineformset_factory(Claim,Basis, fields=('basis',), can_delete = True, extra = 0) views.py @login_required def add_case(request): context_dict = {} user = request.user if request.method == 'POST': case_form = CaseForm(request.POST) claim_form = ClaimForm(request.POST) basis_form = BasisForm(request.POST) if … -
Get object with biggiest related set in Django ORM
Is it possible to get object which has the highest number of related objects? I want to choose most used plan which is a plan with the maximal number of UserPlan objects. I can get the number but not the instance. number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users'] code: class UserPlan(Model): plan = ForeignKey('Plan'..) class Plan(Model): ... @staticmethod def favorite(self): number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users'] # ? I could find it using loop but it could be slow. -
CSS file not found
I am going crazy with linking stylesheet file to my 'base.html' template which I use in my whole project. here is path to file I want link: C:\forum_project\static\main\css\style.css Below is code snippet from 'base.html' from head section. <meta charset="UTF-8"> <title>Django Developers Forum</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css/' %}"> As you can see the last line is attempt to derive from this stylesheet. I am getting following information in console, when browser tries to send GET request for stylesheet. [16/Apr/2017 23:55:14] "GET /static/main/css/style.css/ HTTP/1.1" 404 1670 Any suggestions what I am doing wrong? -
Django SingleObjectMixin
I try to create simple SingleObjectMixin class, later i will use it with render_json_response() for providing AJAX data streaming. The main goal is basket for online store. So there is simple test class: class Test(SingleObjectMixin): model = GoodsDescription slug_url_kwarg = 'test_id' slug_field = 'artikul' # pk field in 'GoodsDescription' table def get(self, request, *args, **kwargs): self.object = self.get_object() return render(request, 'temp_code.html', {'msg':self.object.name}) So the mistake is: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/test%3D5/ Django Version: 1.10.5 Python Version: 2.7.12 Installed Applications: ['alexbase', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'easy_thumbnails'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) Exception Type: TypeError at /admin/test=5/ Exception Value: object() takes no parameters -
Django 1.11: Cannot import name "X"
I have a problem when I try to import my model "Book" and my model "Comment" from different apps. My Settings.py INSTALLED_APPS = [ ... 'books', 'comments', ... ] books/models.py from comments.models import Comment class Book(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(unique=True) autor = models.CharField(max_length=200) description = models.TextField() likes = models.PositiveIntegerField(default=0) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) files = models.FileField(upload_to=upload_location, validators=[validate_file_extension]) book_type = models.CharField(max_length=100, choices=Book_Type_Choices) tags = TaggableManager() comment = models.ForeignKey(Comment) and my comments/models.py from books.models import Book class Comment(models.Model): book = models.ForeignKey(Book, related_name='cooments') user = models.ForeignKey(User, unique=False) text = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) I was trying so mamy things but nothing works :( The error is: File "C:\Users\a_niu\Desktop\Proyectos\Django\tt\Tescha-books\books\models.py", line 12, in <module> from comments.models import Comment File "C:\Users\a_niu\Desktop\Proyectos\Django\tt\Tescha-books\comments\models.py", line 5, in <module> from books.models import Book ImportError: cannot import name Book -
download a file with django
O.K. This might perhaps be a simple question, but I somehow just can not find the solution. Django offers a lot about uploading file, but how do I do to download a file. Let's assume we have a button on html and uploads/something.txt as a file. I tried with django.views.static.serve, however what this did it would open a file on webpage. My question is simple: What is the best and most pythonic way for user of our website to download a file?