Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using modelformset_factory and access attributes of an object
I have some Containers and they have a number of Boxes I want to edit. So, naturally, I use modelformset_factory. It works very good: container = get_object_or_404(Container, id=container_id) BoxFormSet = modelformset_factory(Box, fields=('a', 'b', 'c')) formset = BoxFormSet(queryset=container.box_set.all()) In my template I iterate over formset to show the boxes I want to modify. This works very well and I can edit the attributes a, b and c of each Box. But each box has also a label. I want to access the value to show it in the label but it should not be editable, like an input-field. I just need the value. How can I achieve that? -
DRF SessionAuthentication login page insecurity?
In the Django Rest Framework SessionAuthentication documentation it says that Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. Why should I use Django's standard login views on login pages? If I would like to make my own login views (for example, in React, Vue or Angular), what I should take into account to make the view "as secure as the Django's standard login view"? -
get django-cms plugin instance from another page
I have a django-cms page and am still trying to figure out best practices for it. I have the following problem: I have written a projects page, with an plugin ProjectsOverview, which can hold plugins of the type Project. Every Project has a 'tags' list to it, in order to filter the projects. this is done in the ProjectsOverview plugin: def unique_tags(self): split_tags = map(lambda project: project.tags.split(","), self.child_plugin_instances) tags = [item.strip() for sublist in split_tags for item in sublist] return list(set(tags)) by clicking on a project, the visitor is redirected to a new page, set via a PageField in the Project plugin. Now what I'd like to do is reference the different categories in the project page to easily go back to the projects overview. I figured out I can get hold of the plugins by doing this: {% for placeholder in current_page.parent.get_placeholders %} {% for plugin in placeholder.get_plugins_list %} {{plugin}} {% endfor %} {% endfor %} I do not know how to get a plugin instance (something like plugin.instance.unique_tags) from there. Maybe there is someone able to help? Thank you very much! -
django-celery and rabbitmq, scheduled task not executed
I have the following setup: django 1.8.13 celery 3.1.17 RabbitMQ 3.6.12 My relevant settings.py snippet: CELERY_WORKER_DIRECT = True CELERYD_TASK_TIME_LIMIT = 7200 CELERYD_TASK_SOFT_TIME_LIMIT = 7000 CELERY_ROUTES = { 'vdr.tasks.process_uploads': {'exchange': 'C.dq', 'routing_key': 'celery@node1.mailin.msp'}, 'vdr.tasks.send_html_mail_async': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'vdr.tasks.handle_file': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'queued_storage.tasks.TransferAndDelete': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'vdr.tasks.TransferAndDeleteNonLocked': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'queued_storage.tasks.Transfer': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, } CELERYBEAT_SCHEDULE = { 'process-uploads-every-minute': { 'task': 'vdr.tasks.process_uploads', 'schedule': timedelta(seconds=60), }, } BROKER_URL = 'amqp://%(user)s:%(password)s@%(host)s:%(port)s//' % {"host": os.environ.get("RABBITMQ_PORT_5672_TCP_ADDR", "rabbitmq"), "port": os.environ.get("RABBITMQ_PORT_5672_TCP_PORT", 5672), "user": os.environ.get("RABBITMQ_ENV_RABBITMQ_DEFAULT_USER", "user"), "password": os.environ.get("RABBITMQ_ENV_RABBITMQ_DEFAULT_PASS", "password")} CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True I can see in the celery beat log that the tasks gets sent periodically, as expected: [2017-11-25 14:56:57,759: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2017-11-25 14:56:59,775: DEBUG/MainProcess] Open OK! [2017-11-25 14:56:59,776: INFO/MainProcess] Scheduler: Sending due task process-uploads-every-minute (vdr.tasks.process_uploads) [2017-11-25 14:56:59,779: DEBUG/MainProcess] using channel_id: 1 [2017-11-25 14:56:59,780: DEBUG/MainProcess] Channel open [2017-11-25 14:56:59,781: DEBUG/MainProcess] beat: Synchronizing schedule... [2017-11-25 14:56:59,782: DEBUG/MainProcess] vdr.tasks.process_uploads sent. id->cdfd9873-dc27-4e3b-a226-3a367dc4e05f [2017-11-25 14:56:59,782: DEBUG/MainProcess] beat: Waking up in 59.99 seconds. The worker that is meant to execute the task is also up and running: [2017-11-25 15:22:44,826: INFO/MainProcess] Connected to amqp://user:**@172.17.0.2:5672// [2017-11-25 15:22:44,846: INFO/MainProcess] mingle: searching for neighbors [2017-11-25 15:22:45,869: … -
Controlling permission based views in Dojo on hash change
I have a Dojo website in which different widgets are loaded on hash change. I am trying to restrict user access to certain widgets based on permissions. I am able to achieve the same using Django template where I have access to the request object and I can render or not render views based on that. I am wondering if this could somehow be done on client side in dojo. The simplest way I could think of is to make an xhr call before the hash change handler in javascript and show 403, permission denied page based on response. Is there a better way of achieving the same. Code Sample for my current hash change handler : switch (hash) { case "home": { var Starter= dojo.require("widgets.Starter"); var starter= new Starter(); domConstruct.place(starter.domNode, contentDivId); starter.placeAt(contentDivId); starter.startup(); break; } case "form-mapping": { var FormMapping = dojo.require("widgets.assignForms.FormMappingHome"); var formMapping = new FormMapping(); domConstruct.place(formMapping.domNode, contentDivId); formMapping.placeAt(contentDivId); formMapping.startup(); break; } } -
Many duplicate queries when using image tag in Wagtail
I'm using Wagtail v1.13.1 for my website project. I'm trying to optimize db queries... models.py class ProductPage(Page): ... main_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', blank=True, null=True ) class ProductIndexPage(Page): ... def get_context(self, request, *args, **kwargs): context = super(ProductsIndexPage, self).get_context(request) all_products = ProductPage.objects\ .prefetch_related('main_image__renditions')\ .live()\ .public()\ .descendant_of(self)\ .order_by('-first_published_at') paginator = Paginator(all_products, 10) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context['products'] = products return context product_index_page.html I'm outputting product card in a for loop. Each product card has this tag: {% image product.main_image fill-600x300 %} But still getting a separate call to db for each image. Models are connected in this way: ProductPage --fk--> wagtailimages.Image <--fk-- wagtailimages.Rendition The question is: What is the proper way to prefetch renditions and eliminate duplicate db queries? -
Could not resolve URL for hyperlinked relationship using view name "blog-detail"
I am trying to work with dynamic url in foreign key relationship into django rest framework url.py router = routers.DefaultRouter() router.register(r'(?P<topic_name>\w+)', views.BlogViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] models.py class Blog(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=100) class Topic(models.Model): name = models.CharField(max_length=100) views.py class BlogsViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = Serializerblog lookup_field = 'topic' def list(self, request, *args, **kwargs): response = super(BlogViewSet,self).list(request,*args,**kwargs) return Response( response.data) When I tried to call url getting following error. ImproperlyConfigured at /test/ Could not resolve URL for hyperlinked relationship using view name "blog-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://localhost:8000/test/ Django Version: 1.11 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "blog-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Exception Location: /home/TestProjeect/env/lib/python3.4/site-packages/rest_framework/relations.py in to_representation, line 386 Python Executable: /home/TestProjeect/env/bin/python Python Version: 3.4.3 Python Path: ['/home/', '/home/TestProjeect/env/lib/python3.4', '/home/TestProjeect/env/lib/python3.4/plat-x86_64-linux-gnu', '/home/TestProjeect/env/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/home/TestProjeect/env/lib/python3.4/site-packages'] Server time: Sat, 25 Nov 2017 14:57:16 +0000 -
Invalid Syntax Error in Django
I'm facing invalid syntax error in urls.py ] ^ SyntaxError: invalid syntax Code: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='home.html'), url(r'^about/$', TemplateView.as_view(template_name='about.html')), url(r'^contact/$', TemplateView.as_view(template_name='contact.html')), ] -
django upload to image model with foreign key to user
I'm using Django's Extended User Profile and instead of having many image fields I want to make a new Images class in my models that I can upload many images which automatically get assigned to the right user. Then the user can view and edit all their images. I'm basically stuck on the last part (view and edit). My app is called ve models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) ... etc class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) forms.py class ImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Images fields = ( 'image', ) 1. Edit Image(s) This setup, uploads image (in admin) but doesn't assign the user. Another problem is I can only upload/edit 1 image. views.py @login_required @transaction.atomic def edit_images(request): if request.method == 'POST': images_form = ImagesForm(request.POST, request.FILES) if images_form.is_valid(): images_form.save() return redirect('ve:index_account') else: pass else: images_form = ImagesForm(request.POST, request.FILES) return render(request, 've/cp/edit_images_account.html', { 'images_form': images_form, }) edit_images_account.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ images_form.as_p }} <button type="submit">Upload</button> </form> 2. View Image(s) views.py @login_required def index_account(request): args = {'user': request.user} return render(request, 've/cp/index_account.html', args) index_account.html <p><a href="{% url 've:edit_images' %}">Edit your images</a></p> {% if user.images.images %} … -
I want add a about page using django
the about page is like about me ,about the website... I hope the about page not static.It can be register and easy edit through django.admin. I had try to add a model named About , and the views.py is like.. that's a stupid method , and i don't know how to deal with pk when it changes.Do you have a good method? enter image description here -
django: How to get objects from a ContentType instance
I want to get a queryset of objects from a ContentType instance and then be able to filter them. From the doc, it is possible to get() an object using: ct.get_object_for_this_type(**kwargs) How can I make a similar filter() for that instance? -
Django how form class’s fields map to HTML form <input> elements
In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form elements. (A ModelForm maps a model class’s fields to HTML form elements via a Form; so how the following are translated from a model to html input. I am using a ModelForm. models.CharField(max_length=200,unique=True,null=False) models.SlugField(unique=True) models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM) models.DateTimeField(auto_now=True, auto_now_add=False) models.DecimalField() like type, name, label etc. Is there any list of mappings. -
Tic tac toe game Type error None python
Hi I am trying to create a tic tac toe game with the board values ["0", "1", "2", "3", "4", "5", "6", "7", "8"] coming from the front end and going back to the back end and then all this values being returned to the front end with a X from the user or a 0 from the random maths. The first time I input a value, it works, but the second time I input a value I get this error. if board[cell1] == char and board[cell2] == char and board[cell3] == char: TypeError: 'NoneType' object is not subscriptable The error sounds like that the board list disappears but when I print the board on my codes it shows that the board is there. def tic(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) input_str = body['value'] input = int(input_str) board = body['x'] print(board) # Here I see the board is always there if board[input] != 'x' and board[input] != 'o': board[input] = 'x' if check_match(board,'x') == True: winner = 'x' return JsonResponse({'input': input, 'board': board, 'winner': winner}) board = opponent_fun(board) if check_match(board,'o') == True: winner = 'o' return JsonResponse({'input': input, 'board': board, 'winner': winner}) else: winner = … -
How to put Array data in CharField(validators=[validate_comma_separated_integer_list])?
I chose CharField(validators=...) for alternative to CommaSeparatedInteger field to store array into the field. The Http request has selectedColorsIds body field and I want to put the data into color field of PostDetail model ... "selectedColorIds": Array [ 112, 110, ], ... models.py from django.core.validators import validate_comma_separated_integer_list class PostDetail(models.Model): ... color = models.CharField(validators=[validate_comma_separated_integer_list], max_length=30, blank=True, null=True) ... views.py :> But I'm getting this error when I try to put the array into the field. AttributeError: 'tuple' object has no attribute 'color' error color = self.request.data.get('selectedColorIds') # [112, 110] detail_instance = PostDetail.objects.get_or_create(post=post_instance) detail_instance.color = color <<- error here Why am I getting this error and how can I store array in the Django model? -
Django with apache2 ,only sometimes the server refuse the connection
I have two django projects in my server. I use virtualhost to handle that, i enabled two sites in apache2 configuration: the first is old_cheese.conf using \VirtualHost *:80: ServerName cheese ServerAdmin webmaster@localhost DocumentRoot /home/little_baker/cheese Alias /static/ /home/little_baker/cheese/static/ <Directory /home/little_baker/cheese/static> Require all granted </Directory> WSGIScriptAlias / /home/little_baker/cheese/cheese/wsgi.py <Directory /home/little_baker/cheese> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined the second is new_cheese.conf using \VirtualHost *:8000: ServerName new_cheese ServerAdmin webmaster@localhost DocumentRoot /home/little_baker/new_cheese/ Alias /static/ /home/little_baker/new_cheese/static/ WSGIScriptAlias / /home/little_baker/new_cheese/new_cheese/wsgi.py <Directory '/home/little_baker/new_cheese/static/'> Require all granted </Directory> <Directory /home/little_baker/new_cheese> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined It works most of times, in log there is no exception raised. But something unreasonable happen sometimes: If i open the old cheese page, and exception will be raised in error.log: ImportError: No module named 'new_cheese' If i open new cheese page : ImportError: No module named 'cheese' It seems like these two project try to import each other. This exception is not often raised. Most of time I can reach my page. I don't know the reason why. Is something wrong with apache2 or my project -
Poll app in django tutorial: How to show another poll after voting instead of result page
As following exactly the django tutorial in djangoproject.com, we made a poll web app. After choosing a choice and hit "vote" button, users will see the result page of that question. But i want to change a bit How do i change codes to show the next question after users choose a choice and hit vote button. And if the last question is showed, users will then see the whole results -
Using ExpressionWrapper as inside Value in a Case,When query in Python
I am trying to calculate the share of each type (BookType) of book (Book) in the list of a Publisher's books. I suppose this should do the job: Book.objects.annotate( publisher = F('Publisher__id') publisherBooksNum = Count('Publisher__id') ).values( 'publisher' ).annotate( Case( When(BookType=0, then=Value( ExpressionWrapper( Count('publisher')/F('publisherBooksNum') ), output_field=FloatField()) default=Value(0 , output_field=FloatField()) ... however I get the error: float() argument must be a string or a number, not 'ExpressionWrapper' What am I missing in the code? Is there a better Way to achieve this? -
Converting a a string to be a part of a python command in a Python script [duplicate]
This question already has an answer here: How do I retrieve a Django model class dynamically? 6 answers I have a function in a python script (views.py in Django) with a django's API command: def layer(layer_name, model_name): # here is the command in_out = model_name.objects.filter(geom__contains=location) result = inform_user(layer_name, in_out) return result When I call the layer() function as: layer(layer_variable, model_variable) python interpret the command as: 'model_name'.objects.filter(geom__contains=location) How can I send the model_name variable without python interpreting it as a string ? -
The result of table after running "python manage.py migrate" is different from what shows in sqlmigrate
I wanna create a table like this : Afterwards, I ran command--"python manage.py makemigration",it outputted a file called 0001_init.py as I expected.Then,I ran command "sqlmigrate user 0001_initial" They were all ok at that moment.However,to my puzzlement,when I ran command "python manage.py migrate",the database created the table like this: So,where are my "student_id"and"name" fields???They should had been created as the SQL statement goes that: "student_id" varchar(10) NOT NULL,"name" varchar(20)NOT NULL Is that a Django bug ?or MySQL bug? -
Beautiful soup multiple class storage
def index(request): driver = webdriver.Chrome("C:/Users/Hello/Downloads/chromedriver_win32/chromedriver.exe") browser = webdriver.Chrome("C:/Users/Hello/Downloads/chromedriver_win32/chromedriver.exe") browser.get('the website') time.sleep(10) a="None" for _ in range(1): browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) browser.execute_script("window.scrollTo(0,500);") time.sleep(5) pageSource =browser.page_source **soup = BS(pageSource, 'lxml') hello=soup.findAll("span",{"class":["SRPriceB proPriceField","SRPPS sqrPriceField","localityFirst"]}) for hellos in hello: location=hellos.get_text() landscrapes = landscrape.objects.create(location=location) landscrapes.save() return HttpResponse(location)** as with find all three values are getting found and stored as separate objects in the database, when find all is used. How do i successfully store these three values differently in the database with them corresponding to each other -
Couldn't understand this regex pattern [duplicate]
This question already has an answer here: Reference - What does this regex mean? 1 answer ^,$ When to use this symbol in regex? 1 answer So I recently started learning django and I am making the polling app from django's tutorials. I stumbled upon these two regex expressions which I cant understand-> The first code is in polls/urls.py from django.conf.urls import url from . import views urlpattersn = [ url(r'^$', views.index, name="index"), #1 ] The second code is in mysite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.url')), #2 url(r'^admin/', admin.site.urls), ] Now coming to #1 marked in the code-> I did some research and found out that url takes in 4 arguments 2 of which are optionals. So I basically I am giving a regex expression r'^$' to the url function and also passing an optional name for url and a view. I am having trouble understanding what does r'^$' actually do ? All I could find out is ^ stands for negation or first word in a line and $ stands for last word in a line. Now coming to #2 marked in the code-> I cant understand the working of … -
order django formset without form change
I have a form with only one filed that's repeated(names of family members and that field is the name, so when you want to see the family members using this form all members would be shown). Now I want my form be sorted (arbitrary order) defined by the user. For example in a family, I want to show A first, then B and then C, while the creation sequence may be C, B and A. Is there anyway to do that? I searched and realized I should add an order field to my forms and override --iter--(), is that the only way? If there is no way to do that without change in form, how can I do that? class FamilyMemeberItem(forms.Form): name= forms.CharField(label=_('name'), max_length=20) thanks -
Serving NGINX with DJANGO on Ubuntu
I am trying to Run my django(1.8) project on Nginx server since it is much faster. I am able to run by using uwsgi --ini commands to setup socket. so what i wants to do is by running NGINX alone want to run my django project, is there any way to do that ? Well the socket created by uwsgi is removing automatically when uwsgi --ini command ends. NGINX config and .ini ia as shown below : # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///var/www/html/vir/crum/crumbs.sock; } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .localhost.com; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/www/html/alteryx_vir/crum/media; } location /static { alias /var/www/html/vir/crum/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; /var/www/html/vir/crum/uwsgi_params; } } >>> uwsgi.ini file : # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /var/www/html/vir/crumb/ # Django's wsgi file module = crum.wsgi # the virtualenv (/alteryx_vir/) home = … -
Error: 502 nginx gcloud with Django app
Good day. I uploaded my Django app to Google cloud and I keep getting a 502 error nginx. My error log reads: Exec: gunicorn: not found How do I go about this. Thanks -
How to add new player safely?
Based on my question here I'm trying to use both transactions and select_for_update but using Django to make sure it works on SQLite and later on on PostgreSQL. I have setup Game, PersonGame and Person like this: class Game(models.Model): name = models.CharField(max_length=200, default=None, blank=True, null=True) number_of_players = models.IntegerField(default=2, blank=True, null=True) players = models.ManyToManyField(Person, blank=True, through='PersonGame', default=None, symmetrical=False, related_name='person_game') class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class PersonGame(BaseModel): person = models.ForeignKey(Person, on_delete=models.CASCADE) is_creator = models.BooleanField(default=False) game = models.ForeignKey(Game, on_delete=models.CASCADE) data = models.BinaryField(default=None, blank=True, null=True) So the idea is to lock Game and PersonGame while checking if there's room for another player and if so add a new player. My insertion code looks like this: with transaction.atomic(): g = Game.objects.select_for_update().get(pk=int(pk)) p, created = Personne.objects.get_or_create( user=request.user) if g.players.count() <= g.number_of_players: p_g = PersonGame.objects.create(person=p, is_creator=True, game=g) I'm calling g.players via g.players.count() so will this lock the table PersonGame? If many players want to join the game, are we sure there won't be any possibility of 2 insertions at the same time, resulting in more players than the Game should have? If it's not safe, what is the solution?