Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Django-form edit existing object
I am following the wagtail-form-example on GitHub to implement a Django Form into wagtail. I've got everything working except being able to edit an existing submission. This is the code I have followed so far https://github.com/gasman/wagtail-form-example/blob/master/flavours/models.py I have tried a couple of variants of the below code. def serve(request, id): instance = get_object_or_404(MyModel, id=id) form = MyForm(request.POST or None, instance=instance) If it helps I'm getting the following message: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Any help/examples would be appreciated :) -
How to start other Servers Automatically after Django Server starts
I am using different Servers alongside Django Server. For Example MongoDB server and Celery[command] I want to ask that how can I execute other CMD commands automatically whenever I start "** python manage.py runserver **" -
Django restrict access to user objects
I have Node and User models which both belong to an Organisation. I want to ensure that a User can only ever see Node instances belonging to their Organisation. For this I want to override the Node objects Manager with one that returns a query_set of filtered results. Based on https://docs.djangoproject.com/en/2.1/topics/db/managers/#modifying-a-manager-s-initial-queryset the relevant models.py code I have is below: class Organisation(models.Model): users = models.ManyToManyField(User, related_name='organisation') ... class UserNodeManager(models.Manager): def get_queryset(self, request): return super().get_queryset().filter(organisation=self.request.user.organisation.first()) class Node(models.Model): organisation = models.ForeignKey( Organisation, related_name='nodes', on_delete=models.CASCADE) uuid = models.UUIDField(primary_key=True, verbose_name="UUID") ... objects = UserNodeManager Unfortunately, the overridden Node.objects property does not seem to have any effect and any User can see all Nodes. Am I taking the right approach? -
How to add a comment to post? PostDetailVew, Django 2.1.5
I want add comment to post on his page ("post detail" page). I was find answer, but it create comment on other page. I want create comment on page of "post detail". urls.py url(r'^post/(?P<pk>\d+)/create/$', views.CommentCreate.as_view(), name='comment_create'), models.py class Comment(models.Model): description = RichTextUploadingField() author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) comment_date = models.DateTimeField(auto_now_add=True, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: ordering = ["-comment_date"] def __str__(self): return "{}".format(self.description) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['description'] views.py class PostDetailView(generic.DetailView): model = Post class CommentCreate(LoginRequiredMixin, CreateView): model = Comment fields = ['description'] def get_context_data(self, **kwargs): context = super(CommentCreate, self).get_context_data(**kwargs) context['post'] = get_object_or_404(Post, pk = self.kwargs['pk']) return context def form_valid(self, form): form.instance.author = self.request.user form.instance.post=get_object_or_404(Post, pk = self.kwargs['pk']) return super(CommentCreate, self).form_valid(form) def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.kwargs['pk'],}) comment_form.html ... <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Submit</button> </form> ... post_detail.html ... {% for comment in post.comment_set.all %} <p>{{ comment.author }} ({{ comment.comment_date }}) {{ comment.description|safe }}</p> {% endfor %} <hr> {% if user.is_authenticated %} <p><a href = "{% url 'comment_create' post.id %}">Add a new comment</a></p> ... I think, "comment_form" need to redirect to "post_detail", not generate new page for comment form. And сould you tell, which parameters has … -
Trying to filter django view serializer based on nested model foreignkey
I have a django app. Within it, I have 2 models. One of them is a group and the other is a member model. Then member model has a foriegnkey which is the group model. I serialized the models and now I am trying to get the api to to work as I want. I want to be able to call an api that has a group name at the end that is passed as a filter for the members to only return the members of the group name. I have 2 urls. the first one returns all the members of every group while I want the second one to return just the members of a certain group. I have tried a few different things from suggestions but none of them are working. This is the last thing I tried below. I will add my code below. Models: class Group(models.Model): name = models.CharField(max_length=42) description = models.CharField(max_length=220) user_count = models.IntegerField() status = models.CharField(max_length=12) image = models.ImageField(upload_to='group_images/') created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + ' - ' + self.created_by.username class Member(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) host = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): … -
Django: How to add data into ManyToManyField
Your help will be nice for me. Here are that codes: models.py: from django.db import models class TagModel(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class MyModel(models.Model): title = models.CharField(max_length=50) tag = models.ManyToManyField(TagModel) forms.py: from django import forms from .models import * class MyForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' views.py: from django.shortcuts import render, get_object_or_404, redirect from .models import * from .forms import * def MyWriteView(request): if request.method == "POST": mywriteform = MyForm(request.POST) if mywriteform.is_valid(): confirmform = mywriteform.save(commit=False) confirmform.save() return redirect('MyDetail', pk=confirmform.pk) else: mywriteform = MyForm() return render(request, 'form.html', {'mywriteform': mywriteform}) form.html(1st trial): <form method="post"> {% csrf_token %} {{ mywriteform }} <button type="submit">Save</button> </form> form.html(2nd trial): <form method="post"> {% csrf_token %} {{ mywriteform.title }} <select name="tags" required="" id="id_tags" multiple=""> {% for taglist in mywriteform.tags %} <option value="{{taglist.id}}">{{taglist}}</option> {% endfor %} </select> <button type="submit">Save</button> </form> I am trying to add tags on my post. I made a simple manytomany tagging blog but it does not work. I submitted a post by clicking the save button, and the title was saved, but the tag was not. In the admin, it worked well. Thank you in advance. -
Get Incremented count after forloop depending on condition in template django
I have a block of code in my template wich count the number of programmes associated with department, Am stuck on how to get forloop counter after counting those programmes I've tried to use forloop.counter but it print those iterations <td><small> {% for my_programme_by_department in programme_by_department %} {% if my_programme_by_department.department_id == my_department.id %} {{ forloop.counter }} {% else %} {% endif %} {% endfor %} {# get my count here {{ my_count }}#} </small> </td> -
JWT authentication between Django and Vue.js
I wish to create a public area on a website containing standard Django and templates. When a user logs in to the members area, they are logged in to a SPA (using Vue.js) and Django Rest Framework. I will be using JWT's to handle authentication between the SPA and backend once the user has logged in to the members area. This is the user journey: User browses around the public areas of the site (served by normal Django and templates). User decides to signup / login to the members area. Django Rest Framework generates a JWT for the user and returns the token along with the index.html of the SPA The user continues to use the SPA with the JWT Is the above possible and how would it be done? More specifically, the issue is that the user is not logging in to the SPA and requesting a JWT. They are logging in to regular Django and getting returned a JWT along with the SPA. That JWT would then be used from that point onwards. -
Django Channels Postgres InterfaceError: connection already closed
I can't seem to wrap my head around the issue here. I'm writing tests for my Channel Consumers following the description in the docs. I'd normally use the Django default unittest but since Channels requires using pytest, I'm using it but will still like the maintain the class structure of writing tests. I had issues with writing the setup method similar to unittest which I would use to initialize the test attributes. I tried method fixtures, class fixtures using autouse=true, but none of them seemed to work as I couldn't access the instance attributes in the test methods. Finally I just decided to write the set_up instance method and manually call it for each class. This is what I have so far: @pytest.mark.django_db @pytest.mark.asyncio class TestChatConsumer(object): @database_sync_to_async def set_up(self): self.user = UserFactory() self.api_client = APIClientFactory() self.token = TokenFactory(user=self.user) self.credentials = { 'AUTHORIZATION': self.token.key, ... } self.credentials_params = '&'.join(['{}={}'.format(k, v) for k, v in self.credentials.items()]) self.authless_endpoint = '/api/v1/ws/' self.endpoint = self.authless_endpoint + '?' + self.credentials_params async def test_connect_without_credentials(self): await self.set_up() communicator = WebsocketCommunicator(application, self.authless_endpoint) connected, subprotocol = await communicator.connect() assert not connected async def test_connect_with_credentials(self): await self.set_up() communicator = WebsocketCommunicator(application, self.endpoint) connected, subprotocol = await communicator.connect() assert connected The issue is … -
What filepath should I use for a cron job in django?
I'm setting up my first cron job in Django, following this tutorial - https://medium.com/@bencleary/django-scheduled-tasks-queues-part-1-62d6b6dc24f8 Running python manage.py process_emails manually works and the function runs. I'm stuck at the part where I'm actually editing the crontab file: */1 * * * * /var/path/to/venv/bin/python /var/path/to/my/app/manage.py process_emails 1. How can I find the correct paths in the code above? The first path appears to have something to do with the virtual environment? The second path is to the actual manage.py file, but since this will be deployed to my server on Heroku, I'm pretty sure I'm not supposed to put the path on my local machine (user/workspace/myappname/etc...). Would I just put myappname/manage.py? I'll be totally honest here: I did setup a virtual environment for this app, and it deploys and runs without issue. However, I can't fully remember how I did it, and when I look in my project directory, I don't see any reference to a virtual environment or a venv folder, etc. That may or may not be relevant here, but I thought I'd mention it just in case. 2. Where should the crontab file be? The tutorial says to just enter crontab -e and edit the file. I did this, … -
django unable to create project using command line
I went through all the solutions but none of that reolves my issue. So while trying to create project using the startproject command on command line. I am getting an error. Here is the series of steps that I have tried 1. Installed Python 2. Installed Django 3. django-admin startproject mysite which gives me an error CommandError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\Himanshu Poddar\\Desktop\\mysite' However django-admin is working fine tho, which gives me a list of django commands. My Django version is 2.1.2 and I am using Win10. Thanks. Any help would be highly appreciated. (I have tried all the solutions from the similar question suggestion and none of that helps me.) -
Python caching previous object properties across new instances
I've run into an odd issue. It started with trying to create objects in django in a loop. I have an override on the model save() that does something like self.history.append(new_status) Now, I thought self meant the current instance being evaluated. But, when run in a loop (on a single python process) self.history caches from the last time it was evaluated. So, in the example: for i in range(3): job = Job(...properties, exluding history, as that's done in the save() method) job.save() The jobs stored in the database look like this: job1 - id: 1, history: ['pending'] job2 - id: 2, history: ['pending', 'pending'] job3 - id: 3, history: ['pending', 'pending', 'pending'] ... so on Now, if the django server is not restarted, and this controller is invoked again, then the jobs will be created, starting with history of the last object it created (so it would start with 4 pendings, then the next 5 and so on). Essentially, Previous X + current N records I have been able to largely replicate this in simple Python: class Base(object): id = None name = None history = list() def __init__(self, id=None, name=None): self.id = id self.name = name def save(self, **kwargs): … -
Why does Django error messages have empty class extensions?
I'm trying to learn how to use Django, following this tutorial. However, I keep running into an OperationalError exception every time I try to use the admin site to edit the database. Traceback: File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\options.py" in change_view 1639. return self.changeform_view(request, object_id, form_url, extra_context) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1525. return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\options.py" in _changeform_view 1571. self.log_change(request, new_object, change_message) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\options.py" in log_change 826. change_message=message, File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\models.py" in log_action 35. change_message=change_message, File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Zhang\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\models\query.py" in create … -
ImportError in django1.1.4 but I can execute this file separately
I'm running a python2.5, python 1.1.4 program,When I tried to import a file, I got a No module named pie Exception,But I can run this file alone,Because this program is so old, I don't know what to do with it。 In order to avoid the path problem, I have put the code that needs import into the view. But this part of the code depends cairo and pycha.pie,If I don't execute the django program and just execute this file on my own, that's fine, so I can determine the reason for django. import cairo import pycha.pie def pieChart(lines,out_file,title=u"images"): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 220) datas = [(line[0], [[0, line[1]]]) for line in lines] options = { 'axis': { 'labelFont': 'simsun' , 'tickFont':'simsun', 'tickFontSize':12.0, 'line': { 'ticks': [dict(v=i, label=d[0]) for i, d in enumerate(lines)], }, }, 'colorScheme': { 'name':'fixed' , 'args': { 'colors': [line[2] for line in lines], }, }, 'title':title, 'labelFont': 'simsun' , 'titleFont': 'simsun' , 'background': { 'hide': True, }, 'pieRadius':0.3, 'padding': { 'left': 3, 'right': 3, 'top': 3, 'bottom': 3, }, 'legend': { 'hide': True, }, } chart = pycha.pie.PieChart(surface, options) chart.addDataset(datas) chart.render() surface.write_to_png(out_file) if __name__ == "__main__": lines=[ ['a',1,'#ff0000'],[u'hello',2,'#00ff00']] pieChart(lines,'demo.png') print "file done!" the django error ImportError at … -
Django - How do I use UpdateView correctly with my form?
My current form submits correctly but makes additional listings in the django admin after each form submission. I made an UpdateView class thinking this would solve the issue and no luck. I think I'm missing something since I'm new to Django. I just need this form to update the values in the django admin based on the current user and not repeat creating additional listings. What’s the best way to execute this with my current code? Any help i gladly appreciated, Cheers user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.conf import settings from django.views.generic.edit import FormView from django.views.generic.edit import … -
S WSGIPythonPath takes one argument, Python module search path
I'm sorry if ask very dumb question. But I had no idea what i'm doing, I'm just following the tutorial Link here: https://www.youtube.com/watch?v=F6-yJpPEpoE Now I'm just trying to start up Apache server to run my Django code in productions I encounter this error: C:\WINDOWS\system32>C:/Frontier_Website/Apache24/bin/httpd.exe -k startserver AH00526: Syntax error on line 542 of C:/Frontier_Website/Apache24/conf/httpd.conf: WSGIPythonPath takes one argument, Python module search path. I'm assuming the error is unable to find my python path, something related to python, which apologies I'm not sure what is looking for. This are the codes in httpd setting: #python and mod_wsgi setting LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:\Frontier_Website\FrounterWeb postgreDB-the secnond\FrounterWeb\wsgi.py" WSGIPythonHome C:/users/user/appdata/local/programs/python/python37 WSGIPythonPath C:\Frontier_Website\FrounterWeb postgreDB-the secnond\zigview <Directory C:\Frontier_Website\FrounterWeb postgreDB-the secnond\zigview\static> Require all granted </Directory> <Directory C:\Frontier_Website\FrounterWeb postgreDB-the secnond\zigview> <Files wsgi.py> Require all granted </Files> </Directory> In advance thank you, so much on the help -
Django 2 - ORM - Annotate Substraction of two sums order is not mathematically respected
At the moment we are trying to order a list of videos based on their difference of up and down votes (=> points). The logic is simple: Take a video, sum all Upvotes by each user and sum all Downvotes by each user. Substract the downvote sum from the upvote sum. Call the result points. Order the list by points descending. An expected result would be: Video A : 5 Upvotes : 4 Downvotes : 1 Point Video B : 3 Upvotes : 3 Downvotes : 0 Points Video C : 0 Upvotes : 0 Downvotes : 0 Points Video D: 0 Upvotes : 1 Downvote : -1 Point We have done this with the following Django 2 model queryset: from django.db.models import F, Sum ... q = Video.objects.filter(createdAt__year=year, is_active=True, is_public=True) videos = q.annotate(points=Sum("votes__up") - Sum("votes__down")).order_by("-points")[:15] Unfortunately though, the "ordered" list looks as followed: As we can see from the returned ordered list, it does not respect that -1 is less than 0 and should come after any result that has 0 points. Is there something wrong with our querymodel? -
Dango app not deployed correctly on Heroku: Server Error 500 when DEBUG=False, not loading index view correctly when DEBUG=True
Locally, my Django app works perfectly. I am able to deploy the app on Heroku, but in setting.py when DEBUG=False then GET pypoll.herokuapp.com/polls results in a "Server Error (500)." Heroku logs also just show status = 500. 2019-01-14T20:23:33.934156+00:00 heroku[web.1]: State changed from up to starting 2019-01-14T20:23:35.192270+00:00 heroku[web.1]: Process exited with status 0 2019-01-14T20:23:40.447711+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2019-01-14T20:23:44.348545+00:00 heroku[web.1]: State changed from starting to up 2019-01-14T20:23:44.216211+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-01-14T20:23:44.221560+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Listening at: http://0.0.0.0:23263 (4) 2019-01-14T20:23:44.221733+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Using worker: sync 2019-01-14T20:23:44.232516+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [10] [INFO] Booting worker with pid: 10 2019-01-14T20:23:44.301182+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [11] [INFO] Booting worker with pid: 11 2019-01-14T20:23:46.601813+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. 2019-01-14T20:23:46.601856+00:00 app[web.1]: """) 2019-01-14T20:23:46.729941+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. 2019-01-14T20:23:46.729944+00:00 app[web.1]: """) 2019-01-14T20:31:23.859217+00:00 heroku[router]: at=info method=GET path="/" host=pypoll.herokuapp.com request_id=0c2da020-6e94-4feb-ac0a-23ed191041de … -
django - how can I get a list of all foreignkeys related to a model?
models.py class DataSource(VoteModel, models.Model): dataset_request = models.ForeignKey( 'DatasetRequest', on_delete=models.CASCADE, blank=True, null=True) file = models.FileField(upload_to='datasource_files/') file_size = models.BigIntegerField(blank=True, null=True) title = models.CharField(max_length=255, default="Untitled") description = models.TextField(blank=True, null=True) slug = models.SlugField(blank=True, null=True) is_public = models.BooleanField(default=True) creator = models.ForeignKey(User, on_delete=models.CASCADE) is_csv_or_tsv = models.BooleanField(null=True) thumbnail = models.ImageField( upload_to="datasource_thumbnails/", blank=True, null=True) date_uploaded = models.DateTimeField( auto_now_add=True, blank=True, null=True) comments = GenericRelation(Comment) class DatasetRequest(VoteModel, models.Model): reward = models.DecimalField( decimal_places=2, max_digits=10) # if 0, 1 medal title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) slug = models.SlugField(blank=True, null=True) is_public = models.BooleanField(default=True) creator = models.ForeignKey(User, on_delete=models.CASCADE) thumbnail = models.ImageField( upload_to="datasetrequest_thumbnails/", blank=True, null=True) best_dataset_entry = models.ForeignKey( DatasetEntry, on_delete=models.CASCADE, blank=True, null=True) date_uploaded = models.DateTimeField( auto_now_add=True, blank=True, null=True) is_paid = models.BooleanField(default=False) comments = GenericRelation(Comment) qa_testers = models.ManyToManyField(User, related_name='qas') With the following setup, how can I get all DatasetRequests for a given DataSource? dataset_request (DatasetRequest) is a foreignkey in DataSource. There is no many-to-many in DatasetRequest, though there are data sources for every DatasetRequest. Do I need a many-to-many for either? -
How to emit safe URL in Django?
Consider the following code in Django template: <a href='{{target}}'>Link text</a> or <a href="{{target}}">Link text</a> If the context item target contains quote or double-quote characters (' or "), then I expect the HTML page to break at a minimum. Or someone can insert JavaScript after closing the quote/double-quote, so to run arbitrary code on clients' machines. How to escape the url in such cases? I've tried <a href='{{target|urlencode}}'>Link text</a> But the problem with this approach is that the URL stops leading to the original site like http://www.example.com , but starts leading to my site with http://www.example.com treated as the path after the domain name, i.e. it becomes http://127.0.0.1:8000/http%3A//www.example.com. So could you tell me the correct approach to make URLs safe? -
Django user equals user statement
i want to implement displays the user a message if he trys to vote on his own category_request but somehow its now working. Do i access the objects the right way here? views.py def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) try: if request.method == 'GET': if CategoryRequests_Vote.voter == CategoryRequests.author: #<< this statement messages.error(request, 'You are trying to vote a request you created by your own (Transmision ignored)') return redirect('category_request_detail', pk=category_request.pk) elif CategoryRequests_Vote.objects.filter(voter=request.user, voted=category_request).exists(): messages.error(request, 'You already Voted this request. Double votes are not allowed (Transmision ignored)') return redirect('category_request_detail', pk=category_request.pk) else: category_request.up_vote = F('up_vote') + 1 category_request.save() CategoryRequests_Vote.objects.create(voter=request.user, voted=category_request) messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) except: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) ... class CategoryRequests_Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) voted = models.ForeignKey(CategoryRequests, on_delete=models.CASCADE) published_date = models.DateField(auto_now_add=True, null=True) class Meta: unique_together = ('voter', 'voted') def publish(self): self.published_date = timezone.now() self.save() -
Django. Models. Create same class another instance inside it's method
I have some Djanog application to work with text and save info in database. And there is some cutom method like this: ` class TextClass(models.Model): property1 = models.CharField(max_length=255, default='__') def meth1(self, text_lines): if condition1: self.property1 = some_info self.save() Is it possible in case of another condition inside meth1 to create one more instance of the same class to fill it's properties with info from text block? -
Django set model fields after create
I have a model Movie and a Model DefaultMoviePriceFor which saves the default prices for a specific genre: class Movie(models.Model): name = models.TextField('name', null=True) genre = models.TextField('genre', null=True) price = models.IntegerField('price', default=0) class DefaultMoviePriceForGenre(models.Model): genre = models.TextField('genre', null=True) price = models.IntegerField('price', default=0) Now I would like to fill up Movie.price with the default price of the Movie.genre everytime an object of Movie is instantiated. Is there any good way to do so? I have SQL triggers in my head, they could do that, don't they? How is it done in django? -
Django accepting QueryParams (Must be callable error)
I'd like http://example.com/view_item/4 to handle a view for a selected object by passing the object ID, but after trying every combination I've found online of what will work, I'm still getting the following error: TypeError: view must be a callable or a list/tuple in the case of include(). This is my path: url(r'^view_item/(?P<query>\w+)$','view_item')] I've verified the regex, I've tried without the regex. -
Connection busy with results for another command, while MARS Connection is being used
While trying to dumpdata in Django with the following command: python manage.py dumpdata --all --output /data/django_dump.json --verbosity 3 I get the following error: CommandError: Unable to serialize database: ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]Connection is busy with results for another command (0) (SQLExecDirectW)') Exception ignored in: <generator object _cursor_iter at 0x7f1c4112b0c0> Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/sql_server/pyodbc/compiler.py", line 133, in _cursor_iter cursor.close() File "/opt/conda/lib/python3.7/site-packages/sql_server/pyodbc/base.py", line 500, in close self.cursor.close() pyodbc.ProgrammingError: The cursor's connection has been closed. Following the advice of this post, here's my database configuration: DATABASES = { 'default': { 'NAME': ..., 'ENGINE': 'sql_server.pyodbc', 'HOST': ..., 'USER': ..., 'PASSWORD': ..., 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'MARS_Connection': True, } } } Using the MARS connection doesn't seem to help at all. Is my configuration wrong? Is there some other reason this might not work? Python>=3.6, Django>=2, using MS SQL Server (not sure which version, nothing too old) and django-pyodbc-azure from conda-forge.