Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PostgreSQL query that select objects where JsonField dicts have all a certain key set
My model: from django.contrib.postgres.fields import JSONField class Image(models.Model): tags = JSONField(null=False, blank=True, default={}) tags field value can be empty, or something like: [ {"tag": "xxx", "invalid": "true"}, {"tag": "yyy"}, {"tag": "zzz"} ] I need to make a query that gives me Image objects where all objects in tags column have the "invalid" key set "true". Thank you for you help -
Query for manytomany multiple tables for getting data of multiple models in django
I'm trying to solve following case: many Student has many subjects but only some subjects are marked as his current subjects, one classroom has multiple subjects, student may carry subjects of other classroom which can be checked from his current classroom. I want to get all those subjects which student currently has with all classroom those subject has with the status of classroom, either current or not. class Student(models.model): id = models.OnetoOneField(User) class Subject(models.Model): Subject_Master_Id=models.AutoField(primary_key=True) Subject_Name=models.CharField(max_length=100,blank=False,unique=True) user = models.ManyToManyField(Student,through = 'Student_Subject') class Classroom(models.Model): Class_Master_Id=models.AutoField(primary_key=True) Classroom_Student = models.ManyToManyField(Student,through='Classroom_Student',related_name='classroom_student') Classroom_Subject = models.ManyToManyField(Subject,through='Classroom_Subject',related_name='classroom_subject') class Student_Subject(models.Model): Student_Subject_Id = models.AutoField(primary_key=True) subject= models.ForeignKey(Subject,on_delete = models.CASCADE, related_name='student_subject') user=models.ForeignKey(Student,on_delete = models.CASCADE, related_name='student_subject') is_current = models.BooleanField() class Classroom_Student(models.Model): Classroom_Student_Id=models.AutoField(primary_key=True) Classroom_Id=models.ForeignKey(Classroom,on_delete=CASCADE) Student_Id=models.ForeignKey(Student,on_delete=CASCADE, related_name= 'student') is_current = models.BooleanField() class Classroom_Subject(models.Model): Classroom_Subject_Id=models.AutoField(primary_key=True) Classroom_Id=models.ForeignKey(Classroom,on_delete=CASCADE) Subject_Id=models.ForeignKey(Subject,on_delete=CASCADE, related_name='subject') -
cant spot the syntax error in django views
hi guys i am having trouble in finding the syntax error in my Django views.I am trying to create the view of creating a post by a user with the help of inline formset as code given below.But the view is throwing error in case of following below: iam getting the error indicator right below the (:) if request.method == 'POST': SyntaxError: invalid syntax I checked the indentations but can't spot the error spot.can you find it out if you are reading it ? #views.py from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from . import forms from .models import * @login_required def post(request): form = forms.PostForm() formset =forms.AnswerInlineFormSet(queryset=models.Answer.objects.none() if request.method == 'POST': form = forms.PostForm(request.POST) formset=forms.ImageInlineFormSet(request.POST,request. FILES,queryset=Images.objects.none()) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.user = request.user post.save() images = formset.save(commit=False) for image in images: image.post = post image.save() messages.success(request,'Post added.') return HttpResponseRedirect('/feeds') return render(request,'usersubmit/post_create.html',{'form'= form,'formset' = formset,}) here is the form for the view: #forms.py from django import forms from .models import Post,Images class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'synopsis','category','tags' ) class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('image','body', ) ImageFormset= forms.modelformset_factory( models.Images, form=ImageForm, … -
django-tables2 sorting non-queryset data
Hi I have a table thus: class MyTable(tables.Table): brand = tables.Column(verbose_name='Brand') market = tables.Column(verbose_name='Market') date = tables.DateColumn(format='d/m/Y') value = tables.Column(verbose_name='Value') I'm populating the table with a list of dicts and then I'm configuring it and rendering it in my view in the usual django-tables2 way: data = [ {'brand': 'Nike', 'market': 'UK', 'date': <datetime obj>, 'value': 100}, {'brand': 'Django', 'market': 'FR', 'date': <datetime obj>, 'value': 100}, ] table = MyTable(data) RequestConfig(request, paginate=False).configure(table) context = {'table': table} return render(request, 'my_tmp.html', context) This all renders the table nicely with the correct data in it. However, I can sort by the date column and the value column, but not by the brand and market. So it seems non-string values can be sorted but strings can't. I've been trying to figure out how to do this sorting, is it possible with non-queryset data? I can't populate the table with a queryset, as I'm using custom methods to generate the value column data. Any help appreciated! I guess I need to specify the order_by parameter in my tables.Column but haven't found the correct setting yet. -
Unable to test if method was called with Mock by Celery
I am having an issue while testing if Celery task was executed successfully. My task calls another reusable function that sends request to another server: @shared_task def my_task(): send_request_to_server() I am using mock to check if function send_request_to_server() was called. Task is triggered via Django Admin changelist action, so the final test looks like this: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) @mock.patch(‘helpers.send_request_to_server’) def my_test(self, mocked_function): change_url = reverse('admin:app_model_changelist') response = self.client.post(change_url, {'action': ‘mark’, '_selected_action': [1]}, follow=True) self.assertTrue(mocked_function.called) I am 100% percent sure, that this test at some point calls send_request_to_server() function, since this function also creates a file and it is quite easy to notice that. But mocked_function attribute “called” still holds value of False. Also I am quite certain, that the mock decorator path is correct, since simplified test passes without any problems: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) @mock.patch(‘helpers.send_request_to_server’) def my_test(self, mocked_function): send_request_to_server() self.assertTrue(mocked_function.called) Even if the function is called, what could cause the False value of mocked_function.called? Maybe it has something to do with multiple threads? Thank you! -
django integrityerror: duplicate key value violates unique constraint "django_content_type_pkey"
I've been working on this project on my desktop, upon updating my local repo with the github repo, I tried to migrate the changes I had made on my desktop to the database (added fields). I'm not getting this error and im not sure why. Detail: key(id)=1 already exists. I've tried looking up solutions but could not find any accurate ones. Does anyone know how to solve this? "django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey" DETAIL: Key (id)=(1) already exists." -
Django html interacts with views
I have a html that contains some forms and buttons. One button corresponds to a file that I have uploaded. I want to achieve when I click on a button, my views will act on the corresponding file, and shows the results in another html like picture below. How can I give each button specific parameters from my models? and how to get the parameter in my views. I tried this code, but failed to get it. is this right? <button type="submit" class="btn btn-info btn-xs" name={{item.description}}></button> -
Django set-up in "Python and Django Full Stack Web Developer Bootcamp"
In the Course "Python and Django Full Stack Web Developer Bootcamp" lecture 115 Django set-up, I progressed till "activate myDjangoEnv". I've already created myDjangoEnv and try now to activate it. But, I can't. in the lecture after activation it reads "(MyDjangoEnv) C:\Users\Marcial>" but in my case, after running "activate myDjangoEnv", I get "PS C:\Users\myusername>" How can I activate myDjangoEnv? -
Writing file to a dynamic path on the server in Django
I've been looking at a lot of similar questions, both on Google and StackOverflow, but there doesn't seem to be a satisfactory solution that works for me. My situation is this - I am using jQuery File Upload following the steps here. The location where I want to save my files is dynamic and it depends on the username and the session_key. This is the function to write the file - def handle_uploaded_file(file, session_key, username): folder_path = os.path.dirname(os.path.realpath(__file__)) + '\\Source\\' + username + '\\session_id_' + session_key if not os.path.exists(folder_path): os.makedirs(folder_path) save_path = folder_path + '\\Source Files' with open(save_path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) I tried to upload a file named "normal.csv", but instead I got a file named "Source Files" without an extension inside the directory. When I changed the path inside the open() function to with open(save_path+file.name, 'wb+') as destination I got a file named 'Source Filesnormal.csv'. I then tried to change the save_path to folder_path + '\\Source Files\\', and passed in save_path+file.name to open(), but then it said No such file or directory. I am very confused as to how to get into that folder location and write the file. I can't use MEDIA_URL here … -
Django admin with multiple heritage
I have the following class class master(models.Model): topic = models.ManyToManyField('Topic') class child1(master): question = models.CharField(max_length=100, null=False) class child2(master): answer_display = models.CharField(max_length=300, null=False) In the django admin, I wish add an object child1 and at the same time an object child2 that have the same ID given by the parrent model. How I'm supposed to do that ? -
How to run multiple Django App Gunicorn systemd?
I have two django projects running on different ports in same ec2 instance, One I have configured with gunicorn system as follows by creating gunicorn.service file at /etc/systemd/system/ which is working awesome if I run the command systemctl start gunicorn. Now I want to run another proect, how can I configure it, currently I am running that using gunicorn command /usr/local/bin/gunicorn --graceful-timeout 30 --bind 0.0.0.0:8690 projectFile.wsgi:application --daemon, Can I add same in gunicorn.service itself. How do I configure multiple projects in gunicorn systemd? gunicron.service file - [Unit] Description=gunicorn daemon After=network.target [Service] PIDFile=/tmp/gunicorn.pid LogFile=/tmp/lgunicorn.log User=root Group=www-data WorkingDirectory=/home/ubuntu/website/UniservedWebsite ExecStart = /usr/local/bin/gunicorn --workers 2 --graceful-timeout 30 --bind 0.0.0.0:8134 UniservedWebsite.wsgi:application [Install] WantedBy=multi-user.target -
Changed the name of django app.Now python manage.py shell cant see the models.
This is what I did to change the name of my django app which has classes under models I deleted the database and the migration folder. Then I ran the migration again and the tables were created ( mariadb). All works fine. Except when I run python manage.py shell which starts the interpretor alright. But when I try to from main.models import Teacher I get a LookupError: No installed app with label 'models' . Teacher being the class under models.py of the app main. Main is what I had renamed my earlier app 'foo' to -
Guest Checkout in django
I am currently developing guest checkout in django as I don't want to use django-oscar which gives guest checkout functionality. I searched and got to the conclusion that it can be done through session and got to know that when user logs in the system at that time row will be created in django_session table. So I will have to create manual entry in django_session for my guest checkout. Can anyone please throw some light on how and which will be the best way to do it? -
Static files not working in Iframe in production mode django
In production mode my django project1 working fine. settings.py DEBUG = False STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR,'mysite' ,'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite', "static"), '/var/www/static/', ] I ran this project in localhost:8000 And my different project(project2) which is running into localhost:8001 I want to show project1's home page in project2 using iframe or embed but project1's static files not working here. -
Django/coreapi how to use a local swagger file?
Probably a very simple matter, but I have not been able to find an answer... The short story is this: I have to develop an API client on top of a Django site we have. I think Coreapi would be the way to go. However, the documentation for it says that you should initialize the client as: schema = client.get('https://api.example.org/') Which implies that every time before I do an API call I need to download the full swagger file from the remote site? Given that a) we are going to be doing MANY calls, and b) the other site (which runs the server API to which my app is the client) will not be changing that API any time soon (and, if it does, we will need to re-do most of our code anyway), can't I just download the swagger locally and then initialize using the local copy? -
django connectivity with redshift database
I am working on an django project.trying to connect my django with redshift database using postgresql_psycopg2 backend of django.i am not able to migrate my databse.can any one suggest me with relative solutions.will be very helpful. -
how do i use django CMS placeholder in my existing django project?
I'm new to django CMS and i am abit confused by how it really works.my confusion comes from three areas which i quite don't understand. Would someone be kind enough to explain to me: why does django CMS not take the admin url and ends up working on `localhost:8000(which causes my projects home page not to be available) How do i create a new placeholder to manage my content on existing django websites? I have tried reading the docs but the dont really explain how to create new placeholders in the admin. Any help would be greatly appreciated. -
Wagtail customize file upload
I'm new in wagtail, I'm trying to customize the file upload event in admin side. How I can validate the file name (for image, document, or video) before to upload. -
Django REST ImageField Serializer close file
I want to do bulk images POST to the server. And the same image will be upload to multiple records in Django 1.11 and Django REST 3.6.1 for image in images: data = { 'type': image_type, 'attribute': { 'dealer_id': int(dealer_id), }, 'defaults': { 'created_user': user, 'updated_user': user, 'image': image, } } for shop_id in shops: DisplayImage.objects.update_or_create(**data) I suspect the problem comes from Django REST Serializer mechanics. I think it release the image from memory when the record and disk were save(). Then the next iteration round of shop will not be able to get file. Therefore Django raises the error. -
How to resize the text fields in django using widget tweak
I am new to Django. I have created a login page.click for the screen shot I want to decrease the size of the both fields. I want to bring the login interface to center too. Is there any way to do it. Right now I am using the form-control and redner_field from widget tweak and 1.9 version of django. the code is: {% extends 'website-base.html' %} {% load widget_tweaks %} {% block main %} <form method="post"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %} code for the form.py from django import forms class UserDetails(forms.Form): def __init__(self, *args, **kwargs): super(UserDetails, self).__init__(*args, **kwargs) self.fields["email"] = forms.EmailField() self.fields["password"] = forms.CharField() -
Python DJANGO Error IndexError at / list index out of range
I am new to python. Trying to create a simple application using django. I am facing the index out of range exception with this line "ndim = mobjs[0].ndim". Any help would be highly appreciated Error \File "/home/anthra/server_movierecsys/books_recsys_app/views.py", line 66, in home ndim = mobjs[0].ndim views.py def home(request): context={} if request.method == 'POST': post_data = request.POST data = {} data = post_data.get('data', None) if data: return redirect('%s?%s' % (reverse('books_recsys_app.views.home'), urllib.urlencode({'q': data}))) elif request.method == 'GET': get_data = request.GET data = get_data.get('q',None) titles = cache.get('titles') if titles==None: print ('load data...') texts = [] mobjs = MovieData.objects.all() ndim = mobjs[0].ndim matr = np.empty([1,ndim]) else: print ('loaded',str(len(titles))) -
Django createsuperuser say key already exist
I am confusing about how can I use 'python manage.py createsuperuser' command from the terminal. When I run this command, it say django.db.utils.IntegrityError: duplicate key value violates unique constraint "authtoken_token_user_id_key" DETAIL: Key (user_id)=(abcdef@gmail.com) already exists. But, before use this command, I dropped database and re-create after deleting 000* files in migrations directory. I checked that there is no line in authtoken_token and user table. I have no idea what is wrong. Please give me some advice please. (remoshin) ubuntu@ip-172-31-33-33:~/remoshin/remoshin$ python3 manage.py makemigrations (remoshin) ubuntu@ip-172-31-33-33:~/remoshin/remoshin$ python3 manage.py migrate (remoshin) ubuntu@ip-172-31-33-33:~/remoshin/remoshin$ python3 manage.py dbshell psql (9.5.8) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. remoshin_maindb=# \dt List of relations Schema | Name | Type | Owner --------+-----------------------------------------------+-------+--------- public | auth_group | table | remosys public | auth_group_permissions | table | remosys public | auth_permission | table | remosys public | authtoken_token | table | remosys public | django_admin_log | table | remosys public | django_content_type | table | remosys public | django_migrations | table | remosys public | django_session | table | remosys public | remosys_chat_detail_tbl | table | remosys public | remosys_chat_tbl | table | remosys public | remosys_clinic_ipaddress_tbl | table | remosys public | … -
How to separate a database from a Django web-app when going live?
I need this in order to host a database (MySQL) and an application server on the different servers. Is it even possible? If yes, is that a good idea at all? -
Django DRF Haystack: Append several search querysets
Im trying to create a search view for searching users on a single input field using Haystack. I want to be able to search based on birthdate (as a string), a numeric code and the name and last name of the users. This is my view: class CriminalSearchViewSet(HaystackViewSet, ReadOnlyModelViewSet): """.""" queryset = MyUser.objects.all() index_models = [MyUser] serializer_class = MyUserSearchSerializer pagination_class = StandardResultsSetPagination def get_serializer_context(self): return {"with_base_64": False} My index: class MyUserIndex(indexes.SearchIndex, indexes.Indexable): """.""" text = indexes.EdgeNgramField( document=True, use_template=True, template_name="indexes/myuser_text.txt") And the template: {{ object.first_name }} {{ object.second_name }} {{ object.first_last_name }} {{ object.second_last_name }} {{ object.format_birthdate }} {{ object.crime_area }} {{ object.phones }} {% for a in object.personaldocument_set.all %} {{ a.number }} The problem is that Im not able to search by the date or the numeric code. Haystack just does not provide results. I am considering searching on top of the classic text search, an addistional date and code search and the join the results of the three queries. Im not sure how to do that and if that is the way to go about my problem. Can anyone help me telling me how can I be able to search both numeric and dates (as strings) searches on a … -
How can i use both easy thumbnails and sorl-thumbnail in the same django projects yet they have the same template tags?
I have this project where im using sorl-thumbnail to resize and crop my images on the template, in the same project i happen to use django CMS to manage my content, the problem is Django CMS needs 'easy-thumbnails for its filer app both apps use almost similar tags and i end up with this template syntax error placeholder', expected 'endblock'. Did you forget to register or load this tag? when i try to use Django CMS {% placeholder 'mycontent' %} on my template.