Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image Upload Django Mongoengine
models.py class ImageUpload(models.Model): image = models.ImageField(upload_to='static/media/images/') forms.py class ImageUploadForm(ModelForm): class Meta: model=ImageUpload fields = ['image'] views.py def imageupload(request,uid=None): imageform = ImageUploadForm() if request.method == 'POST': imageform = ImageUploadForm(request.POST, request.FILES) if imageform.is_valid(): imageform.save() return render(request,'img.html',{'imageform':imageform}) return render(request,'img.html',{'imageform':imageform}) I want to upload an image using django and mongodb. Mongodb is connected with django using mongoengine.I need a neat example to get to know what measures I should I take to achieve it as now I am getting error of "Improperly Configured Database". Thanks in advance. -
How to pass shell environment variable to Supervisor program?
I have a Django app which runs on Gunicorn, and is managed by SupervisorD. I want Django to read the DJANGO_SECRET_KEY variable from the environment, since I don't want to store my secret key in a config file or VCS. Here's my supervisor.conf: [program:gunicorn] command=/.../.virtualenvs/homepage/bin/gunicorn homepage.wsgi -w 1 --bind localhost:8001 --pid /tmp/gunicorn.pid directory=/.../http/homepage When I set the variable and run Gunicorn command from the shell, it starts up just fine: $ DJANGO_SECRET_KEY=XXX /.../.virtualenvs/homepage/bin/gunicorn homepage.wsgi -w 1 --bind localhost:8001 --pid /tmp/gunicorn.pid However when I set the variable in the shell and restart the Supervisor service my app fails to start with error about not found variable: $ DJANGO_SECRET_KEY=XXX supervisorctl restart gunicorn gunicorn: ERROR (not running) gunicorn: ERROR (spawn error) Looking at Supervisor error log: File "/.../http/homepage/homepage/settings.py", line 21, in <module> SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] File "/.../.virtualenvs/homepage/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'DJANGO_SECRET_KEY' [2017-08-27 08:22:09 +0000] [19353] [INFO] Worker exiting (pid: 19353) [2017-08-27 08:22:09 +0000] [19349] [INFO] Shutting down: Master [2017-08-27 08:22:09 +0000] [19349] [INFO] Reason: Worker failed to boot. I have also tried restarting the supervisor service, but same error occurs: $ DJANGO_SECRET_KEY=XXX systemctl restart supervisor ... INFO exited: gunicorn (exit status 3; not expected) My question is how do … -
Django - printing multiple passed lists from views.py
I have 4 lists with the same length and would like to pass all of them to the html page. views.py return render(request, 'result.html', {'listA':listA, 'listB':listB, 'listC':listC, 'listD':listD}) And here is the code when I tried with Flask. app.py return render_template('result.html', listA = listA, listB = listB, listC = listC, listD = listD) Below is the code in the template file; with Flask, it prints out the table without any problems, but it doesn't seem to work with Django. How should I fix my code? result.html {% for i in listA %} <tr> <th> {{ listA[loop.index] }} </th> <td> {{ listB[loop.index] }} </td> <td> {{ listC[loop.index] }} </td> <td> {{ listD[loop.index] }} </td> </tr> {% endfor %} -
I don't want my query set be cached
I have my own object manager that limit according to user logged in user: regs = Regelung.objects.filter_for_user(request.user, regelung='differenzregelung') I have two record in database with above limited query in database. but when I iterate on it not show added recently record, it happens like a cache. print regs.count() ==> 2 print regs ==> show one record that added before and not show record that added recently print len(regs) ==> 1 what should I do for update query set? -
Django indexing in template
I have the following section in my template where I make use of indexing my query set to access its fields. I know this can be done without indexing but I am trying whether this can be done by indexing. confirmed_length is a list which is [0] and confirmed_bookings is the query_set {% for i in confirmed_length %} <tr> <th scope="row">{{ confirmed_bookings.0.booking_id }}</th> <td>{{ i }}</td> <td>{{ confirmed_bookings.0.booking_date }}</td> <td>{{ confirmed_bookings.i.room_id }}</td> </tr> {% endfor %} where {{ i }} shows 0 but nothing shows for others except {{ confirmed_bookings.0.booking_date }} and {{ confirmed_bookings.0.booking_id }}. Indexing with 0 shows me the details but indexing with i (where i is an integer and its value is 0) does not show anything. -
Accessing instance from Meta class in ModelForm
Django 1.11.4 Below I have set stub values as attributes: "data-model": "data-model" "data-id": "data-id" Real values are in the instance. But I have failed to access the instance from Meta. Could you help me understand how to do that. views.py class BookmarkMixin(): def get_context_data(self, **kwargs): context = super(BookmarkMixin, self).get_context_data(**kwargs) form = BookmarkForm(instance=bookmark) context['form'] = form return context forms.py class BookmarkForm(forms.ModelForm): class Meta: model = Bookmark fields = ['memo'] widgets = { 'memo': forms.TextInput(attrs={'id': "bookmark-input", "data-model": "data-model", "data-id": "data-id",}) } -
django final clean (validation)
I've a very simple django form with two fields. each have their own validation and rules (one is email the other password). After - and only after - they pass their individual validation(clean), I want to perform another final validation which takes both fields into consideration. So far i've tried something like below but the clean method is being called even when the fields haven't passed validation. class LoginForm(forms.Form): email = forms.EmailField(required=True) password = forms.CharField(required=True, validators=[MinLengthValidator(6)], widget=forms.PasswordInput) class Meta: model = User fields = ("email", "password") # this method is being called even when the password field hasn't passed validation. def clean(self): user_email = self.cleaned_data.get("email") user_password = self.cleaned_data.get("password") ... Am I missing something or am is there another way to achieve what I'm trying; -
posting data to REST API with angularjs after getting a part of the data using $http.get()
I have a backend written in django and it looks like this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "message_body": "Hi mam, you are amazing!!!", "deleted": false, "id": 7, "timestamp": "2017-08-23T15:22:00.676099Z", "moderator_approval_count": 0, "verified_by_moderators": true, "last_like_activity_id": 8, "last_like_count": 2, "likes": [ { "message_id": 7, "liked": true, "unliked": false, "id": 7, "timestamp": "2017-08-26T05:56:02.167164Z", "user_id": 1 }, { "message_id": 7, "liked": false, "unliked": true, "id": 8, "timestamp": "2017-08-26T05:57:49.756284Z", "user_id": 1 } ], "teacher_id": 5 }, { "message_body": "Hi sir, you are amazing ^ 34 !!!", "deleted": false, "id": 13, "timestamp": "2017-08-23T19:20:07.468438Z", "moderator_approval_count": 0, "verified_by_moderators": true, "last_like_activity_id": 6, "last_like_count": 1, "likes": [ { "message_id": 13, "liked": true, "unliked": false, "id": 6, "timestamp": "2017-08-23T19:32:20.652049Z", "user_id": 1 } ], "teacher_id": 6 }, { "message_body": "Hi sir, you are great!!!", "deleted": false, "id": 14, "timestamp": "2017-08-25T08:49:34.158602Z", "moderator_approval_count": 0, "verified_by_moderators": true, "last_like_activity_id": -1, "last_like_count": 0, "likes": [], "teacher_id": 7 }, { "message_body": "You're a wonderful teacher, mam!", "deleted": false, "id": 15, "timestamp": "2017-08-26T15:14:44.745096Z", "moderator_approval_count": 0, "verified_by_moderators": true, "last_like_activity_id": -1, "last_like_count": 0, "likes": [], "teacher_id": 5 } ] I'm deploying it using a virtual environment. My html looks like this: <div class="form-group" ng-controller="createMessage"> <label class="control-label" for="selectTeacher">To</label> <select class="form-control" id="selecT" ng-model="chosen.teacher" ng-options="teacher.name … -
Add and delete option are not visible in django administrator, when using along with mongodb
Attached is the code snippet of the settings file, I have used MongoDB engine. I am not very sure what is happening wrong here. Even on starting a fresh new project, add or delete options are not visible. I have added some extra middleware and context processor in the settings.py as well. """ INSTALLED_APPS = ( 'dbcollection', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( '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', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'boltadmin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'boltadmin.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default' : { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'my_database' } } -
`validators` keyword argument not working when `many` is True?
def validate_number_of_product(products): if len(products) > 1: # this may be temporary raise ValidationError(_('Too many products.')) class OrderAddSerializer(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField( queryset=Product.objects.filter(sold=False), write_only=True, validators=[validate_number_of_product], many=True, allow_empty=False, ) # ... I'm using PrimaryKeyRelatedField with many=True, and also need to validate the field (independently). But it seems that validate_number_of_product is not called when calling OrderAddSerializer.is_valid(). Is this a limitation of DRF or is because I'm using it incorrectly? -
Django-paypal integration
I've followed the instruction using https://django-paypal.readthedocs.io/en/stable/ and it worked. But problem is without test buyer account it does not accept the payments. What to do now? -
django - NOT NULL constraint failed: blog_comment.posts_id
I'm trying to have a comment form be submitted by the user to the respective blog. I'm getting the error "NOT NULL constraint failed: blog_comment.posts_id" when I do that. views.py def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post_detail', slug=post.slug) else: form = CommentForm() template = "blog/post/add_comment.html" context = {'form': form} return render(request, template, context) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('user', 'email', 'title', 'body',) models.py class Post(models.Model): STATUS_CHOISES = ( ('draft', 'Draft'), ('published', 'Published'), ) category = models.ForeignKey(Category) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) content = models.TextField() seo_title = models.CharField(max_length=250) seo_description = models.CharField(max_length=160) author = models.ForeignKey(User, related_name='blog_posts', default=settings.AUTH_USER_MODEL) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOISES, default='draft') def get_absolute_url(self): return reverse('blog:post_detail', args=[self.slug]) def __str__(self): return self.title class Comment(models.Model): posts = models.ForeignKey(Post, related_name="comments") user = models.CharField(max_length=250) email = models.EmailField() title = models.CharField(max_length=250) body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.title What is wrong with my code? From what I understand, somewhere/somehow the comment is not being sent to the right blog post, because … -
How to provide links to each data from many to many relationships on the admin site table
Im newbie use python and django, I have problem in django admin site. My plan is to give a different url to any existing data from many to many relationships that appear on the admin site table. When click data siswa will lead to the edit page. # model.py class WaliSiswa(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=11, choices=TITLE) nama_lengkap = models.CharField(max_length=125) jenis_kelamin = models.CharField(max_length=1, choices=GENDER_CHOICES) relations = models.CharField(max_length=50, choices=RELATIONS) tempat_lahir = models.CharField(max_length=255) tanggal_lahir = models.DateField() alamat_ktp = models.CharField(max_length=500) alamat_tinggal_saat_ini = models.CharField(max_length=500) profesi = models.CharField(max_length=225) nomer_telepon = models.CharField(max_length=25) nomer_seluler = models.CharField(max_length=25) email = models.CharField(max_length=125) siswa = models.ManyToManyField(Siswa) # admin.py class WaliSiswaAdmin(admin.ModelAdmin): list_display = ('getTitleNamaLengkap', 'relations', 'getSiswa', ) def getSiswa(self, obj): return ', '.join([d.nama_lengkap for d in obj.siswa.all()]) getSiswa.short_description = 'Siswa' Like the picture above, I managed to display the data but confused to add its url. So I am very grateful for you who can provide the best solution. -
how to send HTML code via POST using django
How can i send html code via POST method ? now django cuts the part of my code. Should I use any filter ? I have a simple form and trying to check value using print request.POST['htmlContent'] Thanks in advance -
Django INSERT or UPDATE
I am obtaining data from the amazon api, Info is coming in, but I am used to importing data using mysql. I know I should not import anything to Django unless I use the models. Here is what I have come up with. There are may sku's, And I go through obtain each info, include the ItemsSKU(pk) so that I can use it to update each sku. This is how I used to do it in SQL, """INSERT INTO webservice_bsrdata (ItemSKU,AISN,Best_Sellers_Rank,selling_price,price,availability,reviews) VALUES (%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE AISN=%s,Best_Sellers_Rank=%s,selling_price=%s,price=%s,availability=%s,reviews=%s """,payload) conn.commit() Here is my bottom of my Django class. HOW DO I INSERT or UPDATE in Django? def refresh_skus(self,skus): """Extracts cars from page @scope: @param: list @return list""" extract = []#list to hold the extracted data if skus is None: return{"code":-1,"error":"Not defined"} if len(skus) == 0: return {"code":-2,"error":"Empty value"} for sku in set(skus): try: #by ASIN or BY SKU choose one # SKU self.product = self.amazon.lookup(ItemId=sku, IdType="SKU",SearchIndex='All') #ASIN # product = amazon.lookup(ItemId=sku) ItemSKU = sku try: AISN = self.product.asin print AISN except Exception as e: AISN = "" print e try: Brand = self.product.get_attribute("Brand") time.sleep(5) except Exception as e: Brand = "" print e extract.append({ "itemSKU" : str(sku) "ASIN" : str(ASIN), … -
Using jQuery ajax to display something upon a change to a BooleanField in a django database
I have an uber like django app. A customer can signal that they are looking for someone to provide a service and people in the same area who are looking to be service providers can view a list of actively seeking customers. When the customer presses the button signalling they are looking for a serivce, they are redirected to a page that says "Thank you, you will be notified when someone is on the way" and it sets attribute active to True. This displays them on the mentioned list where customers can be 'claimed.' When a service provider claims a customer. I want the customer's page to display 'Someone will be there shortly" or something of that nature. I have the following code: models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) active = models.BooleanField(default = False) urls.py urlpatterns = [ #home url(r'^home/$', views.home, name = 'home'), #/claim/user_id url(r'^claim/(?P<user_id>[0-9]+)/$', views.ClaimView.as_view(), name = "claim"), #/active url(r'^active/$', views.customer_active, name='customer_active'), ] def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() customer_active.html (the customer is looking at this … -
Django foreign key from different app is NoneType
I have a model like this in a django 1.11.4 app which references a foreign key in different installed app (django_celery_results, listed in settings.INSTALLED_APPS): class Worker(models.Model): class Meta: app_label = 'happy_farm' tasks = models.ForeignKey('django_celery_results.TaskResult', null = True) I can run makemigrations happy_farm and migrate without error, but when I try to access worker.tasks it is NoneType rather than the TaskResult manager: $ from happy_farm.models import Worker $ type(Worker.objects.first().tasks) NoneType Typically I'd expect to see something like django.db.models.fields.related_descriptors.ManyRelatedManager. I've also tried importing django_celery_results.models and referencing it directly, like: import django_celery_results class Worker(models.Model): class Meta: app_label = 'happy_farm' tasks = models.ForeignKey(django_celery_results.models.TaskResult, null = True) With the same outcome. -
Automated django scaffolding available
I am getting tired of writing boilerplate code for new models i am adding to my system. Is there any way I can just create a model, and then have some automated system create all CRUD for me automatically? views, templates etc. I know there exists cookiecutter which seems like a nice tool, but I think this is ony for project startup and not for scaffolding new models when project already exists, or am I wrong? I am interested in most elegant way to do this. Thanks -
How to refer to different templates in different apps in Django?
The structure of my project is this: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py Home/ templates/ Home/ Home.html Login/ templates/ Login/ Login.html Application/ templates/ Application/ Application.html Details.html mysite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Home.urls', namespace="Home")), url(r'^Application', include('Application.urls', namespace="Application")), url(r'^Login', include('Login.urls', namespace="Login")), url(r'^User', include('User.urls', namespace="User")), ] Home/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^', views.Home, name = 'Home'), ] Application/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'Application', views.Application, name = 'Application'), ] The structure for the views.py(s) is the same for each app (with changes in names, of course). Home/views.py from django.shortcuts import render def Login(request): return render(request, 'Login/Login.html') I have two links in my Home.html. One is supposed to direct a user to Application.html and the other, to Login.html. I tried to do the followings: templates/Home/Home.html <a href="{% url 'Application:Application' %} ">Apply Now!</a> <a href="{% url 'Application' %} ">Apply Now!</a> <a href="/Login/Login.html">Login</a> None of them work. No errors, no redirections, nothing. What is weird about this whole thing is that url changes for Login and Application look different, even though the structure of both apps are the same: … -
Django - context processors in the view?
Context processors in Django usually allow for a variable to be accessed by all templates. How do I access this variable in the views.py (backend) code? Here is what I have tried: def index(request): request_context = RequestContext(request) center = request_context.get("center") But I get "none" for the center variable. And in the context processor code: def center(request): return {'center': '123'} I have added the context processor's "center" function to the context processor list in settings. -
Get a text box to pop up Django
I am trying to get a text box to pop up on an event. I have an uber like django app, a customer can be looking for someone to provide a service. Once someone 'claims' this customer (ie they are going to provide the service) I want a text box to pop up on their screen saying "Someone is on their way." So basically there is a BooleanField 'active' in the database, True when the customer is looking for a service and False they are not. When a customer is claimed this sets active to false. Is there a way based to trigger a textbox in the customer view when that happens, can I use JQuery, Ajax, etc ? -
How do I write a python test that creates an InMemoryUploadedFile from a zip file?
I have the following Django code in my system: zip_file = zipfile.ZipFile(file, 'r') for filename in zip_file.namelist(): try: file_read = zip_file.read(filename) print(filename) I am trying to test this code by passing in a zip file from a python TestCase. When I use this code with the web interface, I noticed the zip file is an InMemoryUploadedFile type. So I'm trying to mimic this functionality with my TestCase, but can't seem to create an InMemoryUploadedFile() in my test with a zip file. I've tried this: file_name = 'file.zip' in_memory_uploaded_file = InMemoryUploadedFile(file_name, None, file_name, 'application/zip', 0, None, None) Any recommendations? -
Django defined field does not sort
I have a field in my application. I use the admin for an interface to my djangorestAPI. I want to be able to sort this field that I have modifield to display N/A. Originally when there is no BSR the field would populate as 0, This makes admin.py from .models import BSR @admin.register(BSR) class BSRAdmin(admin.ModelAdmin): list_display = ['ItemSKU','AISN','Brand', 'Best_Sellers_Rank','selling_price','ProductGroup','Color','EAN','MPN','PackageQuantity','PartNumber','availability', 'Reviews'] list_filter = ['Brand','ItemSKU','AISN','price','selling_price','availability'] search_fields = ['ItemSKU','AISN','price','selling_price','availability'] # read_only_fields = ("",) def Reviews(self, obj): return format_html('<a href="{}">Reviews</a>', obj.reviews) def Best_Sellers_Rank(self, obj): if obj.BSR == 0: return "N/A" if obj.BSR == None: return "N/A" return obj.BSR model.py BSR = models.IntegerField(blank=True,null=True) Maybe there is a simpler way to get a n/a in the empty field. I know integers are usually left blank=False,null=False, so there is no discrepancy between empty and null. Since I have a condition for those I figured this was ok. In general how do I deal with sorting Integer fields so they are easy to sort, especially when I end up with unwanted 0's in the first page. Using django 1.11 python 2.7 -
django bootstrap css working, custom css isn't
I'm working with django and having problems with my css sidenote: the bootstrap css is still working html- {% extends "base.html" %} {% load bootstrap3 %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'questions/style.css' %}" /> {% block content %} <h1 class="red">RED</h1> <a href="{% static 'questions/style.css' %}">stylesheet</a> css- h1.red { color: red; } when i click on the link it bring me to my css. so I am fairly certain my stylesheet is being linked correctly, but my H1 isn't coming up as red (or being affected by anything that i've tried in the css file) -
Can't get form values in Django
Form Code: <form action="/personal/update_status/" method="post">{% csrf_token %} <div class="form-group"> <label for="ticketid">Query id</label> <input name="ticketid" type="text" class="form-control" id="ticketid" placeholder="Enter email"> </div> <div class="form-group"> <label for="status">Set status:</label> <select class="form-control" name="status" id="status"> <option>Submitted</option> <option>In progress</option> <option>Resolved</option> </select> </div> <button type="submit" class="btn btn-success">Update</button> </form> Forms.py: class UpdateForm(forms.ModelForm): class Meta: model = queryrecord fields = ('status','ticketid') In Views.py: form = UpdateForm(data=request.POST or None) print(form.is_valid()) print form.cleaned_data['status'] print form.cleaned_data['ticketid'] form.cleaned_data['status'] prints right value but when I try to print ticketid, It throws error as : print form.cleaned_data['ticketid'] KeyError: 'ticketid'. Why can't I get 'ticketid; in the form?