Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, select image from previous uploaded images
I have a Post model which has a ImageField. class Post(models.Model): headline = models.CharField(max_length=255) lead = models.TextField(blank=True, null=True) body = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="posts", blank=True, null=True, max_length=255) In my ModelForm, the file input for the image works perfectly, but I was wondering how to let the user choose between uploading a new image, or selecting one from all the images that have been previously uploaded to the site. Any pointers? -
Django - Cannot 'migrate'
I am currently trying to deploy my new changes to my raspberry-pi, but with I run python manage.py migrate I receive the error below: Applying CloudRoni.0007_auto_20180129_2007...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 303, in create_model self.execute(sql, params or None) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 63, in execute return self.cursor.execute(sql) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: unable to open database file When I try … -
Ubunti Server 16.04: Running Django on Apache
I am having troubles getting apache to run django. I am able to run "python3 manage.py runserver 192.168.1.230:80" and it will run everything fine. But once I try to have apache run it, I will get a "500 internal server error". I have watched multiple youtube videos and also read many articles. The main articles I have followed are: https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/ and https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 I am not sure what to do next. I have looked at my error.log and can't find anything to help my particular situation. Here is my /etc/apache2/apache.conf file: # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.4/ for detailed information about # the directives and /usr/share/doc/apache2/README.Debian about Debian specific # hints. # # # Summary of how the Apache 2 configuration works in Debian: # The Apache 2 web server configuration in Debian is quite different to # upstream's suggested way to configure the web server. This is because Debian's # default Apache2 installation attempts to make adding and removing modules, # virtual hosts, and extra configuration directives as flexible as possible, in # order to make automating the changes and administering the … -
Display foriegnkey fields in Django template for a CreateView
I am trying to display a checklist in the CreateView using the values in the ForeignKey fields for descriptions. models.py class Structure(models.Model): name = models.CharField(max_length = 30) description =models.CharField(max_length = 300, null=True, blank=True) def __str__(self): return self.name class SelectedFramework(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) structure = models.ForegignKey(Structure) selected = models.BooleanField(default = False) views.py class FrameworkCreateView(generic.CreateView): model = SelectedFramework fields =['structure', 'selected'] template_name = 'catalogue/structure.html' def form_valid(self, form): form.instance.user = self.request.user return super(FrameworkCreateView, self).form_valid(form) structure.html {% extends 'catalogue\base.html' %} {% block container %} <h2>{% block title %}Structures{% endblock title %}</h2> <form action="" method="post"> {% csrf_token %} {% for field in form %} <div class="col-sm-10">{{form.structure}} {{form.selected}}</div><br> {% endfor %} </div> </form> {% endblock %} The code above works but will display the ForeignKey 'structure' as a dropdown list with the values of __str__. Is there a way to display string for structure.name and structure.description with the checkbox from selected in the CreateView? -
Creating online python Editor
I want to create an online editor where users can come in, write python code and are able to run the code and view their results. I want something like kaggle's kernel editor for python as shown in image below I want to do the backend in python with some library like Flask or Django. My actual problem is how do I proceed with the implementation. My initial idea is to have some js editor that lets user write the code and when user hits "Run", I would send an ajax call to the web-server with the contents of the code editor. The web server would in turn run the code and return the response which would be displayed to another box showing output. My actual concern here is, how do I avoid execution of malicious code? Suppose user writes something that tries to download some data from directories he is not supposed to access, what would be the proper safeguard against it? -
Passenger Django on Centos / Plesk
Followed https://support.plesk.com/hc/en-us/articles/115002701209-How-to-configure-Django-application-in-Plesk- to get my Django 1.11 application up and running on a fresh Centos VPS with Plesk Onyx. Happy with progress as would normally use wsgi on Ubuntu as clearly the app is being seen/recognised but I'm getting an error. Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 325, in <module> app_module = load_app() File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 62, in load_app eturn imp.load_source('passenger_wsgi', startup_file) File "/var/www/vhosts/example.com/httpdocs/app/passenger_wsgi.py", line 8, in <module> if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) File "/var/www/vhosts/example.com/biems-app-venv/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError: [Errno 2] No such file or directory I have followed Passenger + Dreamhost + Django Error but my python seems to exist if I'm to use the one in the virtual-env and not the system wide version. I've updated the database configuration but have not yet sorted the statics/media files but cannot see this causing a problem? My passenger.wsgi looks like import sys, os app_name = 'biems' env_name = 'biems-app-venv' cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/' + app_name) INTERP = cwd + '/' + env_name + '/bin/python' if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) sys.path.insert(0, cwd + '/' + env_name + '/bin') sys.path.insert(0, cwd + '/' + env_name + '/lib/python2.7/site-packages/django') sys.path.insert(0, cwd + … -
Django profile View
Hi I am new to Django and tried existing answers but did not work for me. I would appreciate your help! I have two logins 1 with facebook and 1 with django. I have this profile view in my page. if you login with facebook you can access your profile page and change it. but if you login with a not social account (regular user object) you get redirected to home page not profile.If you go to django admin page all users are listed in user page. if you go to profile page on admin, there are only social auth users from facebook. What can I do to resolve the issue? Thanks in advance. here is the code: @login_required(login_url="/") def profile(request, username): if request.method == 'POST': profile = Profile.objects.get(user=request.user) profile.about = request.POST['about'] profile.slogan = request.POST['slogan'] profile.skill = request.POST['skill'] profile.save() else: try: profile = Profile.objects.get(user__username=username) return render(request,'profile.html',{'user':user}) except Profile.DoesNotExist: return redirect('/') -
How to force HTTPS in a Django project using Cloudinary?
I am using Cloudinary in my Django project to upload and store my images. Something like this: class MyModel(models.Model): logo = CloudinaryField('Logo', blank=True, null=True) In my serializers, if I call something like: mymodel = MyModel.objects.get(pk=1) return mymodel.logo.url What is being returned is a cloudinary url but only with http. How do I fix this? How do I get https? -
Django ugettext_lazy not working for interpolated strings in forms
I have form: class UserForm(forms.Form): fname = forms.CharField(max_length=30, label=_('First Name'), validators=[Alpha()]) lname = forms.CharField(max_length=30, label=_('Last Name {name}').format(name='XXXX'), validators=[Beta()]) i am rendering this form using form.as_p, when i change my language First Name gets translated but for some reason Last Name {name} which using format method for string interpolation is not getting translated, translation for this string is also present in the language catalog. My Django version is 1.8. -
Get objects of a certain quality from many to many field
Say I have the following model: class Project(Model): name = CharField() users = ManyToManyField(), through="Membership") @property def developers(self): ??? class Membership(Model): user = ForeignKey(AUTH_USER_MODEL) project = ForeignKey(Group) level = IntegerField() class Meta: unique_together = ("user", "project") Say there are two levels: developer and tester. Which code shall be written instead of ??? so that project.developers returns a queryset of all users related to the project as developers? -
Save object model with keywords in Django
I'm using drum template to build a reddit style website and I want to populate my database with some entries. My problem is that I'm not able to add a Link and the corresponding keywords. I was trying this (I add a few more attributes to the model): keywords_list = ['key1_test','key1_test'] u = User.objects.get(username = username) obj = Link( link = 'www.example.com', user = u, pub_date = datetime.datetime.now(), title = 'Title', description = 'blabla', fb_shares_ts = '', fb_reactions_ts = '', fb_comments_ts = '', fb_engagement_ts = '' ) for key in keywords_list: keyword, _ = Keyword.objects.get_or_create(title=key) obj.keywords.add(AssignedKeyword(keyword=keyword),bulk=False) obj.save() It gives me this error: django.db.utils.IntegrityError: NOT NULL constraint failed: generic_assignedkeyword.object_pk -
Django FilterSet set initial value
I am new to Django, so if this is a fairly obvious question, I apologise. We are using Django_Filterset in our project. I have been asked to set a default filter value for a foreign key column in the model class RegFilter(django_filters.FilterSet): class Meta: model = models.Reg fields = { 'id': ['exact'], 'nom_id': ['icontains'], 'nom_name': ['icontains'], 'product__name': ['icontains'] } The product name should default to a product already in the db when the initial screen is displayed - any idea how this can be achieved? Appreciate your help. -
Wagtail check user page permission
I have site made in django with Wagtail CMS. In that page menu is generated from templatetag i made. The problem is for now authenticated and anonymous users can see only public pages. I need to show in that menu also private pages, but only that pages which user has permission to view. I easily managing in wagtail admin how to set that permission, but how i can check if user has view permission for specific page in backend or template? if context['request'].user.is_authenticated(): private_categories = Page.objects.live().in_menu().not_public() for category in private_categories: if HERE I NEED TO CHECK IF USER HAS PERMISSION TO VIEW CATEGORY: categories.append(category) -
Django pre_save signal and ModelAdmin custom error message
I have a model whose pre_save() signal is connected to a remove service (json, REST, etc.) in the following way: before saving locally, query the remote service, asking for remote insertion remote service does its things, the main being checking that a relevant entry does not already exist. On success (HTTP 201), all is good, the local model uses the remote service response to populate the db. on failure, the service returns an HTTP 400 (the status code is debatable but that is for a different question on SO :-) ) The error response is in the following form: {'local_model_field': [u'This element already exists']} The local model pre_save signal then raises a ValidationError: raise ValidationError(json_response['local_model_field'][0]) This works nicely. Now, on the django admin, when I try to simulate the remote insertion of an already-existing object, I get a 500 page, which is fine but not ideal. Is there any way to have the pre_save() error bubble all the up to the ModelAdmin and be displayed as a standard error message, populated with the relevant content? I have tried the following but to no avail: def changeform_view(self, request, object_id=None, form_url='', extra_context=None): """ trying to display the right message when pre_save() fails … -
SyntaxError simply a ] while using Django
Hi everyone I get this weird error can someone please help. The error is: File "C:\Users\myshop\myshop\urls.py", line 26 ] ^ SyntaxError: invalid syntax and the urls.py is this: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static app_name='shop' urlpatterns = [ url('admin/', admin.site.urls), url(r'^', include('shop.urls', namespace='shop'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This one looks like Django is acting up and is annoying me. -
How to document a Django project?
How should I go about documenting a Django project? I'm not talking about an app that I'm creating that I'll push to github. It's basically internal documentation that will help new developers that we employ to get up to speed with the system. (I guess that's the point of documentation in general) Should I be documenting each and every view function, model or form as below: def home(request): """View that renders the home page.""" class MyModel(models.Model): "Documentation regarding my model.""" It seems like a bit of overkill. Are there perhaps some good projects that I can look at for inspiration? -
Process large dictionary response in chunks for operations
I have a large dictionary response by which i am creating object in bulk. Since It is a simple object creating in bulk, so it's taking too much time. I am trying to do it by multiprocessing or thread. So I can create bulk object in pieces of data(by single file) and store them together at end. here is my function def create_obj(self, resp): school_db = Schools.objects.bulk_create( [Schools( **{k: v for k, v in value.items() })for key, value in resp.items() ]) return school_db and sample of my large dictionary response- response = { 'A101': { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', }, 'A102': { 'VEG': True, 'CONTACT': '54321', 'CLASS': 'SEVEN', 'ROLLNO': 'A102', 'CITY': 'GANGTOK', }, } So is there any way to split up the dictionary into 15-20 chunks by which I can use multiprocessing to process. Any help would be appreciated. -
Django - {{ MEDIA_URL }} not working as expected
I'm having a slight problem where my Django media tag isn't working properly. This doesn't return the path I expect - which would be '/media/uploads/image_name_goes_here/', and instead I get '/uploads/image_name_goes_here/' even though I have specified in my settings.py that the MEDIA_URL = '/media/'. My upload_to path in the models for the Image is the following function.. def img_path(instance, filename): return ('uploads/%s' % (filename)) class Image(models.Model): ... image_url=models.ImageField(upload_to=img_path,null=True) ... My html: <img src='{{ MEDIA_URL }}/{{ Image.img_path }}'/> Any ideas on why the 'media/' bit of the URL does not show up? -
what are differences between Generics and Views and Viewsets and Mixins in Django
I am new in Django and Django-Rest and I am studying books and video tutorials about it . but I am confused when can I use of these? what are their advantages and disadvantages ? i just see this http://www.cdrf.co and the only thing I know is there are a lot of ways to do 1 thing . but this is totally unclear for me . -
Writting 'Accept' and 'Reject' function Django
Need a help with CarSupplyChain app, which repeats the car business in short. Got a blocker with writing the 'Accept' and 'Reject' function, do not know how to write it. I have 3 type of users: Manufacturer Admin(MA), Dealership Admin(DA) and Customer(C). DA has the ability to Initiate the Wholesale Deal to MA. Here is the model for Wholesale deal: class WholesaleDeal(models.Model): DEAL_STATUS = ( ('Y', 'Accept'), ('N', 'Reject'), ('W', 'Waiting') ) car_name = models.ForeignKey(WholesaleCar, on_delete=models.CASCADE) car_amount = models.IntegerField() total_price = models.IntegerField() status = models.CharField(max_length=2, choices=DEAL_STATUS, default='W') def __str__(self): return self.car_name MA can see the list of Wholesale Deals and he shall have function rather 'Accept' or 'Reject' that deal. If accepted: An amount of Wholesale Cars equal to the amount specified in the Deal application and have the same specifications as mentioned in the application would be removed from the Manufacturer’s Inventory and added to the Dealership’s Inventory as Retail Cars Total cost would be deducted from the Dealership’s Balance and added to the Manufacturer’s Balance Else if the Manufacturer Admin refuses, the application shows up to the Dealership Admin as “Rejected”. WholesaleCar model: class WholesaleCar(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) blueprint = models.ForeignKey(Blueprint, on_delete=models.CASCADE, … -
Repeat a Django template block with different contents, sometimes
I'm working on a website that has a list of steps on the left and a main content block in the middle/right. I want the list to appear once on all pages with the current step highlighted, while the main content block contains content specific to the current step. My template code for this is: base.html <html><body> <!-- Style, headers, etc. --> <ul style="float: left"> {% for listItem in listItems %} <li>{{ listItem }}</li> {% endfor %} </ul> <div style="float: right"> {% block content %}{% endblock content %} </div></body></html> step1.html {% extends "base.html" %} {% block content %} <!-- Step 1 details --> {% endblock content %} step2.html {% extends "base.html" %} {% block content %} <!-- Step 2 details --> {% endblock content %} So far, so good. However, I then want the user to be able to print all these steps without having to navigate to each step and click File -> Print. So what I want is a single webpage that contains all the steps and their details in one long webpage, so the user can print all steps and their details by simply printing this one page. This means I want to repeat both the list … -
django - need help in building a car supply app
I'm building a car supply management app to get experience in django . I have created user signup and login sytem but now I need help for further functionalities mentioned below A user can signup either as buyer or dealer or manufacturer The attributes and permissions of these roles are described below: Manufacturer Admin: a Manufacturer representative in the system whose role is to maintain his/her Manufacturer’s data. A Manufacturer Admin can do the following: Initiate a Manufacturing Order Accept/Refuse a Wholesale Deal Create/Edit/Delete a Blueprint Modify/Remove Cars from his/her Manufacturer’s Inventory Add Balance to his/her Manufacturer’s account However, he/she cannot do the following: - Contact a Customer in any way Initiate Wholesale Deals Initiate Retail Deals Dealership Admin: A Dealership representative in the system whose role is to maintain his/her Dealership’s data. A Dealership Admin can do the following: Initiate a Wholesale Deal Accept/Refuse a Retail Deal Modify /Remove Cars from his/her Dealership’s Inventory Add Balance to his/her Dealership’s account Customer: An interested buyer willing to conduct Retail Deals with Dealerships. A Customer can do the following: View Cars showcased by Dealerships Offer a Retail Deal to a Dealership Add Balance to his/her account It would … -
Does Django REST Framework works normally with Amazon Lightsail? (CORS error)
I have a Django application deployed on Amazon Lightsail but when I try to do a request to our endpoints using Angular I get HTTP 0 error. I have django-cors-headers installed. settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True I am using Apache web server so I also added this to 000-default.conf Header set Access-Control-Allow-Origin "*" -
Django Query Set to get Row value as column name
class Build(models.Model): name = models.CharField(db_index=True, max_length=56) description = models.TextField(max_length=512, null=True, blank=True) class Case(models.Model): name = models.CharField(db_index=True, max_length=255) description = models.TextField(max_length=1024, null=True, blank=True) class Result(models.Model): status = models.CharField(max_length=12) result_build = models.ForeignKey(Build, related_name='result_build', on_delete=models.CASCADE) result_case = models.ForeignKey(Case, related_name='result_case', on_delete=models.CASCADE) Here is my model i need django query set to get data like below .................................................... : case_name : case_description : build_X : build_Y : :...........:..................:.........:.........: : test1 : case1 : PASS : FAIL : : test2 : case2 : FAIL : PASS : :...........:..................:.........:.........: Where case_name and case_description are fields from Case model build_X and build_Y are the two build names avaialble in build model and PASS and Fail are the status for different case and build from result model -
Django CreateView inline formset instance and queryset
So I have a view to make customer payments. When the page is first rendered there's an empty form. I'm using ajax to choose a customer then return an html string of all the outstanding invoices for that customer and inserting it into the empty form. When the form is submitted in order for the outstanding invoices formset to be valid I need to pass it the matching instance and queryset as the ajax generated formset. The problem I'm running into is passing the customer instance into get_context_data(). Right now I have customer hard-coded to pk=1 and can confirm that the formset is valid. There's also a hidden field with the value for customer in the form but I'm not sure how to pass that into get_context_data(). Anyone have any idea how to accomplish this? class PaymentCreate(CreateView): template_name = 'payment_create.html' model = Pay_hdr success_url = reverse_lazy('payments') form_class = PaymentHeadForm def get_context_data(self, **kwargs): context = super(PaymentCreate, self).get_context_data(**kwargs) context['customers'] = Customer.objects.all().order_by('name') if self.request.POST: customer = Customer.objects.get(pk=1) # need to replace this line queryset = Accounts_receivable.objects.filter(customer=customer).exclude(balance=0).order_by('-date_trans') context['user'] = self.request.user context['formset'] = ARLineFormset(self.request.POST, instance=customer, queryset=queryset) else: context['formset'] = ARLineFormset() return context def form_valid(self, form): context = self.get_context_data() user = context['user'] formset = context['formset'] if …