Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I limit the count of returned objects from a related manager in django
I have two models Category and Product the wanted behavior is to return all categories with and each category should include 10 products I tried to return all categories without limiting the products returned objects then I used the slice filter in the templates, but I am not sure if this is efficient for big scale and I am not sure if Django will lazy-load the products. is the way I am using is efficient or I should limit the products when querying the categories using Category.objects.all() ? -
How to change button inside a django table to text after it has been accessed
So, this is my first project with Django, and for the first time I am using the Django-Tables2. I have a Django table with three columns, last column contains add button for each row which when clicked takes me to another page where I can select options. on submitting the options, the mapping gets saved in database and user gets redirected to the tables page again. Here I want to change the "add" button to "Done". def edit_item(request, pk): item = get_object_or_404(BAReg, id=pk) if request.method == "POST": form = ProcessForm(request.POST or None, instance=item) if form.is_valid(): processes = form.cleaned_data.get('process') print(processes) for country in processes: issue = ProcessReg() issue.ba = item.ba issue.regulation = item.regulation issue.process = country issue.save() return redirect('secondpage') else: form = ProcessForm(request.POST,instance=item) return render(request, 'addbutton.html', {'form': form}) def secondpage(request): ba = request.session.get('ba') print(ba) table = PersonTable(BAReg.objects.filter(regulation=ba)) RequestConfig(request).configure(table) context = {'table': table} return render(request,'secondpage.html/',context) class PersonTable(tables.Table): Process = tables.LinkColumn('edit_item',text='Add Process', args=[A('pk')]) class Meta: model = BAReg template_name = 'django_tables2/bootstrap4.html' <form method='post' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit'> </form> {% load render_table from django_tables2 %} {% block content %} <!-- <form method="POST"> --> {% render_table table %} <!-- {{ form.as_p }} --> <!-- <button type="submit" style="margin-left: 680px">Submit</button> </form> … -
How to Fix adding a User to a Group using Django REST framework(API)
I'm trying to build a savings API where A user can get the list of groups available and join the group as long as it as not exceeded the maximum number of members. I've tried a series of approach but it seems not to work, anytime I try to add a user to a group, it seems like it trying to add the whole user properties. I made a group model and connected it to the user model via a ManytoMany field since a user can join many groups and a group can house many users. Where my problem lies in the serializer, any time I try to add a user groups.model class Groups(models.Model): name = models.CharField(max_length = 50, unique = True) group_id = models.UUIDField(default = uuid.uuid4, editable = False) max_no_members = models.PositiveIntegerField() savings_amount = models.PositiveIntegerField() savings_type = models.CharField(max_length = 10, default = 'Monthly') description = models.TextField(blank=True) begin_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True) searchable = models.BooleanField(default = True) members = models.ManyToManyField(User, related_name='group_members') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' ) def __str__(self): return self.name groups.serializer #List of Memebers class GroupMembersListSerializer(serializers.HyperlinkedModelSerializer): # users = UserSerializer(many=True, read_only = True) class Meta: model = Groups fields = ['members','name'] #Join a Group class JoinGroupSerializer(serializers.ModelSerializer): users_to_join = … -
Wagtail add custom comments feature to blog (probably with orderable)
I mean, I need something that will let me hook comments to wagtail page, probably using Orderable. I want to use this model to store comments (My users logs in using google auth, so yeah, I can handle ownership of comment): # Comment model class Comment(models.Model): text = models.TextField() author = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) As you can see below I tried to make it work like in this question, but on form sumbit it throws: AttributeError at /first-post/ 'NoneType' object has no attribute 'attname' Here's my BlogPage - Each instance of this page represents one post in blog: # Standard blog page with text/images etc. class BlogPage(Page): date = models.DateField(auto_now=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) miniature = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='miniature' ) body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ('gallery', blocks.StreamBlock( [ ('image', ImageChooserBlock()), ], label='image gallery' )), ]) content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel('miniature'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), StreamFieldPanel('body'), ] def serve(self, request): from .forms import CommentForm if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.page_id = self.id comment.save() return redirect(self.url) else: form = CommentForm() return render(request, self.template, { 'page': self, 'form': form, … -
Is it necessary to run Django behind a reverse proxy when deployed on Kubernetes
Historically, it's always been good practice to launch any wsgi app behind a reverse proxy. So, it felt natural to me, when launching on Kubernetes, to throw up a 2 container pod, one running an nginx reverse proxy, the other running the Django application. Is this just wasted resources when providing ingress via an nginx ingress controller? Is there any benefit at all to running an additional reverse proxy in this scenario? -
I'm missing something editing database record with Django and Python
I'm new to Django and Python and I want to be able to edit a database record with a model form. It is frustrating as I know I've missed something that will be obvious but I've spent hours trying to work out what it is. I've looked at some posts and they give me an idea but I've missed something in the reading. I'm running Windows 10 desktop, python 3.7. The closest post to what I'm trying to do is this one but I'm still missing something. how to edit model data using django forms (what should the XXX look like in the recommended answer) I've tried various combinations of pk in my_get_name with no success. I appreciate any help and guidance for yourselves. The error I get is: NameError at /proj1/employees/update/EMP0001 name 'EmpID' is not defined Request Method: GET Request URL: http://localhost:8000/proj1/employees/update/EMP0001 Django Version: 2.2.1 Exception Type: NameError Exception Value: name 'EmpID' is not defined and the error occurs in views.py where I define my_instance views.py from .models import emp_table from .forms import EmpDetailForm def my_get_name(request, pk): # error occurs on the next line my_instance = emp_table.objects.get(id=EmpID) if request.method == 'POST': form = EmpDetailForm(request.POST, instance=my_instance) if form.is_valid(): # process … -
Django unable to change name for url pattern
I'm trying to refactor some of my code so that it is consistent, i.e. the name: path('create_project', ProjectCreateView.as_view(), name='create-project'), I have also changed it in my template: <a href="create-project"> <img src="{% static 'project_portal/image/icon_add_circle.png' %}" alt="Add" width="32"> </a> but now I get the following: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/si/create-project/ Raised by: project_portal.views.ProjectDetailView How can changing a "_" to "-" break the code? -
Django: How to add a print button to objects to print some (special) fields of a model instance
I know this might seem to be quite similar to Django admin overriding - adding a print button The answer there is to use django-object-actions, which I already tried but it looks a bit too complex for such an simple task. I would prefer to use "just Django" I would like to create a printable view of some fields of a Django models instance. Let's say I want to print an users Name Last Name Number What I image is something like this: Clicking on a print button, shown at the list view: An preformatted and easy to print website opens which contains the data: What I have so far I added the button by using the following code: class MyModelAdmin(admin.ModelAdmin): list_display = ('number', 'name', 'last_name', ..., 'account_actions') ... def account_actions(self, obj): return format_html( '<form method="post" action="/print_view.htm"> \ <input type="hidden" name="name" value="{}"> \ <button type="submit" name="action">Print</button> \ </form>', obj.name ) account_actions.short_description = 'Actions' account_actions.allow_tags = True So my idea is to send the data which I want to get printed to another Website (via POST, on the same server). I would extract the data from the request then and create a printable view. My question is: Is it possible to … -
Server side rendering in Django does not work when view is loaded into iframe on different domain
My Django app has a view that will be loaded into iframes on different domains. To allow this I'm using @xframe_options_exempt. The static parts of the template are loaded properly in the iframes, but for some reason the parts of the template that have to be rendered are not showing up. When I load the iframe on the same origin everything works fine, so do I have to include something similar like @xframe_options_exempt as a template tag inside my template? -
deploing django app to heroku: application error
I'm trying to deploy my project to heroku. I'm new to django and heroku so I'd appreciate any help. All went smoothly up until opening the heroku app with the application error procfile web: gunicorn count_project.wsgi requirements.txt dj-database-url==0.5.0 Django==2.2 django-heroku==0.3.1 gunicorn==19.9.0 psycopg2==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 runtime.txt python-3.7.3 message after running heroku logs --tail 2019-07-30T13:03:42.277475+00:00 heroku[web.1]: Starting process with command `gunicorn count_project.wsgi` 2019-07-30T13:03:46.087651+00:00 heroku[web.1]: State changed from starting to crashed 2019-07-30T13:03:46.065132+00:00 heroku[web.1]: Process exited with status 127 2019-07-30T13:03:46.018957+00:00 app[web.1]: bash: gunicorn: command not found 2019-07-30T13:03:46.000000+00:00 app[api]: Build succeeded 2019-07-30T13:03:58.852793+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=countthewords.herokuapp.com request_id=77fd8632-f1ec-4f12-9271-3f9c42dc19d3 fwd="95.102.233.42" dyno= connect= service= status=503 bytes= protocol=https 2019-07-30T13:04:00.698445+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=countthewords.herokuapp.com request_id=f05da2fd-0222-4ef6-a005-b4dcbd0993ce fwd="95.102.233.42" dyno= connect= service= status=503 bytes= protocol=https -
How do I configure a Joomla site on the same port where a Django site is running with Apache
I am using mod_wsgi and the OS is Ubuntu 16.04. This is how my apache configuration file looks like: <VirtualHost 172.16.146.130:80> Alias /static /var/www/html/myapp/static <Directory /var/www/html/myapp/static> Require all granted </Directory> <Directory /var/www/html/myapp/inventoryms> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-home=/var/www/html/myapp/env python-path=/var/www/html/myapp WSGIProcessGroup myapp WSGIScriptAlias / /var/www/html/myapp/inventoryms/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I would like to add a Joomla site running on the same port than the Django app that has been already configured with Apache. -
Show two tables specific column data into one list?
I have two tables Customer and Subscription in which Customer has the list of customers and Subscription contains the Customer and Packages. In the customer list i want to show how many packages each customer has. Subscription Model class Subscription(models.Model): client = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True, related_name="subscriptions") package = models.ForeignKey(Package, on_delete=models.SET_NULL, blank=True, null=True) valid_start_date = models.DateTimeField() valid_end_date = models.DateTimeField() usage_count = models.IntegerField(null=True) status = models.CharField(max_length=20) transaction = models.BigIntegerField(blank=True, null=True, default=0) created_at = models.DateTimeField() updated_at = models.DateTimeField() Customer Model class Customer(AbstractBaseUser): first_name = models.CharField(max_length=250, blank=True, null=True) last_name = models.CharField(max_length=250, blank=True, null=True) email = models.EmailField(unique=True, blank=True, null=True) mobile_number = models.BigIntegerField(blank=True, null=True) password = models.CharField(max_length=1000, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) address = models.CharField(max_length=500, blank=True, null=True) country = models.ForeignKey(Countries, on_delete=models.SET_NULL, blank=True, null=True) state = models.ForeignKey(States, on_delete=models.SET_NULL, blank=True, null=True) city = models.ForeignKey(Cities, on_delete=models.SET_NULL, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) number_of_logins = models.IntegerField(blank=True, null=True) is_active = models.BooleanField(default=True) gcm = models.CharField(max_length=250, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = "email" Expected Result : I want to show the package field data from Subscription Model into the list of Customer model. Actual Result : Only Customer field data -
duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists
good day!A separate page was created to change the password, when you enter the password and repeat it and click on the "change password" button, a duplicate key value violates unique constraint "core_user_username_key" error appears DETAIL: key (username) = already exists how to solve this error? forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) initial_data = model_to_dict(patient.user) context['form'] =CallcenterPasswordChange(initial=initial_data) context['patient_pk'] = patient_pk context['patient'] = patient return context def post(self, request, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) form = CallcenterPasswordChange(request.POST) context['form_user'] = form context['patient'] = patient if form.is_valid(): form.save() else: return render(request, template_name=self.template_name, context=context) -
Exception at /openid/callback/login/ this login is not valid in this application in Django
I was trying to make an SSO using keycloak and Django application. My login is working fine as after logged into keycloak I've seen the user session is existed there. But the problem is that, it's not going to the secured page rather it's showing this error : raise Exception('this login is not valid in this application') Exception: this login is not valid in this application And if I reload this then it shows another error: OpenID Connect authentication has failed Error message is: Invalid response invalid_grant. Query content was: This is my code: settings.py INSTALLED_APPS = [ #....... 'bossoidc', 'djangooidc', 'test', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'bossoidc.backend.OpenIdConnectBackend', # ... ] auth_uri = "http://localhost:8080/auth/realms/test" client_id = "test" public_uri = "http://localhost:8000" from bossoidc.settings import * configure_oidc(auth_uri, client_id, public_uri) OIDC_PROVIDERS['KeyCloak']['behaviour']['scope'] = ['openid', 'profile', 'email'] test/views.py def index(request): return HttpResponse('index. <a href="/secure">Secure</a>') @login_required def secure(request): return HttpResponse('Secure page. <a href="/openid/logout">Logout</a>') urls.py urlpatterns = [ url(r'', include('test.urls')), url(r'^admin/', admin.site.urls), url(r'openid/', include('djangooidc.urls')) ] test/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^secure$', views.secure, name='secure'), ] I'm using this plugin for open-id connection: boss-oidc . My python version is Python 3.6.8, Django But there is also some issues after i run this install command for bossoidc pip … -
Django Max count of foreign key set
class Blog(models.Model): pass class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) b = Blog.objects.filter(...) Given b, is it possible to find with a single query the highest count of associated articles? I could do that by iterating: max_count = 0 for blog in b: if b.article_set.count() > max_count: max_count = b.article_set.count() Is there a more efficient way that uses the ORM/SQL? -
Django database access optimization: Efficient creation of many-to-many relationships (between existing objects)
I'm using Django 2.2 with a PostgreSQL database. I have two models: Gene and Annotation and need to create and link (many-to-many) thousands of Genes and Annotations at the same time. class Gene(models.Model): identifier = models.CharField(max_length=50, primary_key=True) annotation = models.ManyToManyField(Annotation) class Annotation(models.Model): name = models.CharField(max_length=120, unique=True, primary_key=True) I already found a way to create the objects very efficiently: Gene.objects.bulk_create([Gene(identifier=identifier) for identifier in gene_id_set]) This is my Django-docs-inspired way to create relationships: relationships = { 'gene1': ['anno1', 'anno2'], 'gene2': ['anno3'], ... } for gene in relationships: gene = Annotation.objects.get(pk='gene1') gene.annotation_set.set([Annotation.objects.get(pk=anno) for anno in relationships[gene]) But this is very clumsy: It hits the database 4 times! Is there not a better way, using Django-built-in-tools or raw SQL queries? The many-to-many table (myapp_gene_annotation) looks like this: id gene_id annotation_id 1 gene1 anno1 2 gene1 anno2 3 gene2 anno3 ... -
How to validate template versioned form fields in django without using django forms?
I wrote a small authentication application where i used manual template rendering. I can fetch and update data from from forms but i just want to validate the fields. But i can't move forward as i didn't use any Django form models.Client side validation is going on but what about the Server side validation. Using python v3 and Django v2 -
How to order_by related field date with annotation?
i have this model : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True) which have this related model : class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) view_date = models.DateTimeField(default=timezone.now) What i am trying to do is to order a queryset of the first model by the view date of the second one, this is the view that i have tried : last_viewed_trees = Node.objects.filter(tree_type='root').order_by('-related_views__view_date') In that one the result is correct but i have a duplicate view_date of many users. I have tried also this one without success : last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Min('related_views__views_count') ).order_by('-time_of_views') last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Max('related_views__views_count') ).order_by('-time_of_views') Nothing have worked for me, there is something that i am missing, but i cannot identify it. -
Assigning several model instances of one Model to another Model, and then comparing them?
I have a model called Hero, which has about 500 different objects. I'm having the user select 4 instances of Hero in a form, and assigning them to a Match model to register what Heroes they played with. I've tried creating a Deck model, that could contain the 4 heroes and then assign that Deck model in Match model and form, but then the user can't select a new combination, only current Deck combinations. This works fine in the adminpanel, where I can add new combinations, but the user doesn't get that opportunity. It's not quite what I want and I can't wrap my head around, is how I can then later compare two instances of Deck or the selected Heroes in Match to see if the user selected the same Heroes in their Deck/Match and/or count how many times that specific combination of Hero is used in a deck/Match. In short: What I want is for the user to, through a form, select 4 Hero objects and save them to a Deck model. If their specific combination of selected Heroes is already in Deck, then it should register it under that. I know it's confusing, but that's owing to … -
How to empty Cart After checking out or making Order?Django
I have e commerce project,I need to empty cart after user checkout and order status is "shipped also if I empty cart manually also orders already made be empty! where is the problem in code and how to separate cart and orders made? def checkout_home(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("cart:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.new_or_get(cart_obj=cart_obj,user=request.user) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, # "billing_profile": billing_profile, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) def checkout_done_view(request): Orders = Order.objects.filter(user=request.user) return render(request, "carts/checkout-done.html",{"orders":Orders}) orders.models.py class OrderManager(models.Manager): def new_or_get(self, user, cart_obj): created = False qs = self.get_queryset().filter( user=user, cart=cart_obj, active=True, status='created' ) if qs.count() == 0: obj = self.model.objects.create( user=user, cart=cart_obj) created = True else: obj = qs.first() return obj, created class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) # shipping_address_final = models.TextField(blank=True, null=True) order_id = models.CharField(max_length=120, blank=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) objects … -
Login with jwt authentication not working
I have tried creating a user login api with jwt authentication but instead of returning the token it is always returning not authorised. This code seemed to work earlier in the initial phase but now it is just not working. I have no idea what is wrong. I have added the jWT_AUTH and Authentication classes in settings.py . Please Help serializer class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField() class Meta : model = User fields = ('username','password') class TokenSerializer(serializers.Serializer): token = serializers.CharField(max_length=255) views from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class LoginView(generics.CreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = UserLoginSerializer queryset = User.objects.all() def post(self, request, *args, **kwargs): username = request.data.get("username", "") password = request.data.get("password", "") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) serializer = TokenSerializer(data={ "token": jwt_encode_handler( jwt_payload_handler(user) )}) if serializer.is_valid(): return Response(serializer.data['token']) return Response("Not Authorized",status=status.HTTP_401_UNAUTHORIZED) I cannot login even when I am using correct username and password. -
Django list of files returns an empty array
I'm starting with Django, so I'm pretty new to this. I'm sending a file to the Django server, saving it, trying to get the last file (the one I just send) from the saved folder and then I want to perform some processes on that file, after that I want to delete the original file. I already managed to upload and save the file to the filesystem, but I'm having trouble selecting this file from the folder. I'm trying select and remove it this way: @api_view(['POST', 'GET']) def geojson_to_shape_view(request): if request.method == 'POST': serializer = FileSerializer(data=request.data) if serializer.is_valid(): # serializer.save() calls .create() in serializers.py file = serializer.save() # Get last saved file print("Analyzing last posted file...") list_of_files = glob.glob('../media/temp_files/*') print(list_of_files) if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) print("Deleting last posted file...") try: os.remove(latest_file) pass except: print("Can't remove the file") return Response(FileSerializer(file).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this code returns: Analyzing last posted file... [] I tried to run a script in the same folder with these file interactions and it run with no problems, so I thinking is some django permission issue. I also tried to change the path to settings.MEDIA_ROOT + 'temp_files/*', but the problem persists. -
Django: Query with foreign key
I have two models called Thread and Post. A Thread has 0..* posts. Now, I need a query that gets all threads sorted by the datetime of the latest post in the thread. In case there is no post yet in the thread, the datetime of the thread creation is important. Honestly, I am a bit overwhelmed with the database query. Thread: created_at = DateTimeField() Post thread = ForeignKey(Thread) My current approach does not work: newest = Post.objects.filter(thread=OuterRef('pk')).order_by('-created_at') threads = Thread.objects.annotate( latest_post=Case( When(Exists(Subquery(newest.values_list('created_at')[:1])), then=Value(Subquery( newest.values_list('created_at')[:1]), ), default=Value(Thread.created_at)))).order_by('-latest_post') Can someone help me? -
Inconsistency between test and django: :int() argument must be a string but also TypeError: string indices must be integers
I have an API view that receives a request and creates some data. It works fine. When I am running my test I wrote with pytest I receive this error: node_name = (data_node['name']) TypeError: string indices must be integers When I change my code to be an integer like this: node_name = int((data_node['name'])) my django view gives me this error: :int() argument must be a string And I am like... whuat?! This is my view (shortened for brevity): @api_view(['POST']) def CreateGraphView(request): for data_node in nodes: print(type(data_node)) node_name = (data_node['name']) print(node_name) print(type(node_name)) new_node = Node.objects.create(name=node_name) status_code = HttpResponse.status_code return Response(status_code) The data (request) I am sending looks like this: {'project': 'project1', 'name': 'Graph1', 'description': 'test', 'nodes': [{'name': '25', 'graph': 3}], 'edges': [{'name': 'EdgeForGraph1', 'graph': 3, 'source': '25', 'target': '25'}]} And finally, if it helps my test (I send the same data): def test_aut_user_can_create_graph(self, client): data = data url = api_reverse('nameofurl') response = client.post(url, data) assert response.status_code == 201 I am very confused why my test wouldn't accept the code and my code wouldn't accept my test. Especially because when debugging and printing out the type of data_node it tells me it is a dict. So that should be correct. Can someone … -
Django-filter, how to make multiple fields search? (with django-filter!)
How can I make multiple fields search with Django-filter from model like: class Location(models.Model): loc = models.CharField(max_length=100, blank=True) loc_mansioned = models.CharField(max_length=100, blank=True) loc_country = models.CharField(max_length=100, blank=True) loc_modern = models.CharField(max_length=100, blank=True) I need one input field on my website, that can search over all fields of Location model