Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: jQuery autocomplete with multiple queryset
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/ Now i was able to send in a queryset the objects of two model: def multi_autocomplete(request): if request.is_ajax(): # In base a cosa sta scrivendo l'utente mostro un set di aziende. query = request.GET.get("term", "") companies = Company.objects.filter(name__icontains=query) treatments = Treatment.objects.filter(name__icontains=query) results = [] for company in companies: place_json = company.name results.append(place_json) for treatment in treatments: place_json = treatment.name results.append(place_json) data = json.dumps(results) return HttpResponse(data, "application/json") As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided? -
Unable to reference HTML values in Javascript
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below: <head> {% for candidate in candidates %} <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}"> <h3>{{forloop.counter}}</h3> {% endfor %} </head> I then try to access the data here: <script type="text/javascript"> var metatags = document.getElementsByTagName('meta'); for (var i = 0; i < metatags.length; i++) { console.log(metatags[i].data-id) } </script> However, an issue is thrown trying to access the data: Uncaught ReferenceError: id is not defined In reference to the line console.log(metatags[i].data-id) Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript? Thanks in advance. -
How create REVERT opportunity in django-reversion app?
I have task to rewrite correct Function Based View to Class Based View. Below you can see my code. My question is whats wrong with my Class Based View? It raise error. Where is my mistake? FBV: @reversion.create_revision() def article_revert(request, pk, article_reversion_id): article = get_object_or_404(Article, pk=pk) revision = get_object_or_404(Version.objects.get_for_object(article), pk=article_reversion_id).revision reversion.set_user(request.user) reversion.set_comment("REVERT to version: {}".format(revision.id)) revision.revert() return redirect('project:article_list') CBV: class ArticleRevert(RevisionMixin, View): model = Article def get(self, request, *args, **kwargs): article = get_object_or_404(Article, pk=pk) revision = get_object_or_404(Version.objects.get_for_object(article), pk=article_reversion_id).revision reversion.set_comment("REVERT to version: {}".format(revision.id)) revision.revert() return redirect('project:article_list') When I use CBV it raise next error: Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/views.py", line 43, in do_revision_view return func(request, *args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Applications/Projects/web/project/article/views.py", line 166, in get reversion.set_comment("REVERT to version: {}".format(revision.id)) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 122, in set_comment _update_frame(comment=comment) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 87, in _update_frame _local.stack = _local.stack[:-1] + (_current_frame()._replace(**kwargs),) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 53, in _current_frame raise RevisionManagementError("There is no active revision for this … -
Create django form from ajax request
I have a cutom form of the following outline: class NewTestForm(forms.ModelForm): class Meta: model = TestModel fields = ['field1', 'field2'] and i want to use it in a view def post(self, request): self.form = NewTestForm(request.POST) form_instance= self.form.instance ... i'm submitting it using ajax $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), But the data of the form is not available in NewTestForm(request.POST), because ajax request has different structure, than the regular form submit, i think. How is it possible to create new form from request made by ajax. I've tried to do this like $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: {'data': frm.serialize()}, dataType: "application/json", headers: {"X-CSRFToken": getCookie('csrftoken')}, and get data in a view like self.form = NewTestForm(request.POST.get('data')) but no effect. -
Error in django-app-metrics
I am using django-app-metrics for recording some metrics in my webapp. I using python3 and i installed app-metrics using following command - pip3 install django-app-metrics. But when I am importing from app_metrics.utils import create_metric it is giving me this error : File "/usr/local/lib/python3.6/site-packages/app_metrics/utils.py", line 92 except Exception, e ^ SyntaxError: invalid syntax Can someone tell me what i am doing wrong ? -
If I try to call multiple methods from django views sequentially with ajax, only the last call's response is returned
Hi everyone, I am building a web application in django, that takes a file from the user, processes it server side, zips the results and downloads the zip file to the user. The downloading part is done with an ajax call from a template. After downloading the file, I would like to delete it from the server, so I made a method called clean_up, that wipes all folders. Ajax call from the template: (I tried other things too, like calling window.location in the complete() part with no success. If I only run the first ajax call, that works, the two together do not, but the logger.debug prints the messages in my command line, so I know the methods are called and run, just the response is not returned) function my_download() { $.ajax({ url: '/ymap_webtool/result', type: "GET", data: { }, success: function (data) { alert("The browser is now going to download the results") window.location = '/ymap_webtool/result'; }, complete: function () { }, error: function () { } }).then($.ajax({ url: '/ymap_webtool/clean_up', type: "GET", data: {}, success: function (data) { window.location.href = '/ymap_webtool/clean_up'; }, complete: function () { }, error: function () { window.location.href = '/ymap_webtool/submission_failed'; } })); }; Called methods from the … -
Django - Discard inline form value
I've created a simple form Django Admin Form with a select field and a inline sub form. I would like that the fields of inline form were loaded only if the select field takes a value "example: 1". It's possible? I've already overwrite the functions save_model and save_formset but without effect def save_model(self, request, obj, form, change): if form.fields['my_field']!="1": # discard inline super(TaskAdmin, self).save_model(request, obj, form, change) Can someone help me? -
Celery does not registering tasks
Hello! I just started to use Celery with Django. I've a task that i need to be periodic. In admin interface I can see my task in dropdown list named "Task (registered):". But when Celery Beat tries to execute it NotRegistered exception is thrown. Python 3.5.2, Django 1.11.4, Celery 4.1, django-celery-beat 1.1.0, django-celery-results 1.0.1 Part of settings.py related to celery: CELERY_BROKER_URL = 'amqp://user:*****@192.168.X.X/proj' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Moscow' celery.py and proj/__init__.py are identical to documentation examples. proj/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) proj/__init__.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] tasks.py: from celery import shared_task from core.backend.files import SFTP @shared_task def load_files_from_sftp(): ftp = SFTP() ftp.get_files() I get the following json result: {"exc_message": "'core.tasks.load_files_from_sftp'", "exc_type": "NotRegistered"} If I try to use celery.task.control.inspect() from shell, it is only debug_task() there. Just stuck! ( I'll be grateful for any help. -
Integrate flask with legacy Database
I am new with flask, I am trying to create model classes from existing database tables ,in Django to achieve that we can use python manage.py inspectdb it will create a model classes. Is there any slimier option in flask ? I searched it and found some options like SQLAlchemy's autoload, it does not creates models classes on the fly. Please suggest.. -
django NOT NULL constraint failed error
I am having an error in the form :NOT NULL constraint failed: website_team_members.myuser_id in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team. I am getting that error when trying to assign an existing user in the data base here is my code : def TeamRegister2(request): #import pdb; pdb.set_trace() InviteFormSet = formset_factory(InviteForm2) if request.method == 'POST': formset = InviteFormSet(request.POST) if(formset.is_valid()): for i in formset: mail = i.cleaned_data['Email'] if MyUser.objects.filter(email = mail).exists(): user = MyUser(email = mail) u1 = user.id # get user ID a1 = MyUser.objects.get(email = request.user.email) #get user email a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user a3 = a2.latest('id') # extract the last project a4 = a3.team_id # extract the team linked to the project a4.members.add(u1) # add the member to the team invited_user = MyUser.objects.get(email = mail) current_site = get_current_site(request) message = … -
Using the reserved word "class" as field name in Django and Django REST Framework
Description of the problem Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species. More information on Taxonomy and Taxonomic ranks in Wikipedia. Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this: { "species": "vulpes", "genus": "Vulpes", "family": "Canidae", "order": "Carnivora", "class": "Mammalia", "phylum": "Chordata", "kingdom": "Animalia", "domain": "Eukarya" } Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name. What I have tried A model class created in Django would look like this: class Species(models.Model): species = models.CharField() genus = models.CharField() family = models.CharField() # class = models.CharField() - class is reserved word in Python # class_ = models.CharField() - Django doesn't allow field names # ending with underscore. That wouldn't be either a satisfying … -
django rest framework syntax error in exceptions.py
I am getting syntax error in exceptions.py which is in rest_framework package of site_packages. I have tried to correct those lines but as such there is no error. -
My Django website not showing any forms when I edit
I'm building a website using Django. And for somereason, the dictionary using all the forms is not showing at all.. When I click my Edit button the modal is showing without the forms... forms.server_id needs to contain all the forms using server_id... the server_id I use to show the previous data when I edit. But for some reason, it doesn't show any form at all... index.html - <div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Edit Server <strong>{{ server.ServerName }}</strong> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% with server.id as server_id %} <form action="{% url 'edit_post' server_id %}" method="post"> {% csrf_token %} <!--<center> {{ forms.server_id.as_p }} </center> --> {% for field in forms.server_id %} <div class="fieldWrapper"> {{ field.errors }} <!-- {{ field.label_tag }} --> <small><strong>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </strong> {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> <div class="wrapper"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>&nbsp;&nbsp;&nbsp; <h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2> </div> </form> {% endwith %} </div> </td> </tr> {% endfor %} </tbody> </h5> </table> views.py - # Create your views here. from … -
cursor.execute doesn't return anything in django but it works on mysql
So I have a query I want to run in Django using cursor.execute: def get_user_history(user_id): with connection.cursor() as cursor: cursor.execute(""" SET @user_id = %s; SELECT * FROM ( SELECT channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM channel WHERE user_id = @user_id UNION ALL SELECT channel_id, article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM article WHERE channel_id in (SELECT channel_id from channel where user_id = @user_id) UNION ALL SELECT NULL as channel_id, article_id, comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM comment WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM user_friends WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, channel_id as followed_channel_id, NULL as liked_article_id, created_at FROM user_follows_channel WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, article_id as liked_article_id, created_at FROM user_likes_article WHERE user_id = @user_id ) T1 ORDER BY created_at; """, [user_id]) if cursor.fetchall(): return dictfetchall(cursor) … -
Setting points for an object in pinax-points
I want to set points or upvote or downvote for an object using pinax-points But there is no documentation. I'm adding docs but I'm unable to figure out how to add upvotes or downvotes. I can get the points using this documentation I have added, but can't set them {% load pinax_points_tags %} {% points_for_object user as points %} <div class="user-points">{{ points }}</div> -
Add filter and export to excel in django app without using django tables-2
i need to add an option to filter data according to some column categories earlier i was using django tables_2 to display my table but that i was not able to filter data using that and decided tow rite my own view my home.html looks like this <thead> <tr> <th>Customer Name</th> <th>Status</th> <th>Product</th> <th>Operating System</th> <th>Server Type (PHY/VM/LPAR)</th> <th>Version</th> </tr> </thead> <tbody> <tr> {% if custom %} {% for item in custom %} <tr> <td>{{ item.name }}</td> <td>{{ item.Status}} </td> <td>{{ item.Product}}</td> <td>{{ item.Operating_System}}</td> <td>{{ item.Server_Type}}</td> <td>{{ item.Version}}</td> </tr> {% endfor %} {% else %} there are no records {% endif %} </tbody> Now my table is displayed but I would like to give an option to filter data and also an option to export that to excel sheet after filtering how should i go about it ? -
Host Not Allowed 192...224 even though it is already in my django project
I have a django project that I have puhsed to docker and then a digital ocean server for live testing in a working environment. In the settings file, I have an ip address from my digital ocean server added to the allowed host portion of the settings file, but I am getting the following error: DisallowedHost at / Invalid HTTP_HOST header: '192...244:8000'. You may need to add '192...244' to ALLOWED_HOSTS. Here is the code I have ALLOWED_HOSTS = ['192...244', 'localhost', '127.0.0.1'] I didnt add the full Ip even though I have the fill ip in my files. -
How do I set django generic foreign key from my views?
I have 4 forms that the user submits by clicking one Submit button. The forms are: Person Form - Will Save to Person Model Address Form - Will Save to Address Model Email Form - Will save to Email Model Phone Form - Will save to Phone Model. So, a Person can have multiple Addresses, Emails and Phone Numbers. So, I did this in the Person Model: class Person(models.Model): first_name = models.CharField(max_length=99) middle_name = models.CharField(max_length=99, blank=True, null=True) last_name = models.CharField(max_length=99, blank=True, null=True) address = GenericRelation('Address') phone = GenericRelation('Phone') email = GenericRelation('Email') I have these 3 lines along with their respective model fields for Address, Phone and Email content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Now, how do I save data to these models properly in my views when I receive the form from the user? This what I have so far. if request.method == 'POST': if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \ and phone_form.is_valid(): address = address_form.save() email = email_form.save() phone = phone_form.save() person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone person.address = (address) #This is where I need help. Am I thinking right? Is this the … -
How can I avoid inline styling, yet take advantage of the templating language?
For each instantiation of an object in the template, I'd like to extract it's associated ImageField's url in order to show the photo. But I'm having trouble finding a way to do this without inline styling: {% for entry in entries %} <div class="row"> <div class="col s4"> <div class="card-panel" style="background-image: url('{{entry.image.url}}');"> <h1>{{entry.title}}</h1> </div></div></div> {% endfor %} This works in bringing each individual image to the template, but I wonder if I can abstract away the css just to keep my css in a separate file. -
Django matching query does not exist - about encoding
I've got a Error: "User does not exist" when I'm querying in Django by Chinese name of users. related codes: reload(sys) sys.setdefaultencoding('utf-8') user_name = sheet.cell_value(r, 7).replace(' ', '') equipment.eq_receiver = User.objects.get(user_name=user_name) class User(AbstractUser): user_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=20) Traceback: Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "F:/repositories/ITIMS\eqp_mgt\views.py", line 652, in import_excel equipment.eq_receiver = User.objects.get(user_name=user_name) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name DoesNotExist: User matching query does not exist. In Debugger,I got the value of user_name: user_name={unicode}u"邵阳" Then in Watches view of Pycharm,I tried some other queries,but the result confused me: User.objects.get(user_name=u'\u90b5\u9633')={User}邵阳 #unicode of '邵阳' User.objects.get(user_name=u'邵阳')={DoesNotExist}User matching query does not exist. User.objects.get(user_name='邵阳')={User}邵阳 User.objects.get(user_name=user_name)={DoesNotExist}User matching query does not exist. -
When will a Django model instance with multi relations (ForeignKey with CASCADE) be deleted?
Having class C with relation to A & B and on_delete is set to CASCADE: class A(models.Model): pass class B(models.Model): pass class C(models.Model): palette_operation = models.ForeignKey(A, on_delete=models.CASCADE, blank=True, null=True) palette_operation = models.ForeignKey(B, on_delete=models.CASCADE, blank=True, null=True) If delete A while B is null, will C be deleted? If delete A while B is not null, will C be deleted? -
How to create a serializer class to return json of such a view?
I'm beginning to learn django and I did the polls app first and an extended version of it, now I'm trying to create a JSON-api for the same app using the REST framework. Models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') total_votes = models.IntegerField(default=0) pop_response = models.CharField(max_length=200, default='No responses yet') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now # used the following functions to order choices differently def choices_by_votes(self): return self.choice_set.order_by('-votes') def choices_by_text(self): return self.choice_set.order_by(Lower('choice_text')) # admin page config was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text View: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now() - datetime.timedelta(days=1)).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' Serializer view for the list of question @csrf_exempt def question_list(request): """ List all questions """ if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return JsonResponse(serializer.data, safe=False) Serializer for the same question list class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id', 'question_text', 'pub_date', 'total_votes', 'pop_response') Now this works fine, this gives me an equivalent json response to … -
Django join multiple models using django ORM
I googled and read many articles but got confused in multiple table join. My models looks like- class ProductCategory(models.Model): category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) category_image = models.ImageField(upload_to='category', null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.category_name) class ProductSubCategory(models.Model): category = models.ForeignKey(ProductCategory) sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.sub_category_name) class Product(models.Model): category = models.ForeignKey(ProductCategory) sub_category = models.ForeignKey(ProductSubCategory) product_name = models.CharField(max_length=200,blank=True, null=True) product_price = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) # is_discountable = models.CharField(max_length=3, default='Yes', choices=option) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.product_name) class ProductColor(models.Model): product = models.ForeignKey(Product) product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True) product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) product_image = models.ImageField(upload_to='images', null=True, blank=True) Now in views, I want to get the product filters according to category and sub-category having all the images and colors. -
Django IntegrityError null value in column "author_id" violates not-null constraint
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django. Below are my files: models.py class CommonModel(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=400) comments = models.TextField(blank=True) requirements = JSONField(default = {}) specs = JSONField(default= {}) created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(blank=True, null=True) class Meta: abstract = True def update(self): self.updated_date = timezone.now() self.save() def __str__(self): return self.title class Item(CommonModel): HW = 'HW' NW = 'NW' SW = 'SW' VM = 'VM' WI = 'WI' SI = 'SI' ITEM_TYPES = ( (HW, 'Hardware'), (NW, 'Network'), (SW, 'Software'), (VM, 'Virtual Machine'), (WI, 'Work Item'), (SI, 'Support Item'), ) UNIT_LOE = 'LOE' UNIT_USD = 'USD' UNIT_TYPES = ( (UNIT_LOE, 'LOE,MD'), (UNIT_USD, 'USD'), ) item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES) unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES) otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) gp_code = models.TextField(default='Unknown') class Meta: abstract = True class ItemTemplate(Item): pass # Need ID here to relate to estimate class ItemObject(Item): pass … -
Grabing first object for each item related to items in an array - DJango
I have a django project I am working on. I have two tables which are groups and group activities. Groups store information about the group that is created. GroupActivity stores all of the activities that are related to a group. for instance a group called Welcome would be stored in the group table with info about the group. if a member is added to the group there would be a record of the activity in the group activity table. I want to create a system that allows me to grab all of the groups someone is a part of and for each group, grab the last activity that happened for each of the groups that the user is a member of. I tried using two different queries and use two for loops but it is not working at all. Can anyone help me with this.. here is the code I have Here are the tables: class Group(models.Model): name = models.CharField(max_length = 25) description = models.CharField(max_length = 250, null=True) created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class GroupActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE) bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=200, default='some …