Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to delete a object directly from a button in a table
(sorry for my bad english) I need to delete an object, but directly from a list of the objects that y have in my template. I have a work orders, that have spare parts but i don't know how to create the deleteview for the spare parts using only a buton in the detailview of the work order. The idea is that the user make click in the Delete button. This is the model of the Spare Parts class OrderSparePart(models.Model): # Relations workorder = models.ForeignKey( WorkOrder, verbose_name=_('order'), ) # Attributes - Mandatory spare_part = models.CharField( max_length=80, verbose_name=_('spare part'), ) # Attributes - Optional price = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True, verbose_name=_('price'), ) # Object Manager # Custom Properties # Methods def get_absolute_url(self): return reverse('work_orders:detail', kwargs={'order_id': self.workorder.id}) # Meta and String class Meta: verbose_name = _("order spare part") verbose_name_plural = _("order spare parts") This is where is showed in the template {% if spare_parts %} <table class="table"> <thead> <tr> <th>{% trans "Spare Part" %}</th> <th>{% trans "Price" %}</th> <th>{% trans "Delete" %}</th> </tr> </thead> <tbody> {% for part in spare_parts %} <tr> <td><i class="fa fa-gear"></i> {{ part.spare_part }}</td> {% if part.price %} <td>$ {{ part.price }}</td> {% else %} <td></td> {% … -
Returning JSON from error pages with status <> 200 in Django
I have a website that is both for humans and API use. When called by the API (in jSON) I wish to return all errors as JSON. I put a middleware that use 'process_exception', but it not catch things as 404 (where django return a HTML). This is my middleware: class ExceptionMiddleware(MiddlewareMixin): def process_exception(self, request, exception): """ Allow unhandled excpetions to be returned encoded for the API """ if is_api_request(request): return JsonResponse(json_error(request, exception), status=500) else: return None # let django do the usual stuff I try with process_response, but then how get the error message? -
Specify max-width of a ModelChoiceField in Django Template
I'm just having a problem trying to specify the max-width of a ModelChoiceField in a Django Template. There is a long String and my Select list exceed the size of the col. I have to add an icon next to the Select list but I can't because it's hidden by the list... Here is my form : class ArtefactsUpdateForm(forms.ModelForm): origin = forms.ModelChoiceField(Origin.objects, widget=SelectWithPop, help_text='The place, city and country where the artefact comes from or the object to which the section considered belongs to', required=False) recovering_date = forms.ModelChoiceField(RecoveringDate.objects, widget=SelectWithPop, help_text='The date of excavation for archaeological objects, of production and use for other artefacts', required=False) chronology_period = forms.ModelChoiceField(ChronologyPeriod.objects, widget=SelectWithPop, help_text='The dating of the artefact', required=False) class Meta: model = Artefact exclude = ['object',] And here is the part of my template : <div class="row"> <div class="c3"><em>Origin and date of recovering</em></div> <div class="c8"> {{ form.origin }} <p><i>{{ form.origin.help_text }}</i></p> </div> <div class="c1"> <div class="pull-right"> {% for key, values in tokenComments.items %} {% if 'descriptionArtefact' == key %} {{ values|length }} {% endif %} {% endfor %} <a href="#commentDescription" data-toggle="collapse" aria-expanded="false" aria-controls="commentDescription"> <i class="fa fa-comment"></i> </a> </div> </div> </div> </div> The element {{ form.origin }} exceed the size of the c8 col, because of … -
Django Migrations removing field
So I have a model in my Django project (for arguments sake called 'app'), for example; class ModelA(models.Model): fieldA = models.IntegerField(default=0) and I can run python manage.py makemigrations app; which gives me Migrations for 'app': app/migrations/0001_initial.py - Create model ModelA If I then add a new field to ModelA so it looks like; class ModelA(models.Model): fieldA = models.IntegerField(default=0), fieldB = models.IntegerField(default=1) and then run makemigrations again, I get; Migrations for 'app': app/migrations/0002_auto_20170529_1737.py - Remove field fieldA from modela - Add field fieldB to modela The auto-generated file backs this up; operations = [ migrations.RemoveField( model_name='modela', name='fieldA', ), migrations.AddField( model_name='modela', name='fieldB', field=models.IntegerField(default=1), ), ] Why does it remove fieldA? My understanding was that it should only script changes to the models, i.e. That fieldB has been added. -
How to upload image by request : Python Django Rest framework
I can upload the field time and employee but I can't upload an image to the attendance_pic Model class Attendance(models.Model): time = models.DateTimeField(default=datetime.now, blank=True) employee = models.ForeignKey(Employee, related_name='employees') attendance_pic = models.ImageField(upload_to='attendance_pics',null = True) Serializers class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = '__all__' Views class AttendanceList(APIView): def get(self,request): model = models.Attendance attendances = model.objects.all() serializer = AttendanceSerializer(attendances, many = True) return Response(serializer.data) def post(self,request): now = timezone.now() serializer = AttendanceSerializer(data=request.data) serializer.is_valid(raise_exception=True) if serializer.is_valid(): serializer.save(time=now) # print (serializer.validated_data) # emp = serializer.validated_data.get("employee") # obj = models.Attendance.objects.create(time=now, employee=emp) return Response("Success", status=status.HTTP_201_CREATED) # return Response(AttendanceSerializer(obj).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Request f = open("pic.jpg","rb") r = requests.post(self.url,data={"employee":ID,"attendace_pic":f}) If I encode f with base64.encodebase64, serializer will allow request.data but I can not decode it and if i just pass it without encoding serializer won't allow. -
IntegrityError: book_app_author.book_id may not be NULL
So, this question has been asked multiple times, but I'm having a hard time applying those solutions to my app. Models: class User(models.Model): name = models.CharField(max_length=45) alias = models.CharField(max_length=45) email = models.EmailField() password = models.CharField(max_length=45) objects = UserManager() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(Author) user = models.ManyToManyField(User, related_name='books') def __str__(self): return self.title class Review(models.Model): content = models.TextField() rating = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ManyToManyField(User, related_name='reviews') book = models.ManyToManyField(Book, related_name='reviews' Views, the error pops up at the first except when trying to create a new author. def add_book(request): if request.method == 'POST': user = User.objects.get(pk=request.session['user_id']) data = { 'title':request.POST['title'], 'content':request.POST['review'], 'rating':request.POST['rating'], } #Create new author or add author author_name = request.POST['new_author'] print 'About to see if a new author was provided' if len(author_name) > 0: try: print ' Trying to get existin author ' author = Author.objects.get(name=author_name) except: print 'Trying to create a new author' Author.objects.create(name=author_name) else: print 'About to set author to existing author ' author_name = request.POST['author'] author = Author.objects.get(name=author_name) print … -
Django - Get Foreign key value directly with custom db_column
I'm trying to do what's described here: https://docs.djangoproject.com/en/dev/topics/db/optimization/#use-foreign-key-values-directly I have a model like this: class Pizza(models.Model): last_name = models.CharField(max_length=80, null=True, default=None) baker = models.OneToOneField(User, to_field='username', parent_link=True, null=True, db_column="django_username", default=None, db_constraint=False) I have a pizza instance, I want the actual username stored in the Pizza table without hitting the user table. -
fabric deploy "mkdir -p" gives socket error "no such file or directory", but command works in ssh
I'm using fabric3 to deploy a django project to an ubuntu (16.04) server. The code includes making directories, if required, with mkdir -p. A code snippet: from fabric.api import env, local, run (...) def _create_directory_structure_if_necessary(site_folder): for subfolder in ('database', 'static', 'virtualenv', 'source'): run(f'mkdir -p {site_folder}/{subfolder}') When I run fab deploy:host=ubuntu@my.site.com, I get the following error: [ubuntu@my.site.com] Executing task 'deploy' [ubuntu@my.site.com] run: mkdir -p /home/ubuntu/sites/my.site.com/database Fatal error: Low level socket error connecting to host my.site.com on port 22: No such file or directory (tried 1 time) Underlying exception: No such file or directory Aborting. The directory that was generated is correct, and there is already this file structure, with a working web site, on the server. If I ssh into the server, mkdir -p /home/ubuntu/sites/my.site.com/database works with no error. Why does the command work in a ssh window, but not in a fabric script? Details: Using an Amazon Web Services EC2 server, with default ubuntu user. App uses django, nginx, gunicorn, Python3.6. I'm following the book Test-Driven Development with Python by Harry Percival. Deploying from Mac OS X. -
auto define names from multi-upload images in django
hello I am Django user. how to auto define names from upload images using path? in the python that work nice : filepath = 'C:/Users/username/Desktop/imagename.tif' # set the filepath layer_name = filepath[:-4].split('/')[-1] # get the layer name in the layer_name I take the name but how to create a function to do that automate in Django models.py ? because I use multi upload images here my model: class MyModel(models.Model): name = models.CharField() user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='upload') -
Improve end-point Django Rest Framework
I created a new end-point for an API (Django Rest Framework) that generates a PDF from a HTML template. I follow the example form the plugin django-easy-pdf Is working but I would like to improve and to know what could be done in a better way. views.py class DemoPDFView(PDFTemplateView): template_name = 'reports/asset.html' pdf_filename = 'asset.pdf' def get_context_data(self, **kwargs): Asset = 5 asset = Asset.objects.get(id=Asset) project = asset.project.name id = asset.id name = asset.title return super(DemoPDFView, self).get_context_data( pagesize='A4', title='Asset', project=project, name=name, id=id, **kwargs ) -
Django development cannot find third party script in node_modules
I'm working in a development environment with debug = True on Windows 10. I have installed node and npm and run npm microm from the main folder of my project. It created a node_modules subfolder with a microm folder inside, among others. so the microm.js script is located in: f:\roomtemp\node_modules\microm\microm.js The relevant portion of my Settings file is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'node_modules') My template contains the following: {% load staticfiles %} <script src='{% static "/microm/microm.js" %}'></script> When I attempt to load the page, the Chrome console shows a 404 and I see this in the server console: "GET /static/microm/microm.js HTTP/1.1" 404 1661 I have read many SO questions that seem to contain the solution but none have worked so far. I've also searched high and wide on the internet. No luck so far. Any help would be much appreciated. Mike -
django tag with dynamic variable
i am displaying a multibarchart with django-nvd3. i get my data almost like in the example. http://django-nvd3.readthedocs.io/en/latest/classes-doc/multi-bar-chart.html view.py ... return render_to_response('multibarchart.html', {'data': data, 'form': form}) my data is a dictionary with all the infomation for nvd3. the data comes from a database. the dictionary has data for several years which i access with an select form. data = {2014: { 'charttype': charttype, 'chartdata': chartdata}, 2015: { 'charttype': charttype, 'chartdata': chartdata} } in the html i have a variable with the post from the selected year and i want to change the year nvd3 tag (here 2014). {% include_container data.dict.**2014**.chart... 400 600 %} i tried several things like ... {% with year as selected_year }} {% include_container data.dict.{{ selected_year }}.chart... 400 600 %} or {% include_container data.dict.selected_year.chart... 400 600 %} but i cant figure out how the year can be dynamic. thanks -
Django Wagtail Middleware kicks error: status_code not defined in response
I'm in the process of upgrading a project to Django 1.11. I've rewritten a custom piece of site middleware that seems to be working; however, I'm not sure it isn't causing a problem down stream. The error I'm getting, however, is from Wagtail: 'NoneType' object has no attribute 'status_code' Here is the full trace: Traceback (most recent call last): File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/utils/deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailredirects/middleware.py", line 30, in process_response if response.status_code != 404: AttributeError: 'NoneType' object has no attribute 'status_code' Here is the middleware code from Wagtail causing the error; I note it is using the deprecation Mixin: # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(MiddlewareMixin): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: ... return response # If a middleware before `SiteMiddleware` returned a response the # `site` attribute was never set, ref #2120 if not hasattr(request, 'site'): return response Has anyone run into this before? -
No module named 'django_auth_ldap'
I'm trying to configure a website with django and LDAP authentification. Upon my login page, I just type in any username and password, and expect to get to a different html page (without connecting to a database, for now. My method in my view.py file: def login_view(request): if request.POST: print ('*'*50) print (request.POST) print ('*'*50) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print ('*'*50) print (user) print ('*'*50) if user is not None: if user.is_active: login(request, user) return redirect('index') else: messages.error(request, "User is not active in Database") else: messages.error(request, "Please check your username and password!") return render(request, 'login.html') I'm new to django so not even too sure whether I should be seeing any page of if this error message is correct. I'm using Python3.5 and I installed successfully pyasn1-0.2.3. Then going into my console I can successfully import ldap3. However I can't get any further than this. -
How is Administration stored in django?
When I do `from django.apps import apps apps.get_app_config('admin').verbose_name' I get the result as Administration How is this result obtained? I cannot find anywhere written as administration, when instead of admin I put an installed app's name it shows the same name with capitalization. How is admin configured in django such that this results? -
Accessing app-specific server-side generated files in django template
I have a django app (my_app) that based on the user query: creates a file from the db runs a program on the file from step-1 and gets an output file generates a json file from the step-2 output file renders a D3 visualization from a django template using the data from the json file from step-3 I need the program to run on the server side and the json file to be generated server-side as well. Because the json files are query-specific, I thought it's not a good idea to keep these files in the /static/ folder and thought of keeping the files (even if temporarily) in e.g. /myapp/output_files/ folder. The problem is that there is no url pattern corresponding to /myapp/output_files/my_file.json and I get a "Page not found (404)" error if I try to open the generated file and it obviously doesn't load in the javascript code in the template. Is there a better way to design the system? If the design is ok, how can I access a json file in the app's folder from the django template? Do I need something in the urls.py? P.S. Everything works fine if I change the json location to /static/ … -
What's the meaning of get_all_lexers in pygment package?
I have started learning Django REST framework a few days ago. I have written models.py file as follows. from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) I know that pygments package is a generic syntax highlighter suitable for use in code hosting, forums, wikis or other applications that need to prettify source code. But I'm not sure what's the meaning of get_all_lexers, get_all_styles in pygments package. I don't know what the LEXERS, LANGUAGE_CHOICES, STYLE_CHOICES means exactly and why we use LEXERS, LANGUAGE_CHOICES, STYLE_CHOICES. What's the value of LEXERS, LANGUAGE_CHOICES, STYLE_CHOICES? -
Adding new python libraries to Edx Studio
I'm working with OpenEdx and i want add new libraries for make new funtionalities. I have the normal DevStack Edx environment (work in Docker). I want add google-api-python-client for my project, so i added this package to: After rebuild the image and run the container i review this packages in respective containers: Where are my libraries? It only happen in Studio, in LMS all is well. So: - Which is the correct external python packages installation's way? Thank you! -
How to scrap multiple html page in parallel with beautifulsoup in python?
I'm making a webscraping app in Python with Django web framework. I need to scrap multiple queries using beautifulsoup library. Here is snapshot of code that I have written: for url in websites: r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("a", {"class":"dev-link"}) Actually here the scraping of webpage is going sequentially, I want to run it in parallel manner. I don't have much idea about threading in Python. can someone tell me, How can I do scrap in parallel manner? Any help would be appreciated. -
Deploying my Django app on CentOS, styles stopped loading
I have a Django 1.11 app that I want to deploy on a CentOS 7 server, which I access via a terminal from my Ubuntu 16.10 guest on Windows 10 host through Virtualbox 5.1.18. After reconstructing my working environment on CentOS and cloning the repository I decided to run a development server to check if all python packages have been successfully installed and loaded (I went for python manage.py runserver 0:0:0:8000 to be able to connect to the app from Ubuntu guest). My problem is the following - although the app works fine, for some reason the app on CentOS does not "see" the .css files, which results in styles not being loaded. I double-checked that the files are there, and in settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) So the relative paths have not changed and yet the styles are not loaded on CentOS while they work perfectly well on Ubuntu. Anyone knows how to fix the problem and what caused it? -
Include Content-disposition header for Django FileUpload
I defined an API endpoint which accepts a file (e.g. using Django REST Framework). In Django, the content disposition header can be used when inspecting the response. https://docs.djangoproject.com/en/1.11/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment Now, if we want to set the header when testing the endpoint, how do I include this header using REST-Framework's APITestCase? What I tried so far is, but it does not seem to accept the headers. class TestSaleViews(APITestCase): def test_sale_detail_view(self): f = create_named_temporary_file() files = {'archive': f} basename = os.path.basename(f.name) headers = { 'content-disposition': 'attachment; filename={}'.format(basename), } response = self.client.post(url, files, format='multipart', **headers) -
django query set error (istartswith)
I tried : objects_list = Feed.objects.filter( job__istartswith__in=['AW', "cons", "S1"]) it shows me following error: FieldError: Unsupported lookup 'istartwith' for CharField or join on the field not permitted. if i tried like below, its working: objects_list = Feed.objects.filter( job__istartswith='AW') what should I do for searching words startswith for the list of words in query? -
Django no such column ForeignKey
I'm doing a Django project (kind of social network) and want to have a page where I can see all my posts, which I did. I allways get the error: no such column: uploaded_by in models.py from django.db import models from django.contrib.auth.models import User class ContentItem(models.Model): upload_date = models.DateTimeField(auto_now=True) title = models.CharField(max_length=100, default='no title') description = models.CharField(max_length=400, default='no description') image = models.ImageField(upload_to='image_board/posts/', default='null') uploaded_by = models.ForeignKey(User, default='0') def __str__(self): return self.title in views.py def view_my_favorites(request): all_posts = ContentItem.objects.raw('SELECT * FROM image_board_ContentItem WHERE uploaded_by = request.user.username') template = loader.get_template('favorites.html') context = { 'all_posts': all_posts, } return HttpResponse(template.render(context, request)) I want to get the user name of the user who is loged in, how can i whrite this in the sql query? Thaks guys :) -
Filter a ManyToManyField in django admin page
The problem I have two many to many fields (disciplines, subjects) showing in Excerpt Model and I would like to show in admin page only the subjects inside disciplines that corresponde. How I partially solved For that I'm using the function formfield_for_manytomany inside admin, it works well for filtering the objects, but I couldn't figure out how to filter the subject objects based on the discipline choosed, What I Tried I tried use a function in model.py get_disciplines for return the corresponding id, for then filtering the subjects, but this approach doesn't seem to work inside my admin proxy model, because raise an Error global name 'get_disciplines' is not defined probably cuz I can access outside model.py. I tried also declare this method inside admin proxy, but also doesnt work. my code # model.py class Discipline(models.Model): id = models.CharField(max_length=15, primary_key=True) name = models.CharField(max_length=100) class Subject(models.Model): id = models.CharField(max_length=15, primary_key=True) name = models.CharField(max_length=100) disciplines = models.ManyToManyField(Discipline) # my idea def get_disciplines(self): e = self.discipline.first() return e.id class Excerpt(models.Model): discipline = models.ManyToManyField(Discipline) subjects = models.ManyToManyField(Subject) # admin.py class ExcerptTaggerAdmin(ImageCroppingMixin, admin.ModelAdmin): filter_horizontal = ('subjects','discipline') def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "subjects": kwargs["queryset"] = Subject.objects.filter(disciplines = get_discipline) return super(ExcerptTaggerAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) … -
how to send notifications to multiple users at a time in django?
I am creating a rental website, where users can pay online. I want to inform users to pay the bills monthly once. how can I send the notification to all at once in django?