Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generate a form directly with the results of a request
I want to pass a form and the result of a request to the template of this kind when displaying, I get a form with the values from the result of the query. Exactly like when you modify a tuple via the admin page of django. How to do it ? Views.py def modification_ue(request, code): ue_form = UEForms() ue = UE.objects.get(code_ue=code) return render(request, 'felyn/modifier.html', {'ue_form': ue_form, 'ue': ue}) -
FOREIGN KEY constraint failed with specific id
i have an error FOREIGN KEY constraint failed when trying to add item with id => 3. So if i am trying to add item with id 1 or 2 there is no error views.py from Products.models import product @login_required() def add_to_cart(request, **kwargs): user_profile = get_object_or_404(Profile, user=request.user) products = product.objects.filter(id=kwargs.get('item_id', "")).first() user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False) # !!!!!!!!!! user_order.items.add(order_item) if status: user_order.save() messages.info(request, "item added to cart" return redirect(request.META.get('HTTP_REFERER','/')) models.py class OrderItem(models.Model): product = models.OneToOneField(product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) -
How to restrict Django models from using certain foreign key values?
I am trying to create a Django model that has a "successor" field, which is a foreign key to that same model. I want to restrict the model from ever being able to (1) set an instance to be its own successor and (2) create a circular predecessor-successor relationship. This would be simple if Django called clean before saving, but apparently it doesn't. I essentially want to call the validators in the clean, add_predecessor, and add_successor methods below whenever a model is saved. class MyModel(models.Model): ... successor = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, ) ... def clean(self): if self.successor is self: raise Exception("...") def add_predecessor(self, predecessor): if predecessor is self: raise Exception("...") if self.successor is predecessor: raise Exception("...") predecessor.successor = self def add_successor(self, successor): if successor is self: raise Exception("...") if successor.successor is self: raise Exception("...") self.successor = successor I could override save, but that seems like a heavy-handed solution. -
Why is form_valid() being executed twice?
I am trying to show a Bootstrap Form Modal instead of the usual form in Django. I have written the following code. However, the form_valid() method executes twice when the modal is submitted, thus adding the data twice in the database. Any help would be appreciated. form_class = CreateBookForm template_name = 'create.html' success_url = '/main/' success_message = 'Book created' def form_valid(self, form): obj = form.save(commit=False) ## Do some additional tasks obj.save() return HttpResponseRedirect(reverse('main')) -
JSONDecodeError at '/' @ {% render_bundle 'app' %}
My goal is to get a VueJS frontend working with my DRF backend. I'm about at my wits end with this, I can't seem to get webpack-bundle-tracker to work to save my life, currently I'm battling an error which I have no idea what it means... Expecting value: line 1 column 1 (char 0) at {% render_bundle 'app' %} Does anyone have ANY kind of resource where I can either learn how to, or simplify this process? I am at the point where all I have to do is connect my front end and back end and it's a bit frustrating having such a massive road block where I didn't expect there to be one. So, I've now tried both Vue-Resource and django-cors-headers to try and get it working, however I get a cross origin reference error (403 Forbidden, Django won't let me access it from a URL without the same origin) Now I am trying to use webpack-bundle-tracker and django-webpack-loader, but there's not much information on how to configure this with Vue and the few tutorials I have found don't seem to cover authentication, or just plain don't work. vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { baseUrl: "http://0.0.0.0:8080/", … -
How can I show a message in Django url?
My views.py works properly under the path in urlpattern I have defined. I have a for loop and I want to show a message in the browser screen I've tried with httpResponse and JsonResponse, but I cant or get some errors. My views.py function is: def all_disconnect (request): try: url_cnc = 'http://**********************' auth = {'username':'*****', 'password':'*******'} log = requests.post(url_cnc, data=auth) log.cookies['SESSION'] cookie_log = log.cookies['SESSION'] peticion = requests.Session() peticion.headers.update({'Cookie' : 'SESSION='+cookie_log}) #--------------DOWN IS THE PROBLEM----------------------------------- for meter in all_meter: x = peticion.post('http://150.214.144.246:8443/ws/v1/cg/dc/meters/'+ meter +'/control/plc/Disconnect/immediate') HttpResponse ('El meter '+meter+' ha sido desconectado') return JsonResponse("fin", safe=False) except ValueError as e: return JsonResponse(e.args[0]) I can print "fin", but if I put JsonResponse inside the loop to print each "meter" I get some error. Do you know how to do this? -
Django REST: No pagination block in JSON response (PageNumberPagination)
For my API I'm using api_view decorator. Problem with pagination (JSON response). I got response without "pagination block": [ { "id": 18, "name": "Monitor Acer Test", "price": "2212.00", "stock": 21, "image": "/media/9hq.webp", "available": true }, { "id": 17, "name": "Monitor LG Test", "price": "2512.00", "stock": 10, "image": "/media/811AFxM28YL._SX425_.jpg", "available": true } ] I also tried to override default PageNumberPagination, it works, but still without "pagination block" My api view (look at GET example > else): @csrf_exempt @api_view(['GET', 'POST',]) @permission_classes([AllowAny, ]) def product(request): item = request.data if request.method == 'POST': serializer = ProductSerializer(data=item) serializer.is_valid(raise_exception=True) serializer.save() return Response({"message": "Product created!", "data": request.data}, status=status.HTTP_201_CREATED) else: all_obj = Product.objects.filter(available=True) if len(all_obj) > 0: paginator = PageNumberPagination() result_page = paginator.paginate_queryset(all_obj, request) serializer = ProductSerializer(result_page, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({"message": "There is no created items!"}, status=status.HTTP_200_OK) My settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny',], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2 } Expected result: { "count": 1023 "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } -
Django Docker: Convert video after upload
I run a Django-Backend using Docker. I want to upload large .mkv videos to the backend but convert and store them as .mp4 How should I proceed? Since this will eventually run on a kubernetes cluster, should I spawn docker-worker instances that do the job? Usually I would just run ffmpeg -i input.mkv -codec copy output.mp4 via pythons os-module but I don't want to overload the django container. I use the following to upload the .mkv video: models.py class Record(models.Model): name = models.CharField(max_length=255) ... video = models.FileField(null=True, upload_to='uploads/') serializers.py class VideoSerializer(serializers.ModelSerializer): class Meta: model = Record fields = ('id', 'video') read_only_fields = ('id',) views.py ... @action(methods=['POST'], detail=True, url_path='upload-video') def upload(self, request, pk=None): record = self.get_object() serializer = self.get_serializer( record, data=request.data ) serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) ) -
Django - CHOICE DDL - hide/disable choices
In my model I define a Choice DDL object: a = '900' b = '915' c = '930' d = '945' e = '1000' f = '1015' g = '1030' h = '1045' i = '1100' l = '1115' m = '1130' n = '1145' z = 'è uguale' ORARI_CHOICES = ( (z, "Indifferente"), (a, "09.00"), (b, "09.15"), (c, "09.30"), (d, "09.45"), (e, "10.00"), (f, "10.15"), (g, "10.30"), (h, "10.45"), (i, "11.00"), (l, "11.15"), (m, "11.30"), (n, "11.45"), ) fasce_orarie = models.CharField(max_length=15, choices=ORARI_CHOICES, default=000) In the template I was able to display the DDL al follow: {{ form.fasce_orarie }} I'm having hard times figuring out how could I disable certain specific choice fields on the go. I was able to disable other form fields into the template, by passing a variable from the view, for example: if request.method == 'GET': return render(request, "prenota.html", {'form': form, 'free_places': free_places}) else: form = PrenotaForm(request.POST) and then in the template {% if free_places > 0 %} {{ form.field_name }} {% endif %} Any hint how could I hide/disable only a certain DDL choice? Or radio button? Or may be the question is how to render a DDL in a more basic way so I … -
Internal Server Error On Django Project Served Over uWSGI & Nginx
My django Project structure is below # tree -L 2 . ├── account │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── apps │ ├── blog │ ├── blogs │ ├── gallery │ ├── __init__.py │ ├── myapp │ ├── mysensing │ ├── __pycache__ │ └── qrcreate ├── Blog │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── urls.py │ ├── views.py │ └── wsgi.py and this is my uwsgi file content [uwsgi] project = djangy uid = $USER base = /home/%(uid) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).Blog.wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true and lastly my nginx configuration file server { listen 80; server_name djangy.vm www.djangy.vm; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/$USER/djangy; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/djangy.sock; } } When I run this project using manage.py, it runs fine and shows as this But when I run it behind uwsgi & nginx, it shows internal server error, I can't … -
how to list dates in sequence between two points of time in django templates?
i want to autogenerate timetable, i created a model as follows: class Timetable(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL, null=True, blank=True) fromDate = models.DateField(blank = False, null = False) toDate = models.DateField(blank = False, null = False) heading = models.CharField(max_length =50,blank=True, null = True) i want to make a list of dates between fromDate and toDate display that list on a template. Please help if it's possible. Thank you -
ValueError: Please move the function into the main module body to use migrations
The error that I am trying to Fix ValueError: Could not find function func in posts.models. Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared and used in the same class body). Please move the function into the main module body to use migrations. For more information, see https: //docs.djangoproject.com/en/1.11/topics/migrations/#serializing-values Intro: I am using Django==1.11.20 and Ubuntu 18.04. My python version is 3.6.7 When I do in my Django project in the (venv)some_path$ python --version Python 3.6.7 However when I do the same in my Ubuntu terminal I get Python 2.7.15rc1 About my project: I have the below models def upload_name (user_fld='user', prefix=None): def func(instance, fname): #return os.path.join(prefix, fname) if prefix else fname attrs = user_fld.split('.') user = instance print ("Getattr %s %s" % (attrs, user)) try: for attr in attrs: user = getattr(user, attr) except: username = 'anon' else: username = user.username print ("Upload name** %s, %s" % (instance.pk, username)) # Extract the raw fname fparts = fname.split('.') base = fparts[0] try: atoms = base.split("_") ts = datetime.strptime('_'.join(atoms[-7:]), "%Y_%m_%d_%H_%M_%S_%f") ousername = atoms[-8] base = '_'.join(atoms[:-8]) except: # Any exception in handling this means it wasn't already equipped with our # … -
using tab keys and putting space bar four times
I heard I should avoid using tab key then does this mean I have to press space bar four times every time I want to put space which is really annoying? -
Django. How to get data from a database to a url variable in a js script?
I do a search on the site, I need to make a dependent drop-down list. I made a script following the example with a backend in php, tried to remake for django, but I just don’t understand how to get data from the database in the script while they are displayed dynamically in the template, but I need to get it in order to make the dependent list, who understands, Please see how correctly in the url variable in the script to retrieve data from the database: Search function in views.py: def search(request): regions = Region.objects.all() cities = City.objects.all() districts = District.objects.all() queryset_list = Listing.objects.order_by('-list_date') if 'region' in request.GET: region_id = request.GET.get('region') if region_id: queryset_list = queryset_list.filter(region_id=region_id) if 'city' in request.GET: city_id = request.GET.get('city') if city_id: queryset_list = queryset_list.filter(city_id=city_id) if 'district' in request.GET: district_id = request.GET.get('district') if district_id: queryset_list = queryset_list.filter(district_id=district_id) context = { 'districts': districts, 'cities': cities, 'regions': regions, 'listings': queryset_list, 'values': request.GET } return render(request, 'listings/search.html', context) urls.py path('search', views.search, name='search'), Template with script: <form action="{% url 'search' %}"> <!-- Form Row 1 --> <div class="form-row"> <div class="col-md-3 mb-3"> <label class="sr-only">Область</label> <select name="region_id" id="region_id" class="form-control"> <option value="0">-Выберите область-</option> {% for region in regions %} <option value="{{ region.pk }}">{{ … -
How to redirect to previous page? or How to get title from ForeignKey?
PART 1 I have some problems with redirecting on same page after click. or example i was at /memes and after click i am at page /add_to_cart OR PART 2 I have another solution for my problem PART 1 in view i have def add_to_cart(request, **kwargs): return redirect(reverse('meme:meme_list')) and my html looks like this a href="{% url 'shoppingcart:add_to_cart' post.id %}" class="col-2"> but if i am at the /videos and whant to add to cart i will be redirected at /meme. i ve found request.path_info but it only shows current path (add_to_cart/1) PART 2 I have category in my models for product class product(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) class Category(models.Model): title = models.CharField(max_length=32) so i can just make my prev path by '/'+ category title and i can't do it because 'ForwardManyToOneDescriptor' object has no attribute 'title' how to get title from my category? -
Sending custom mail from django admin panel
I am trying to send email to the user from admin panel to their gmail . whact can id o to send mail from admin panel to gmail. -
How to save a model instance using custom APIView in Django REST API?
I am developing a website which is build on 2 servers: Django(back), ReactJS(front); (I have changed some titles to abstract names for the sake of convenience) Model: class Model(model.Model): attr1 = models.CharField(max_length=500) attr1 = models.CharField(max_length=500) .... **author = models.ForeignKey(UserModel, on_delete=models.CASCADE)** Custom Create View: class ModelCreateAPI(APIView): def post(self, request): serializer = serializers.ModelSerializer(data=request.data) if serializer.is_valid(raise_exception=True): model_saved = serializer.save() return Response({"success": "Model created successfully"}) Serializer: class ModelSerializer(serializers.ModelSerializer): class Meta: model = Model fields = '__all__' On my React APP there is a form that sends HTTP request, including 'user token', that is stored in localStorage. However, 'author' of model should be an integer that represents pk. I have managed to convert token to pk: >>> from rest_framework.authtoken.models import Token >>> Token.objects.get(key='token').user_id Is it an effective way of doing this operation? What are your suggestions? How I can implement HTTP POST request in way that it saves the model with correct author_id? -
Is it possible to use the same url pattern with different number of kwargs?
Early I had next code in urls.py, models.py files: main urls.py: urlpatterns = [ ... path('post/', include('my_post.urls', namespace='posts')), ... ] urls.py: app_name = 'posts' urlpatterns = [ path('create/', views.PostCreateView.as_view(), name='post_create_page'), ... ] models.py: class Post(models.Model): author = models.ForeignKey(CommonUser, to_field='user', null=True, on_delete=models.SET_NULL, related_name='author') text = models.TextField() create_data = models.DateTimeField(default=timezone.now) ... and in templates I used: <a href="{% url 'posts:post_create_page' %}">Create new Post</a> And all worked Ok. Then I decided to add new optional field 'group' to Post model, after creating Group model: models.py: class Post(models.Model): ... group = models.ForeignKey(Group, null=True, default=None, on_delete=models.CASCADE, related_name='posts_in_group') ... views.py: class PostCreateView(LoginRequiredMixin, generic.CreateView): login_url = '/login/' fields = ('text',) model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['group_id'] = self.kwargs['group_id'] return context def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user.common_user self.object.posts_in_group = self.request.group_id self.object.save() return super().form_valid(form) def get_success_url(self): common_user = self.object.author return reverse_lazy('for_users:user_home_page', kwargs={'pk': common_user.pk}) I've tried to solve my problem by adding get_context_data method in views.py and also I've added self.object.posts_in_group = self.request.group_id line in the form_valid method. And now I have an exception: KeyError at /post/create/ 'group_id' with call in template: <a href="{% url 'posts:post_create_page' group_id=group_details.pk %}">Create a new post in group</a> because I haven't changed my urlpattern but I try to … -
How can I let a user choose which fields are required for a form?
I have a CarType and Car category, the user wants to be able to say: if a car is of a specific type, then only show fields X, Y, Z in the CarCreateForm. This is because CarType determines which fields are necessary (for instance, a 4 wheel drive has different info). I am guessing that this has been done before, but I can't find it. I was thinking storing the choices per field type in a json field on CarType and then dynamically create the form. -
Ajax POST sends null Value
in the template of my website I try to do an Ajax POST request to send the cordinates of the user to the server, which then should output the corresponding nearest city. However currently the only thing Ajax does is outputing a null value. The whole project uses the django framework. To make sure that the crsf is not the reason I disabled crsf protection for the whole site. I also tried instead of passing json, strings integers etc, all returned null. Additionally my success function is fireing, so the ajax function is clearly working. <script> var loc = [] ; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { loc.push( "Geolocation is not supported by this browser."); } } function showPosition(position) { loc.push(position.coords.latitude) ; loc.push(position.coords.longitude) ; } </script> <script > window.onload = function(){ getLocation(); }; $.ajax({ url: '{% url "locnews" %}', type : "post", data: { "location": loc }, datatype : "json", success : console.log("succ"), }) </script> -
Add "duplicate" objects to a table in Django
I have a model called Song and another called Chord. They have a ManyToMany relationship through a label called ChordIndex. A song might need to have the same chord more than once, which django would not allow. Hence, I gave the model an extra field (manually coded auto-incremental field) called index, so objects are not identical. Still I can't add "duplicate" chords. Nevertheless the approach works with a form and a POST method. But, if I use the POST method I am unable to set song field to default="lastSongByUser" because you can only query "user" inside a view. models.py class ChordIndex(models.Model): def incrementalNumber(): objectCount = ChordIndex.objects.count() if objectCount == None: return 2 else: return objectCount + 1 index = models.PositiveIntegerField(default=incrementalNumber) chord = models.ForeignKey('Chord', on_delete=models.CASCADE) song = models.ForeignKey('Song', on_delete=models.CASCADE) views.py def addchord_view(request, idChord): user = request.user.profile chord = Chord.objects.get(pk=idChord) songsByUser = Song.objects.filter(uploader=user) lastSongByUser = songsByUser.last() previousPage = request.META.get('HTTP_REFERER') filterUserLastSong = ChordIndex.objects.filter(song=lastSongByUser) lastSongByUser.chords.add(chord) thisObjectAdded = filterUserLastSong.last() thisObjectAdded.save() return HttpResponseRedirect(previousPage) editchords.html {% for chord in allChords %} {% if chord.acronym != silent%} <button class="btn btn-dark"><a href="{% url 'add-chord-view' idChord=chord.pk %}">{{ chord.acronym }}</a></button> {% else %} <button class="btn btn-primary"><a class="text-dark" href="{% url 'add-chord-view' idChord=chord.pk %}">next part</a></button> {% endif %} {% endfor %} I would … -
Django User model with encrypted and hashed email as username
I have a custom User model with email as username. I have encrypted the email field to be in conformity with GPDR (I will hold a lot of personal information). I have added a email_hash field with index on it for the database to be able to retrieve immediately user. I have modified get_natural_key of my user object manager to use the hash for retrieve. But now i face a problem I have to disable the uniqueness on field email (username field) but Django don't let me do it when i try to makemigrations. myuser.MyUser: (auth.E003) 'MyUser.email' must be unique because it is named as the 'USERNAME_FIELD'. Otherwise, I want the uniqueness error to be fired on email field and not on email_hash field .... How to have functional encrypted email field as user and stored hash for index ? -
do you know how to fix undefiend error in underscore js?
error is occured in <%= edit_url %> ERROR MESSAGE: edit_url is undefined do you know why error is only one variable(<%= edit_url %>) in underscore js template i tried to slove error ex) Alphabet error checking, Template type checking etc. JSONRESPONSE if request.is_ajax(): return JsonResponse({ 'author': comment.author.username, 'text':comment.text, 'created_at':comment.created_at, 'edit_url': resolve_url('todo:edit_url', comment.id), # 'delete_id':comment.id, }) return redirect(comment.get_absolute_url()) UNDERSCORE.JS <script class="reply_template" type="text/x-template"> <tr> <td><%= author %></td> <td> <%= text %> </td> <td><%= created_at %></td> <td> <a href="" class="btn btn-sm btn-info float-right"><%= edit_url %></a> <a href="" class="btn btn-sm btn-warning float-right">delete</a> </td> </tr> </script> -
Bookmarks implementation logic django
I am developing REST API using django rest framework. Now I want to make a functionality to mark some ads as favorite. Here are some of my ideas: creating new model Favorites, containing user id and ad id. So, mobile app will be fetching them from tables. However, making table containing foreignkeys only looked not good for architecture. adding array field inside user model, and save ad ids inside. Tried using ArrayField from postgres-extensions, but I keep getting typeerror related with 'form_size'. Even though I removed 'form_size' from migrations files, as it is shown here, I get 502 error. So, should I keep using ArrayField and try to fix that error? Or creating table with 2 foreignkeys only looks not that bad? Please, If anyone faced 'form_size' typeerror, help me. Thank you. -
How to combine django-extra-views ModelFormSetView and django-filter
I try to filter the queryset of my formset in a CBV ModelFormSetView with django-filter. Looks like a classic use case to edit a model but I can't find a way to do it.