Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not assign must be a instance. Django
Error : Cannot assign "'1'": "OrderInfo.ordertype" must be a "Orders" instance. I know that it means 'string' must to be an 'instance' (maybe model object) But, I have no idea why string is not allowed. This is my code. Models.py : class OrderInfo(models.Model): post = models.OneToOneField(Post) ordertype = models.ForeignKey(Orders) company = models.CharField(max_length=50, blank=True, null=True) position = models.CharField(max_length=50, blank=True, null=True) class Post(models.Model): board = models.ForeignKey(Board) writer = models.CharField(max_length=50, blank=True, null=True) writtendate = models.DateTimeField(blank=True, null=True) editeddate = models.DateTimeField(blank=True, null=True) subject = models.CharField(max_length=50, blank=True, null=True) text = RichTextField() hits = models.IntegerField(default=0) class Orders(models.Model): order = models.CharField(max_length=50, blank=True, null=True) Forms.py : class OrderEditForm(forms.ModelForm): qs = Orders.objects.all() list = [(order.id, order.order) for order in qs] ##### list's value is [('1', 'A'), ('2', 'B')] ordertype = forms.CharField(widget=forms.RadioSelect(choices=list)) class Meta: model = OrderInfo fields = ('ordertype', 'company', 'position') class PostForm(forms.ModelForm): class Meta: model = Post fields = ('subject', 'text') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['subject'].required = True views.py def order_post_edit(request, board_id, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) orderform = OrderEditForm(request.POST, instance=post.orderinfo) if form.is_valid(): print(request.POST['ordertype']) print(orderform.fields) post = form.save(commit=False) post.editeddate = timezone.now() post.save() orderform.save() return redirect('order_post', board_id=board_id, post_id=post.id) else: form = PostForm(instance=post) orderform = OrderEditForm(instance=post.orderinfo) return render(request, 'board/order/order_post_edit.html', {'form': … -
Accessing relative import beyond top-level package
i have searched across stackoverflow and i havent been able to come up with an answer. I have this directory: project/ util/ utility.py models.py So here is a description of what each file does models.py : contains a list of my django models utility.py: from ..models import * [...] May i know why i keep getting this error: ValueError: attempted relative import beyond top-level package? And how can i solve this? -
Protect third party iframe like from being used elsewhere
I am using a third party (Company X) service for a part of my app (Django based), which is behind a secure login. The content from X is delivered in an iframe that is simply embedded in one of my pages. I have spent a lot of time building the custom content in X's app (it is a custom, interactive geology tool) and my subscription with X is pricey as well. I want to protect against the possibility of one of my users sharing the iframe link with other coworkers or even users in other companies and simply using my content from X without even having to log into my app. Unfortunately, X has no way to limit the iframe content by IP or any other type of link security. I know, sounds crazy but that's the way it is right now. What would be the best way to build my own security solution? Is there a way to use another server as an intermediary, so that when the client opens the page my live server hits my intermediary server that fetches the content from X? Then I only accept requests on my intermediary server from my live server. Thanks … -
nginx config for flower celery as a subdomain
I am trying to setup nginx config to run my flower instance in a subdomain. here is the config: upstream myapp { server unix:///var/www/myapp/application/live.sock; } server { listen 80; server_name app.myapp.com; charset utf-8; client_max_body_size 75M; # Django media location /media { alias /var/www/myapp/application/app/media; expires 60d; add_header Cache-Control public; } location /static { alias /var/www/myapp/application/app/static; } location / { uwsgi_pass myapp; include /etc/nginx/uwsgi_params; } } server { listen 80; server_name flower.myapp.com; charset utf-8; error_log /var/log/nginx/error.log debug; location / { proxy_pass http://localhost:5555; proxy_set_header Host $host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } The config for app.myapp.com is working. But if I go to flower.myapp.com it is giving me 504 Gateway Time-out after loading for some seconds. what am I doing wrong? -
Django filter tag not working: AttributeError at / 'str' object has no attribute 'filter_function
According to the Document model below, the 'document.upload.name' in the template will display like "user_NAME/smile.jpg". I want to split the "user_NAME/smile.jpg" by '/'. So in the template, it will only display "smile.jpg". I use the 'value.split' in the filter of 'upload_extras'. but the error was: 'str' object has no attribute 'filter_function'. this is the template: <td><a href="{{ document.upload.url }}" target="_blank">{{ document.upload.name|filename_extract }}</a></td> this is my function in upload_extras.py #upload_extras.py from Django import template register =template.Library @register.filter('filename_extract') def filename_extract(value): '''extract the file name from the upload_to_path''' folder, filename = value.split('/') return filename And the last is the model: # Create your models here. def upload_to_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.username, filename) class Document(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(upload_to=upload_to_path) user = models.ForeignKey(User, on_delete=models.CASCADE) -
UnboundLocalError : local variable 'album' referenced before assignment
i need help... im a beginner script display -
django - context processor variables are not being updated
I have several variables within a navbar that are to be displayed on every single template, so I've made a custom context processor to handle the fetching of those variables. Everything is working, except that when the data is changed in the database, the values of the context variables are not refreshed(for example it'll only get updated once I quit runserver and rerun). Here's my basic pseudo code: context_processor.py: foo = db.get('foo') bar = db.get('bar') def default(request): return {'foo': foo, 'bar': bar} base.html: {% block header %} foo value is: {{ foo }}, bar value is {{ bar}} {% endblock %} {% block content %} {% endblock %} some_other_template.html: {% extends "base.html" %} {% block content %} ...blabla {% endblock %} Is there something I am missing or is this normal behavior? Have I used the wrong approach of using a context processor here? -
What happens behind the scenes in 'Q' complex database queries?
I am trying to write a query that is as efficient as possible. Here is my problem: Assume I have 10 teachers objects, and each teacher has a 100 test objects (The test is related to the teacher by OneToOne relation). I have the unique slug of the each test, and so I can just look it up like this: CreateTest.objects.filter(slug__iexact= slug_name) But, this way seems very inefficient because Django will look for every test that has been created, and there is 1000 of them out there because there are 10 teachers. Instead, I am trying to do something like this: teacher=TeacherUser.objects.filter(user__username__iexact=self.request.user) teacher_test = teacher.createtest_set.filter(slug__iexact=slug_name) Now, it is getting all the tests from a specific user, and then it is searching for that test that is needed. I want to write that same thing using 'Q'. I thought about writing this: CreateTest.objects.filter(teacher__user__username=self.request.user, slug__iexact=self.kwargs['slug']) But, for some reason, I think that this is not doing what I want. It is checking if the teacher is the same, and the slug is the same. I want it first to get all the tests for a specific teacher. After that I wanted to query the test from only from that list. Any ideas … -
Django settings.py "psycopg2.OperationalError"
In my django project, I had a sqlite3 database, and I wanted to add another postgresql one, I followed the django docummentation and my settings code is : # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'users': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres_user', 'PASSWORD': 'pgdjango', 'HOST': 'localhost' } } and like the docummentation say, I should do a migrate like this : python manage.py migrate --database=users When I do that, I get an error : Traceback (most recent call last): File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line … -
How do I set the value of a model object's property after using `get_field()`?
I'm making a terminal command for my Django app: from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import FieldDoesNotExist from django.apps import apps class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--app", dest="app", required=True, ) parser.add_argument( "--model", dest="model", required=True, ) parser.add_argument( "--col", dest="col", required=True, ) def handle(self, *args, **options): app_label = options.get('app') model_name = options.get('model') column_name = options.get('col') try: model = apps.get_model(app_label=app_label, model_name=model_name) except LookupError as e: msg = 'The model "%s" under the app "%s" does not exist!' \ % (model_name, app_label) raise CommandError(msg) try: column = model._meta.get_field(column_name) except FieldDoesNotExist as e: msg = 'The column "%s" does not match!' % column_name raise CommandError(msg) else: print(column, type(column)) # Do stuff here with the column, model. Right now, column is <django.db.models.fields.IntegerField: column_name>. I want this instance of model to have column_name set to 100. How can I set and save this instance in this manner? -
django.core.exceptions.FieldError: Unknown field with datetime field in django modelform
I'm using django 1.8. When I use a datetime field, I get an error saying that the field is unknown. I checked many times that the name is spelled right. Any ideas what's going on here? class MyTable(models.Model): origin = models.PositiveIntegerField(null=True, blank=True) last_modified = models.DateTimeField(auto_now=True) class MyTableForm(ModelForm): class Meta: model = MyTable fields = ['origin', 'last_modified'] Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/home/user/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/venv/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/user/venv/lib/python2.7/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/user/src/biosys/myapp/myapp/admin.py", line 6, in <module> from forms import * File "/home/user/src/biosys/myapp/myapp/forms.py", line 46, in <module> class InterpForm(ModelForm): File "/home/user/venv/lib/python2.7/site-packages/django/forms/models.py", line 295, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (last_modified) specified for MyTable -
Mysql error 1049 prevents access to make corrections
I have developed a Django application and now find myself trying to host it on ubuntu 16.04. I'm following the DigitalOcean guides as far as possible. I started a database for a Django application, created a user for the application, granted privileges to that user and then decided to dump the database for some reason (I think I was planning to ensure that the Django model could be migrated from scratch, but this was just before Christmas.) If I try to log in to mysql I get Error 1049 (42000): Unknown database, and kicked back out to the shell - no interactive mysql. How can I fix this? It seems that mysql won't listen to me. -
Testing `CharField(unique=True)` in django with py.test
I'm working to move all tests for a django application over to py.test. One case I have not been able to overcome is testing that uniqueness constraints on model fields are enforced. An example test: # requirements.txt pytest pytest-django ... # myapp/models.py from django.db import models class UniqueModel(models.Model): unique_field = models.CharField(max_length=100, unique=True) # myapp/tests/test_unique_model.py from django.db import IntegrityError import pytest from myapp.models import UniqueModel def test_unique(self, db): unique_1 = UnqiueModel(unique_field='not-unique') unique_1.save() unique_2 = UniqueModel(unique_field='not-unique') with pytest.raises(IntegrityError): unique_2.save() This test fails: ... with pytest.raises(IntegrityError): > unique_2.save() E Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'> ... Any guidance? Thanks! -
Django Admin, accessing reverse many to many
I would like to have access to reverse many to many relationship on Django Admin (django.contrib.admin). class Company(models.Model): name = models.CharField(max_length=100) status = models.BooleanField() users = models.ManyToManyField(User, related_name='company') Right now I am able to see the User through Company on Django Admin but I cannot access the company through User. What is the correct way to have access to reverse relationship? -
How I can get user group permissions for django-admin fields?
In project, with custom django-admin, I create two groups with permissions, one group name "A" other is "B". My class is: class Card(models.Model): number = models.CharField(max_length=250, blank=True, null=True, default="") I want show to A group number field for only read, to B group for edit. How can I get request.user in my admin.py. for using query like this. from django.contrib.auth.models import Group class Card_Admin(admin.ModelAdmin): if Group.objects.get(name='A').user_set.filter(id=request.user.id).exists(): readonly_fields = ['number'] -
How to return python script response as Http response using Django framwork
I am using Python Django framwork, new to it. I am getting "None" in browser, not sure what is wrong in my code.. from django.http import HttpResponse def index(request): from amazon.api import AmazonAPI AMAZON_ACCESS_KEY = "cant share my key" AMAZON_SECRET_KEY = "cant share my key" AMAZON_ASSOC_TAG = "cant share my tag" REGION = "US" amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG) products = amazon.search(BrowseNode='3760911', SearchIndex='Beauty', MaximumPrice='30') for i, product in enumerate(products, 1): return HttpResponse(print(str(product))) The code works like a charm when I run in python shell however it doesn't run in browser. -
Testing error: No module named 'app.post'
I'm trying to use Django's unit test feature. I've added a blank test.py under app/post/tests (along with __init__.py). However when I run python manage.py test post it returns ImportError: No module named 'app.post'. Any idea why it says this and how I can fix it? -
Create related field if it does not already exist
I have the following two Django model classes (names have been changed to protect the not-so-innocent): class Foo(models.Model) foo = models.CharField(max_length=25) class Bar(models.Model): foo = models.ForeignKey(Foo) And Django Rest Framework serializers for each model: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ('foo',) class BarSerializer(serializers.ModelSerializer): class Meta: model = Bar fields = ('foo',) Routes: urlpatterns = [ url(r'^foo/', ModelListView.as_view(model_class=Foo, serializer_class=FooSerializer), name='foo'), url(r'^bar/', ModelListView.as_view(model_class=Bar, serializer_class=BarSerializer), name='Bar'), ] Views: class ModelListView(ListCreateAPIView): model_class = None serializer_class = None def create(self, request, *args, **kwargs): data = JSONParser().parse(request) serializer = self.serializer_class(data=data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) To illustrate usage of the /bar route, the Bar model and its serializer, I wrote a test. I want to be able to specify the string value of the field foo. The POST request should use an existing instance of Foo if one already exists. Otherwise it should create it. class BarTest(UnitTest): def setUp(self): self.model_class = Bar self.fields = [{'foo': 'foo1'}, {'foo': 'foo2'}] self.url = reverse('bar') def test_post(self): data = JSONRenderer().render(self.fields) response = self.client.post(self.url, data=data, content_type='application/json') self.assertEqual(HTTP_201_CREATED, response.status_code) result = response.json() self.assertEqual(self.fields, result) I read Serializer Relations in the Django REST Framework documentation. It seems that either StringRelatedField or SlugRelatedField might fit my … -
How to use "rest_framework" routers with Django 2
I am aware that "Django 2 with router url patterns has changed". I cant manage to work with Router because I am getting an error : 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I have written a basic model and after that I have created an api folder, I have prepared files "views.py": from rest_framework import generics from yogavidya.apps.articles.models import Article from .serializers import ArticleSerializer from rest_framework import routers, serializers, viewsets class ArticleUpdateView(generics.RetrieveUpdateAPIView): lookup_field = 'pk' serializer_class = ArticleSerializer queryset = Article.objects.all() router = routers.DefaultRouter() router.register(r'api/articles', ArticleUpdateView, base_name='api-articles') after I have urls.py : from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from .views import ArticleUpdateView from django.urls import re_path urlpatterns = [ re_path(r'articles/(?:page-(?P<page_number>\d+)/)?$', ArticleUpdateView.as_view(), name='article-update'), ] now I want to add the api to project urls.py from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static from yogavidya.apps.articles import views from .views import home,home_files, pricing from … -
Django - how to make a complex math annotation
I have this model: class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='img/') signature = models.TextField(null = True) The signature is a numpy monodimensional vector encoded in json. In order to make my query, I have to decode each object signature into a nparray, and make a dot product between each object's signature and a given vector, then annotate as a float (named "score") field beside each raw. Lastly I have to order from max to min. I tried this in view.py def image_sorted(request): query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/003_ant_image_0003.jpg") # a NParray object image_list = Image.objects.annotate(score=np.dot( JSONVectConverter.json_to_vect(F('signature')), query_signature.T ).astype(float)).order_by('score') #JSONVectConverter is a class of mine return render(request, 'images/sorted.html', {'image_sorted': image_list}) of course it doesn't work. I think "F()" operator is out of scope... If you're wondering, I'm writing an image retrieval webapp for my university thesis. Thank you. -
Store raw data into .png file in python
>>> def qrcodegenerate(nbr): ... res = requests.get("https://chart.googleapis.com/chart?cht=qr&chs=300x330&choe=UTF-8&chl="+str(nbr)) ... print(res.url) ... data =res.text ... with open("C:\wamp\www\Paymentapi\qrcode\qr_"+str(nbr)+'.png','w',encoding="utf-8") as f: ... f.write(data) ... >>> qrcodegenerate(5697) Here I am calling API to generate qrcode and I want to save into png. Qrcode is generating but it not saving. -
Contactform in footer of page
I have a contactform in the footer of a website. So it is on every page. It works, with one problem: as soon as it is sent, it doesn't show anymore. More specific I guess when my request is no longer empty. @register.inclusion_tag('home/tags/contact.html', takes_context=True) def contact_form(context): request = context['request'] if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['naam'] from_email = form.cleaned_data['email'] message = form.cleaned_data['bericht'] messages.success(request, 'Form submission successful') try: send_mail(subject, message, from_email, ['myemailaddress']) except BadHeaderError: return HttpResponse('invalid header found') return context else: form = ContactForm() return {request: 'context.request', 'form': form} Tips would be appreciated. -
Calculate price in models with django v2.1
I need your help about this app I'm making, in those models, I want the price of the topping and the type be calculated automatic in the model Pizza, so when someone record new data, he can choice the type and the topping and the price is calculated and save it in that table Pizza. class Type(models.Model): typeName = models.CharField( max_length = 50 ) priceBase = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 ) obsBase = models.CharField( max_length = 200, null=True ) def __str__(self): return self.typeName class Topping(models.Model): nameTopping = models.CharField( max_length = 200) priceTopping = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 ) obsTopping = models.CharField( max_length = 200, null=True ) def __str__(self): return self.nameTopping class Pizza(models.Model): namePizza = models.CharField(max_length=200) typePizza = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True ) toppingPizza = models.ForeignKey(Topping, on_delete=models.SET_NULL, null=True) obsPizza = models.CharField(max_length = 200, null=True) def __str__(self): return self.namePizza Guys, can I use this logic to save my kind of pizzas in a database so I can retrive the calculated data when someone order a pizza online?, I'm starting with the right foot?, sorry I'm new at django, and I'm trying to learn everything on the web, and your help will be precious for me! … -
Is it possible to limit the number of messages a user can send a day?
I have been using Django Postman for a few weeks now, and in order to limit the number of messages sent by each user, I have been wondering what would be the best way to limit the number of messages a user can send a day, a week... using Django-postman? I have been browsing dedicated documentation for weeks too in order to find an answer for the how, but I think this is not a usecase for now, and I do not really know how to manage that. Of course I am not looking for a well cooked answer, but I would like to avoid writing labyrinthine code, so maybe just a few ideas about it could help me to see clear through that problematic. Many thanks for your help on that topic! -
Display the fruit's name with the same ID as user's in Django
sorry for the weird example. I have 2 apps : accounts & fruits. Let's say that the user can have 1 fruit and it's showed in his class 'Profile' as 'fruit'. (FRUIT_CHOICES is the ID of the fruit). fruit = models.IntegerField(choices=FRUIT_CHOICES) Now that the User got the fruit's ID in possession, I would like to take more informations from this. So, just after, I write this : user_fruit = Fruit.objects.filter(id = fruit) And here's what I get : django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. How can I fix that ? Thanks !