Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass Model Field Value Via a URL in Django Using FormView
I have two different views that work together. A Formview and a ListView. They are working fine. Here is my HTML: <form method="GET" autocomplete=off action="{% url 'Book:book_by_name_list' %}"> <div> {{ form.dropdown }} </div> <button type="submit" class="button1">Submit</h3></div></button> </form> Here is my FormView: class BookByNameView(LoginRequiredMixin,FormView): form_class = BookByNameForm template_name = 'book_by_name.html' def get_form_kwargs(self): kwargs = super(BookByNameView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs Here is my Form: class BookByNameForm(forms.Form): dropdown = forms.ModelChoiceField(queryset=Book.objects.none(),required=False) def __init__(self, *args, **kwargs): user = kwargs.pop('user') dropdown = kwargs.pop('dropdown', None) super(BookByNameForm, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices6' qs = Book.objects.all() self.fields['dropdown'].queryset = qs Here is the URL that I am using: url(r'^book_by_name_list/(?P<pk>\d+)/$',views.BookByNameListView.as_view(),name='book_by_name_list'), When the user clicks on the form.dropdown, view and clicks submit, the book_by_name_list URL is returned via the following ListView: class BookByNameListView(LoginRequiredMixin,ListView): model = Book context_object_name = 'book_list' template_name = 'book_by_name_list.html' paginate_by = 15 def get_form_kwargs(self): kwargs = super(BookByNameListView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_context_data(self, **kwargs): context = super(BookByNameListView, self).get_context_data(**kwargs) dropdown = self.request.GET.get("dropdown", None) context['dropdown'] = dropdown return context def get_queryset(self): dropdown = self.request.GET.get("dropdown", None) user = self.request.user if dropdown: queryset = Book.objects.filter(Q(id__exact=dropdown)).distinct() else: queryset = Book.objects.none() return queryset Using the code above the dropdown is retrieved via the HTML GET and the ID of the dropdown … -
Trying to connect Django and MySQL
I've been using Django with Sqlite to learn and now waned to start on a first real project. I'm looking to use MySQL as the database. I installed MySQLClient but keep running into this error when trying to run a migration. I've spent several hours trying to look through other posts but just can't seem to figure this out. Any direction on this out would be greatly appreciated. My setup is: Python - 3.8 Django - 3.0.6 MySQL - 5.7 MSQLClient - 1.4.6 macOS - Catalina Traceback (most recent call last): File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 222, in all return [self[alias] for alias in self] File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File … -
Display user's posts in their profile on django
I have been trying to make the profile page of a user have the user's posts but everytime I run my code nothing shows up only the user's username and user's email. I've tried multiple ways to make it work but somehow it doesn't. I think the profile.html has the error in it. views.py def profile(request, pk=None): if pk: post_owner = get_object_or_404(User, pk=pk) user_posts=Post.objects.filter(posti=request.user) else: post_owner = request.user user_posts=Post.objects.filter(posti=request.user) return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts}) models.py class Post(models.Model): text = models.CharField(max_length=200) posti = models.ImageField(upload_to='media/images', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default=2) profile.html <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post_owner.username }}</h2> <p class="text-secondary">{{ post_owner.email }}</p> </div> {% for Post in user_posts %} <li class="list-group-item">{{ Post.text }} <a href="{% url 'profile_pk' pk=image.user.pk %}">{{ Post.user }}</a> {% if Post.posti %} <img src="{{ image.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px"> {% endif %} {% if Post.user == user %} <div class="float-right"> <form action="delete_image/{{ image.id }}/" action="post"> <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button> </form> </div> {% endif %} </li> {% endfor %} </div> </div> -
Template Variations title not showing
I have made a variation to an Item class in models.py and I think i got the template syntax right but apparently there are something wrong which i can't figure it out Here is the model class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() slug = models.SlugField(unique=True) image = models.ImageField(blank=False, upload_to='approved designs') def __str__(self): return self.title class Meta: unique_together = ('title', 'slug') class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.title and here is the template {% if item.variation_set.all %} <select class='form-control' name='size'> {% for items in item.variation_set.all %} <option value='{item.variation|lower}'>{{title.title|capfirst}}</option> {% endfor %} </select> {% endif %} -
Need help formulating a query
I have a model named Portfolios, where one field contains a set of Widgets. I am trying to create a query that will return me the Unique set of Widgets from a selected set of Portfolios. list(Portfolio.objects.filter(user=user).values('widgets').distinct()) From this query, I am getting back a list that looks like this [{'widgets': 2}, {'widgets': 6}, {'widgets': 159}, {'widgets': 184}, {'widgets': 291}] What I can't figure out is how to have it return the list of the resolved Widget instances. Ultimately, what I need, is this. [WidgetInst1, WidgetInst2, WidgetInst3, WidgetInst4, WidgetInst5] I can of course pull the instances out of the dictionary entries if they have to come back that way. I am trying to do this with the best performance possible, since I am trying to resolve performance issues from manually iterating over results and doing additionally queries. In addition to the list of Widgets, I also need to get the list of all of the Portfolios that the Widgets are contained in. What would be the best way to go about that from a performance stand point? Do I need to iterate over each of the Widgets and do a separate query for each one? -
Duplicate Entry for Key Primary in Django - how do I do an upsert in Django?
I am trying to do an update_or_create on Django, with some logic involved as well (I have to do a slight deviation from best practices with PUT due to the unique nature of the character set I am using). I've got the following code in my view (only showing the PUT method): class WordView(APIView): def put(self, request, user_id): character = request.data.get('character') correct = request.data.get('correct') mistakes = request.data.get('mistakes') score = request.data.get('score') if Word.objects.filter(user_id=user_id, character=character).exists(): orig_word = Word.objects.get(user_id=user_id, character=character) correct = correct + orig_word.correct mistakes = mistakes + orig_word.mistakes trials = orig_word.trials + 1 score = (score + (orig_word.score * orig_word.trials)) / trials pk = orig_word.pk else: trials = 1 # Note - I know that pk won't exist on create - just testing update right now word_saves = {"user_id": user_id, "character": character, "correct": correct, "mistakes": mistakes, "score": score, "trials": trials, "pk": pk} serializer = WordSerializer(data=word_saves) if serializer.is_valid(raise_exception=True): word_saved = serializer.save() return Response({"success": "Word character {} saved for user {}".format(word_saved.character, word_saved.user_id)}) Any then in my WordSerializer, I have this: class WordSerializer(serializers.Serializer): user_id = serializers.IntegerField() character = serializers.CharField() correct = serializers.IntegerField() mistakes = serializers.IntegerField() score = serializers.FloatField() trials = serializers.IntegerField() pk = serializers.IntegerField() def create(self, validated_data): return Word.objects.update_or_create(**validated_data) However, when I make a … -
Django view test fails because form is invalid, but form test passes with same form data
I'm trying to create a test for this view in Django (using ModelBaker/ModelMommy): views.py @staff_member_required def bulk_assertion_create(request): initial = {} form = BulkBadgeAssertionForm(request.POST or None, initial=initial) if form.is_valid(): # ... do stuff return redirect('badges:list') return render(request, "badges/assertion_form.html", {"form": form}) But my test for this view fails: test_views.py def test_bulk_assertion_create(self): # log in a teacher success = self.client.login(username=self.test_teacher.username, password=self.test_password) self.assertTrue(success) form_data = { 'badge': baker.make('badges.Badge'), 'students': [baker.make(User).profile, baker.make(User).profile] } response = self.client.post(reverse('badges:bulk_grant'), data=form_data) self.assertRedirects(response, reverse("badges:list")) It fails because form.is_valid() is false in the view, so it doesn't redirect where I'm expecting it too if the form was valid. Debugging the test shows that the for is not valid because: ValidationError(['"testuser2" is not a valid value.']) But if I use the same form data when testing the form directly, it IS valid: forms.py class BulkBadgeAssertionForm(forms.Form): badge = forms.ModelChoiceField(queryset=None, required=True) students = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwds): super(BulkBadgeAssertionForm, self).__init__(*args, **kwds) self.fields['students'].queryset = Profile.objects.all_for_active_semester() self.fields['badge'].queryset = Badge.objects.all_manually_granted() self.fields['students'].widget = ModelSelect2MultipleWidget( model=Profile, queryset=Profile.objects.all_for_active_semester(), search_fields=['first_name__istartswith', 'last_name__istartswith', 'preferred_name__istartswith', 'user__username__istartswith', ] ) test_forms.py def test_bulk_badge_assertion_form(self): form_data = { 'badge': baker.make('badges.Badge'), 'students': [baker.make(User).profile, baker.make(User).profile] } form = BulkBadgeAssertionForm(data=form_data) self.assertTrue(form.is_valid) Why does the form_data validate in the form test, but not the view test? -
Display a results from using foreign key - django
I'm looking to display clients information. A client is registered then they can fill out different forms, I need those forms to be attached to the client and display the latest 4 forms in an area on the same page as the client details. model.py class Casenotes(models.Model): FORMREG = models.ForeignKey(Register_Client, blank=True, null=True, on_delete=models.CASCADE) FORMREGCOUN = models.ForeignKey(Register_Counsellor, blank=True, null=True, on_delete=models.CASCADE) DATEADDED = models.DateField(auto_now=True) NOTES = models.TextField(blank=True) def get_absolute_url(self): return f"/case/{self.id}/" class Register_Client(models.Model): DATEADDED = models.DateField(auto_now=True) TITLES = ( ('MR', 'Mr'), ('MISS', 'Miss'), ('MRS', 'Mrs'), ('OTHER', 'Other') ) TITLE = models.CharField(max_length=5, choices=TITLES, blank=True, default=None) FIRST_NAME = models.CharField(max_length=50) LAST_NAME = models.CharField(max_length=50) views.py def registerclient(request): #register a client if request.method == 'POST': form = RegisterClientForm(request.POST) if form.is_valid(): form.cleaned_data saved = form.save() return redirect(saved.get_absolute_url()) else: print("Invalid form") print(form.errors) else: form = RegisterClientForm() return render(request, 'HTML/ClientRegistration.html', {"form":form}) def registeredclient(request, id): #display the registered client obj = get_object_or_404(Register_Client, id=id) content = { "obj": obj, } return render(request, 'HTML/Client.html', content) -
Creating a csv from request data and saving it into a model field - Django
I have a model that includes a text field and a file field. A user can either upload a csv file or some text which I should parse into a csv and save it in the file field. It goes something like this class UserUpload(models.Model): ...... ...... filefield = file_uploaded = models.FileField(upload_to='media/', validators= FileExtensionValidator(allowed_extensions=['csv'])], blank=True, null=True) datafield = models.TextField(blank=True, null=True) In the serializer import csv class UserUploadSerializer(serializers.ModelSerializer): ..... def csv_parser(self, datastream): with open('test,csv', 'w') as csv_file: data_writer = csv.write(csv_file) for x in datastream: data_writer.writerow(x) return csv_file def create(self, validated_data): if 'datafield' in validated_data: output_file = self.csv_parser(validated_data['data_uploaded'].split(", ")) return UserUpload.objects.create(filefield=output_file, **validated_data) else: return UserUpload.objects.create(**validated_data) Upon working with this logic I always get an error saying _io.TextIOWrapper object has no attribute '_committed' which i figured it might do with the Django FileContent class but when I tried that, it didn't succeed. Any help on how I can figure this out? -
How to call a app endpoint from within app django
Let's say I have a django app that is running on http://127.0.0.1:8000/ That app has an endpoint called homepage which renders a view and on the view there is a button. When that button is pressed, I want to call an API endpoint (button_pressed) within my django app, for example http://127.0.0.1:8000/button_pressed (this should return JSON) Would I have to just do a normal XMLHttpRequest to http://127.0.0.1:8000/button_pressed in JS when the button is pressed? Or is there another, better way to do it? -
IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint
django rest framework post request error Here is the image model class Img(models.Model): created_at=models.DateTimeField(auto_now_add=True) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img") picture=models.ImageField(upload_to='fake_picture',null=True,blank=True) tags = TaggableManager(blank=True) Here is the image serializer for model Img class ImgSerializer(serializers.ModelSerializer): tags = TagListSerializerField(required=False) author = serializers.StringRelatedField(read_only=True) # post = serializers.StringRelatedField(read_only=True) class Meta: model=Img fields='__all__' views.py class ImgViewSet(viewsets.ModelViewSet): parser_class = (FileUploadParser,) permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication) queryset = Img.objects.all() serializer_class=ImgSerializer but when ever a post request to that particular api endpoint is triggered from the post man with key value pair as picture:image.jpg this is what the response is IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null). Request Method: POST Request URL: http://localhost:8000/api/img/ -
Why does the view function render more than one instance of the form field?
Please I need help with the code below. I'm trying to make an ajax call that renders the create_post view on a modal page. But it renders multiple instances of the form fields, instead of one. def save_room_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True rooms = list(Room.objects.all().values()) data['html_room_list'] = render_to_string('sharespace/includes/partial_room_form.html', {'rooms': rooms}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) print(data.items()) return JsonResponse(data) def create_post(request): if request.method == 'POST': form = RoomForm(request.POST) else: form = RoomForm() return save_room_form(request, form, 'sharespace/shareform.html') ajax call: $(function () { var loadForm = function () { var btn = $(this); console.log("before ajax") $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-room").modal("show"); }, success: function (data) { $("#modal-room .modal-content").html(data.html_form) console.log("clicked"); } }); }; //Create room $(".js-create-room").on("click", loadForm); }); My sanity check suggests the problem is from the view(i think). Any help will be appreciated. Thanks -
Multiple for loops (not nested) in Django Template and the second one not working
I'm facing the following problem: On the view.py I send to the view template a list, such as: return render(request, 'template.html', {'images': list}) Then on the template I make a for like: {% for img in images %} {{ img }} {% endfor %} and on other part of the template again I do: {% for img in images %} {{ img }} {% endfor %} but this second time the code doesn't even enter inside the loop, it looks like the cursor of the for is pointing to the last element of the array, is that right? how to fix it, I mean, move this cursor to the first position, supposing this is the case. -
Can't get my Django Build to deploy on Heroku. i
-GitHub link to my project- I've followed every link and tutorial I can find. I'm operating under a virtual environment. I've tried to pip install Heroku, tried to run the commands you see in the errors... I'm stumped and can't find anyone else with a problem like mine? Help me see the silly error I'm making. -----> Python app detected -----> Installing python-3.6.10 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip Collecting bcrypt==3.1.7 Downloading bcrypt-3.1.7-cp34-abi3-manylinux1_x86_64.whl (56 kB) Collecting cffi==1.12.3 Downloading cffi-1.12.3-cp36-cp36m-manylinux1_x86_64.whl (430 kB) Collecting Django==2.2.3 Downloading Django-2.2.3-py3-none-any.whl (7.5 MB) Collecting pycparser==2.19 Downloading pycparser-2.19.tar.gz (158 kB) Collecting PyMySQL==0.9.3 Downloading PyMySQL-0.9.3-py2.py3-none-any.whl (47 kB) Collecting pytz==2019.1 Downloading pytz-2019.1-py2.py3-none-any.whl (510 kB) Collecting six==1.12.0 Downloading six-1.12.0-py2.py3-none-any.whl (10 kB) Collecting sqlparse==0.3.0 Downloading sqlparse-0.3.0-py2.py3-none-any.whl (39 kB) Building wheels for collected packages: pycparser Building wheel for pycparser (setup.py): started Building wheel for pycparser (setup.py): finished with status 'done' Created wheel for pycparser: filename=pycparser-2.19-py2.py3-none-any.whl size=111031 sha256=46327781c9ae2fca04d15bc02ca6a1f09a2624442730fdc7b492f1431e81c4de Stored in directory: /tmp/pip-ephem-wheel-cache-xz8b2s9m/wheels/c6/6b/83/2608afaa57ecfb0a66ac89191a8d9bad71c62ca55ee499c2d0 Successfully built pycparser Installing collected packages: six, pycparser, cffi, bcrypt, sqlparse, putz, Django, PyMySQL Successfully installed Django-2.2.3 PyMySQL-0.9.3 bcrypt-3.1.7 cffi-1.12.3 pycparser-2.19 pytz-2019.1 six-1.12.0 sqlparse-0.3.0 -----> $ python burnett_portfolio/manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' … -
KeyError Post DjangoRestFramework
I'm new on Django Rest Framework and when I want to POST data I get a error: KeyError: 'id_area' I do not know what I'm doing wrong. Here's my code: in my models.py class Area(models.Model): id_area = models.AutoField(primary_key=True) APM = 'apm' BUSINESS = 'business' DESARROLLO = 'desarrollo' SISTEMAS = 'sistemas' ATENTUSIANOS_CHOICES = ( (APM, 'Apm'), (BUSINESS, 'Business'), (DESARROLLO, 'Desarrollo'), (SISTEMAS, 'Sistemas'), ) nombre = models.CharField(max_length=255, choices=ATENTUSIANOS_CHOICES) class Meta: verbose_name = 'Área' verbose_name_plural = 'Áreas' def __str__(self): return self.nombre class Atentusiano(models.Model): id_atentusiano = models.AutoField(primary_key=True) nombre = models.CharField(max_length=255, blank=False, null=False) apellido = models.CharField(max_length=255, blank=False, null=False) correo = models.CharField(max_length=255, blank=False, null=False, unique=True) anexo = models.CharField(max_length=255, blank=True, null=True) area = models.ForeignKey(Area, related_name='areas', on_delete=models.CASCADE) class Meta: verbose_name = 'Atentusiano' verbose_name_plural = 'Atentusianos' ordering = ['nombre'] def __str__(self): return self.nombre + ' ' + self.apellido in my serializers.py class AreaSerializer(serializers.ModelSerializer): areas = serializers.CharField(read_only=True) class Meta: model = Area fields = ('id_area', 'nombre', 'areas') class AtentusianoSerializer(serializers.ModelSerializer): atentusianos = serializers.CharField(read_only=True) area = serializers.CharField(source='area.nombre', read_only=True) id_area = serializers.CharField(source='area.id_area') class Meta: model = Atentusiano fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos'] def create(self, validated_data): area_data = validated_data.pop('id_area') area = models.Area.objects.create(**area_data) atentusiano = models.Atentusiano.objects.create(area=area, **validated_data) return atentusiano And in my views.py class AtentusianoView(viewsets.ModelViewSet): queryset = Atentusiano.objects.all() serializer_class = … -
Django admin not allowing blank on foreign relation
I have a model a foreign relation class M(models.Model): f_key = models.ForeignKey(FModel,blank=True,null=True,) name = models.CharField(max_length=250, blank=False, null=False) When i add objects through the command line or programmatically I can add objects that have a null f_key but in the admin GUI it forces me to fill out this field. Is there a way to make it nullable in the GUI? -
Django: NOT NULL constraint failed even with `null=True`
I have a problem while trying to create a child. I have a model Work parent to a model Price. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.id) My price_model: from django.db import models from .model_work import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, null=True, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) And my work_serializer: from rest_framework import serializers from ..models.model_work import Work from .serializers_user import * class WorkIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Work models from DB """ user = UserIndexSerializer() class Meta: model = Work fields = [ 'id', 'user', 'name', 'image', 'length', 'width', ] class WorkCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Work model in DB """ user = UserIndexSerializer() class Meta: model = Work fields = [ 'user', 'name', 'length', 'width', ] def create(self, validated_data): work = Work.objects.create(**validated_data) return work class WorkDetailsSerializer(serializers.ModelSerializer): """ Serializer showing details of a Work model from DB """ user = UserDetailsSerializer() class Meta: model = Work fields = [ 'id', 'user', 'name', 'length', 'width', … -
Django How to add class media with condition
How to add class media with condition ,only in add form and change form , but not in the view page ( where fields are readonly )? or add media class with condition by user group id ? my model admin class CooperationBilateraleAdmin(ManyToManyAdmin): fieldsets = [ ( '', { 'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation'] }), ('Autres élements à rajouter ?', { 'fields': ['infoPlus', ] }), ('', { 'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')] }), ('Base Documentaire', { 'fields': [], 'description': 'Joindre le(s) fichier(s) '}), ] class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js', # jquery '/static/admin/js/CooperationBilaterale.js', # project static folder ) css = { 'all': ('/static/admin/css/CooperationBilaterale.css',) } def render_change_form(self, request, context, *args, **kwargs): user = get_user_model() group = request.user.groups.values_list('id', flat=True).first() if request.user.has_perm('system.edit_CooperationBilaterale') or request.user.has_perm('system.add_CooperationBilaterale'): context['adminform'].form.fields['partenaire'].queryset = PartenaireInternational.objects.filter( caneva__contains=',2,') context['adminform'].form.fields['etat'].queryset = Etat.objects.filter(type__exact=3) context['adminform'].form.fields['duree'].queryset = DureeCooperation.objects.all().order_by('order') if group==2: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=1) | Q(region=2)).distinct() if group==3: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(region=6).distinct() if group == 4: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=3) | Q(region=4)).distinct() return super(CooperationBilateraleAdmin, self).render_change_form(request, context, *args, **kwargs) -
Separate from through model
Django==3.0.6 django-taggit==1.2.0 I'd like to organize special tagging for myself. It is not for users and will not be used in templates. class SpecialAdminTaggedPost(TaggedItemBase): # https://django-taggit.readthedocs.io/en/v0.10/custom_tagging.html # Used at admin site only (for sorting, filtering etc.). content_object = models.ForeignKey('Post', on_delete=models.PROTECT) class Post(models.Model): tags = TaggableManager() admin_tags = TaggableManager(SpecialAdminTaggedPost) When I run the program, I got this error: "You can't have two TaggableManagers with the" ValueError: You can't have two TaggableManagers with the same through model. Documentation: https://django-taggit.readthedocs.io/en/v0.10/custom_tagging.html I seem to have failed to separate from "through model". Could you help me here? -
Exception Type: OperationalError Djano Although I executed makemigrations and migrate
I am really confused for the reason of this error although I read several times that an error named: "OperationalError" to be fixed by makemigrations and migrate I did it several time but I am not sure what is the reason for still coming up with this error: Here is the Model.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) def __str__(self): return self.title class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.title here is the admin.py from.models import Variation admin.site.register(Variation) here is the error OperationalError at /admin/core/variation/ no such column: core_variation.item_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/core/variation/ Django Version: 2.2 Exception Type: OperationalError Exception Value: no such column: core_variation.item_id -
How can I get my css to render correctly? Is my file path correct?
So I'm a newbie and I'm having trouble getting my css to render in Django. I am attempting to create a red notification like in Facebook for my unread messages. But my css isn't rendering. I am thinking it's something to do with where I placed the css file, but I'm not sureWhat am I doing wrong here? Here's my code: settings.py/Static STATIC_URL = '/static/' STATICFILES_DIRS = [ "/DatingAppCustom/dating_app/static", ] notification.css .btn { width:100px; position:relative; line-height:50px; } .notification { position:absolute; right:-7px; top:-7px; background-color:red; line-height:20px; width:20px; height:20px; border-radius:10px; } base.html/notification section <link href="{% static 'notification.css' %}"> <button class="btn">message counter <div class="notification">{% unread_messages request.user %}</div> </button> directory project path . ├── 11_env │ ├── bin │ │ ├── __pycache__ │ │ ├── activate │ │ ├── activate.csh │ │ ├── activate.fish │ │ ├── django-admin │ │ ├── django-admin.py │ │ ├── easy_install │ │ ├── easy_install-3.7 │ │ ├── pip │ │ ├── pip3 │ │ ├── pip3.7 │ │ ├── python -> python3 │ │ ├── python3 -> /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 │ │ └── sqlformat │ ├── include │ ├── lib │ │ └── python3.7 │ └── pyvenv.cfg ├── dating_app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ … -
How to properly serve a Django application throught Twisted's Web server?
I am building a system that was some components that will be run in its own process or thread. They need to communicate with each other. One of those components is a Django application, the internal communication with the Django app will not be done through HTTP. Looking for networking libraries I found Twisted (awesome library!), reading its documentation I found that Twisted implements the WSGI specification too, so I thought its Web server could serve WSGI applications like Django. Following the docs I come with the following script to serve the Django app: from twisted.web import server from twisted.internet import reactor, endpoints from twisted.web.wsgi import WSGIResource from twisted.python.threadpool import ThreadPool from mysite.wsgi import application as django_application # Create and start a thread pool to handle incoming HTTP requests djangoweb_threadpool = ThreadPool() djangoweb_threadpool.start() # Cleanup the threads when Twisted stops reactor.addSystemEventTrigger('after', 'shutdown', djangoweb_threadpool.stop) # Setup a twisted Service that will run the Django web app djangoweb_request_handler = server.Site(WSGIResource(reactor, djangoweb_threadpool, django_application)) djangoweb_server = endpoints.TCP4ServerEndpoint(reactor, 8000) djangoweb_server.listen(djangoweb_request_handler) reactor.run() I made a django view that does a blocking call to time.sleep() to test it, it worked fine. Since it's multithread, it did not block other requests. So I think it works well with … -
what is the correct way to override the save method in django?
I have an image model where I can upload images and I want to optimize them with pillow, I did that but there is three problems: the images doesn't get saved in the correct folder. django has a feature when there is two files with the same name django adds a random string to its name but now with two images with the same name only one gets uploaded. the original images gets uploaded too. class Images(models.Model): image1 = models.ImageField(upload_to='images/%Y/', validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])]) image2 = models.ImageField(upload_to='images/%Y/', validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])]) def save(self, *args, **kwargs): im = Image.open(self.image1).convert('RGB') im2 = Image.open(self.image2).convert('RGB') im.save(self.image1.path,"JPEG",optimize=True,quality=75) im2.save(self.image2.path,"JPEG",optimize=True,quality=75) super(Images, self).save(*args, **kwargs) -
How to create user groups for permissions within code (not in admin)
I'm wanting to create user groups for permissions and am wondering how to do this in the code as it sounds like the more proper way to do it (or not?). I have done some searching and have found a few completely different pieces of code, but I am not even sure in which file this code should be located? Here is one example that I found: from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Thank you. -
Generate configuration templates using django forms and jinja template
Need help on how can I give data in django forms and pass the values to jinja template to generate configuration using python