Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to verify my container that has SSL with Postgres?
I can verify my Django connection is secure by using dbshell on my OSX laptop $ python manage.py dbshell --settings=config.settings.local psql (10.11, server 11.2) WARNING: psql major version 10, server major version 11. Some psql features might not work. SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. However, on my production container does not has it /app $ python manage.py dbshell CommandError: You appear not to have the 'psql' program installed or on your path. Question: How do I know that my Django container is making encrypted connection with RDS? -
How to inner join 4 tables in Django?
we want to retrive all table records at a time how to impliment like sql quries in django orm example SQL query: select * from Company_info inner join Bank_info on Bank_info.manufacturer = Company_info.manufacturer inner join Company_info on Company_info.manufacturer = Company_info.manufacturer inner join Transport_info on Transport_info.manufacturer = Company_info.manufacturer class Manufacturer(models.Model): name = models.CharField(max_length=42) class Bank_info(models.Model): account = models.CharField(max_length=42) manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE) class Company_info(models.Model): name= models.CharField(max_length=42) manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE) class Transport_info(models.Model): name= models.CharField(max_length=42) manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE) -
django-import-export not working with mptt
I'm having and issue trying to get import-export to work for mptt models. This is my code: models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class MyModel(MPTTModel): name = models.CharField(max_length=255) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') active = models.BooleanField(default=True,null=False,blank=False) sort_order = models.PositiveIntegerField(default=0,null=True,blank=True) class MPTTMeta: order_insertion_by = ['name'] class Meta: ordering = ['sort_order'] def __str__(self): return self.name admin.py from django.contrib import admin from mptt.admin import MPTTModelAdmin, DraggableMPTTAdmin from .models import MyModel from import_export import resources from import_export.admin import ImportExportModelAdmin, ImportExportMixin class MyModelResource(resources.ModelResource): class Meta: model = MyModel exclude = ('lft','rght','tree_id','level') @admin.register(MyModel) class MyModelAdmin(ImportExportMixin, DraggableMPTTAdmin): resource_class = MyModelResource list_display = ('tree_actions','indented_title','active','sort_order') list_editable = ('active','sort_order') list_display_links = ('indented_title',) When I export it puts the name field in the parent column. When I import again it fails on the parent field: "MyModel.parent" must be a "MyModel" instance. Any help is greatly appreciated -
convert SQL query with multiple joins to Django ORM
I am new to Django and finding it impossible to convert below sql query to ORM, can any one explain me? select t1.fincode, t2.year_end, t1.type, current_gross_block, current_cwip, t1.gross_block*t1.unit as previous_gross_block, t1.CWIP*t1.unit as previous_cwip, cash_from_operation*t3.unit as cash_from_operation_ext, (((Cash_from_Operation*t3.unit)-((Current_gross_block)-(t1.gross_block*t1.unit)))) as free_cash_flow_banking, (((Cash_from_Operation*t3.unit)-((Current_gross_block + Current_cwip)-( (t1.gross_block*t1.unit) + (t1.CWIP*t1.unit) )))) as free_cash_flow_non_banking from t_balance_sheet t1 join ( select fincode, year_end, type, gross_block*unit as current_gross_block, CWIP*unit as current_cwip, (select max(year_end) from t_balance_sheet t2 where t1.fincode = t2.fincode and t2.year_end < t1.year_end ) as last_date from t_balance_sheet t1 ) t2 on t1.fincode = t2.fincode and t1.year_end = t2.last_date and t1.type = t2.type join t_cash_flow t3 on t1.fincode = t3.fincode and t2.year_end=t3.year_end and t1.type = t3.type order by fincode, year_end, type In Above there are two tables involved, but they are not related to each other. But both of them are related to another table company with fk. Any help please -
Use AJAX returned IMAGE URL from Django MEDIA folder
I'm trying to use the return an image URL via AJAX that is referenced to Django's MEDIA folder. Folder Structure website media music image.jpg music templates player.html Every field from the object works, altho I can't seem to make use of the returned image URL. views.py from django.core import serializers from django.http import JsonResponse from django.template.loader import render_to_string def change_song(request): featured_song_id = request.session['featured_song'] song_list = Song.objects.all().order_by('-date') # list of objects if request.method == "POST": request.session['featured_song'] = request.POST['song_id'] featured_song_id = request.session['featured_song'] obj = Song.objects.get(pk=featured_song_id) serialized_obj = serializers.serialize('json', [obj]) serialized_song_list = serializers.serialize('json', song_list) string_render = render_to_string('music/player.html') context = { 'html': string_render, 'obj': serialized_obj, 'song_list': serialized_song_list, } return JsonResponse(context, safe=False) AJAX/jQuery/Javascript $('a.play').click(function(e){ e.preventDefault(); var song_id = $(this).attr('id'); var this_url = $(this).attr('href'); $.ajax({ type: 'POST', url: this_url, data: { 'song_id': song_id, }, dataType: 'json', success: function(data) { obj = JSON.parse(data.obj); image = obj[0]['fields']['image']; $('.player-image').css('background', 'url("/media/' + image + '") no-repeat center; background-size: 100% 100%;'); } }); }); I also tried inside the url(): image "image" /media/ + image "/media/" + image -
"message": "'NoneType' object has no attribute 'addcategory'",
this is my views .py (trying to get data in postman) def list(self,request): try: user=sub_category.objects.all() users=[] for i in user: users.append({ 'category':i.category, 'subcategory':i.subcategory }) return Response({'data':users}) print('hello',subcategory) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) this is my models class add_category(models.Model): addcategory=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.addcategory class sub_category(models.Model): category=models.ForeignKey('add_category', on_delete=models.CASCADE,null=True,related_name='xyz') subcategory=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.subcategory -
access request arg of @api_view in custom decorator django rest framework
Access request arg inside custom decorator and decorated response if method is get otherwise do nothing how can i do that. def mapping_the_fields(func): def decorator(self, *args, **kwargs): response = func(self, *args, **kwargs) return response return decorator @mapping_the_fields @api_view(['GET']) def user_view(request, id=None): if request.method == 'GET': if id: data = get_object_or_404(User, id=id) serializer = UserSerializer(data, many=False) return Response(serializer.data) else: data = get_list_or_404(User) serializer = UserSerializer(data, many=True) return Response(serializer.data) -
Django: child models with the same properties, but different attributes on those properties
I have two models in my database that, if I don't do anything "creative" will look something like this: class AbstractModel(models.Model): uuid = models.UUIDField(default=uuid.uuid4) class Meta: abstract = True class ModelA(AbstractModel): name = models.CharField(max_length=128) class ModelB(AbstractModel): name = models.CharField(max_length=128, blank=True) The only real difference between ModelA and ModelB is that I want ModelA's name property to be non-nullable, but writing it like this, especially when you consider that I've got about 10 different fields to write in much the same situation, feels very not-DRY. Surely, there's a better/smarter way? Note that this isn't about validation, so moving the blank-checking up into a form isn't going to solve the problem. I want the database column to be NOT NULL for ModelA and NULL for ModelB. -
how to automate Import_export in Django
I am trying to automate the process of exporting data from Django/admin to google spreadsheets any leads,the application is already exporting data in csv format but it downloads directly to my computer. -
setting cookie from http to https and redirect in python django
I have a python django application, where its been deployed in http. So i have a url once you click on it i am trying to redirect to an https. I have added SECURE_SSL_REDIRECT = True in my local.py currently the redirect is happening but i am not able to set a cookie. If its a http then the cookie is setting. I have tried SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') but there was no luck The redirect application is react and node js app, i am serving the static files of create react app in node js using the below code. Using docker for building this application image. And the application is https. if (fs.existsSync(path.join(__dirname, "..", "client", "build"))) { app.use("/", express.static(path.join(__dirname, "..", "client", "build"))); app.get("/*", (req, res) => { res.sendFile(path.join(__dirname, "..", "client", "build", "index.html")); }); } Any help is appreciated -
Best practice to handle large number of concurrent users using django channels?
I have a consumer method, which runs every 15 seconds using a scheduler(apscheduler library). The purpose of this method is to send JSON data to all the users in a channel group. def auto_update(): group_name = 'auto_update' channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'auto_update', # this is the name of my consumer method which return json data } ) I have deployed Django-channels on the daphne server(as API server) and the Apache server is to serve HTTP/HTTPS requests. When concurrent users increase more than 50(approx value), the next users are not able to receive data. Getting 403 handshake error. What is the best practice for this scenario? Here, I need to only send data to a large group(more 350-460 concurrent users). -
queryset in django M2M signals returns none
This is such an unusual behavior that I have seen. So, I have a model with a many-to-many field and another model associated with this field as shown below. I am using Razorpay Python SDK to create invoice. The data is structured as per this documentation. My idea is when the user fills the form in the frontend these items should be added as line_items and then create invoice must be called client.invoice.create(data=data) in signals.py. However, everything works fine until I add this line of code client.invoice.create(data=data) and all of a sudden queryset returns None. Output as shown below. models.py class Product(models.Model): name = models.CharField(max_length=30, unique=True) price = models.DecimalField(max_digits=19, decimal_places=2, blank=False) def __str__(self): return str(self.name) class Billing(models.Model): invoice_name = models.CharField(max_length=50) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) product = models.ManyToManyField(Product) def __str__(self): return str(self.invoice_name) signals.py import razorpay client = razorpay.Client(auth=(settings.rzp_key_id, settings.rzp_key_secret)) client.set_app_details({"title": "Test App", "version": "1.0"}) def save_invoice(sender, instance, **kwargs): data = { "type": "invoice", "currency": "INR", "customer": { "email": instance.organization.user.email, "billing_address": { "line1": instance.organization.address_line1, "city": instance.organization.city, "state": instance.organization.state, "zipcode": instance.organization.zipcode, "country": instance.organization.country } }, "line_items": [] } name = Product.objects.filter(billing__timestamp=instance.timestamp).values('name') price = Product.objects.filter(billing__timestamp=instance.timestamp).values('price') print(name) print(price) for item, amount in zip(name, price): data_new = { "name": item['name'], "amount": float(amount['price']), "currency": … -
django | expected str, bytes or os.PathLike object, not InMemoryUploadedFile
I want to try to retrieve the path of the user uploaded image and I will continue to encode base64 to parse the result of api, and I am trapped in this error, I found this error in my django project. File "/root/wibuzone/tool/module/LookAnimeInfoWithImage.py", line 11, in request self.data = {'image':base64.b64encode(open(self.path,'rb').read())} TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile forms.py class LaiwiForm(forms.Form): browse_a_file = forms.ImageField( required=False, widget=forms.FileInput( attrs={ 'class':'form-control', }, ), ) image_url = forms.CharField( max_length=200, required=False, widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Image Url' } ) ) views.py class laiwi(FormView): form_class = LaiwiForm template_name = "tool/laiwi.html" def post(self,request): if request.method == "POST" or "post": if len(request.FILES['browse_a_file']) == 0: pass else: imageFile = request.FILES['browse_a_file'] print (LookAnimeInfoWithImage.imagefile(imageFile)) return render(request,'tool/result/laiwi.html') template, laiwi.html {% block content %} <img src="{% static 'img/thumbnail/tool/laiwi.jpg' %}" class="img-thumbnail"> <br><br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <small class="form-text text-muted" style="padding-left:0.2em">masukan potongan gambar anime / hasil screenshot</small> {{form.browse_a_file}} <small class="form-text text-muted" style="padding-left:0.2">atau gunakan live url image</small> {{form.image_url}} </div> <button type="sumbit" class="btn btn-primary">search</button></form>{% endblock content %} -
django deploy changes in settings.py
I have a small problem with Django settings. In my page I have some really big input and I got the error: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. took me about 3sec google to find a solution DATA_UPLOAD_MAX_NUMBER_FIELDS = None # None so it ignores the error -> change to big number results in the same error In my local develop it works like a charm. On the server I did the same and after that: service apache2 restart but i still get the error. Any ideas? -
Upgrading django from 1.8 to 2.2.0
Im upgrading my django project from 1.8 to 2.2.0(Using Python 3.6 from virtualenv). I have done the below changes. Added on_delete to all the Foreign Key fields Changed the url reverse import as from django.urls import reverse Included path/re_path instead of url in all the app's url files. Changed the MIDDLEWARE_CLASSES import in settings files to MIDDLEWARE = {} I tried to run the server, still it says "TypeError: init() missing 1 required positional argument: 'on_delete' and it is pointing to /usr2/santhosh/myproject/myapp/migrations/0002_abc.py What should I do now? Do I need to delete all the migration files from the app and re-run python manage.py migrate or what?? Help me you are aware. -
Django: How to call a view function at a specific time
I'm wondering if there's a way to call a particular view function at a specific time, specified by a DateTimeField feature of a model. Here's what I'm working with: Currently, the relevant model looks like this: class Market(models.Model): title = models.CharField(max_length=50, default="") current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.50) description = models.TextField(default="") [...] # A number of features not relevant to the question def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) In one of my templates, I then have a form as follows: <form action="{% url 'resolve' market.id %}" method="post"> {% csrf_token %} <input type="submit" name="resolve" class="btn btn-danger btn-sm" value="Close" /> </form> The relevant part of the url pattern is this: urlpatterns = [ [...] path('<int:pk>/resolve/', views.resolve, name='resolve'), ] And the view function in question looks like this: def resolve(request, pk): market = get_object_or_404(Market, pk=pk) # Some things are done to the market market.save() return HttpResponseRedirect('/' + str(pk)) Here's what I'm trying to achieve: Say that I added a feature to the Market model like so: class Market(models.Model): [...] resolves_at = models.DateTimeField( null=True, default=None ) [...] Once I created a new market, I would then want the resolve function in the view to be called with that market's pk at the … -
Create nested dictionary from queryset
my queryset output is [{'ID': 61, 'CAMP_DETAIL_ID': 1462, 'CAMP_START': datetime.datetime(2020, 1, 1, 0, 0), 'CAMP_END': datetime.datetime(2020, 2, 1, 0, 0), 'ISACTIVE': 1, 'ACTIVETRACKING': 1, 'TRACKINGCYCLE': 5, 'MAILSUBJECT': 'MCBAH Testing Campaign', 'CAMPAIGN_CODE': 'Testing', 'CAMPAIGN_DESCRIPTION': 'First Testing Campaign', 'ACCOUNT_SNO': 1810028081, 'CUSTOMER_EMAIL': 'm.fawadkhalid@gmail.com', 'MOBILE_NO': '923000704342', 'ACCOUNT_NAME': 'MOHAMMAD FAWAD KHALID', 'MAILSTATUS_APP': 'D', 'CAMPAIGN_OBJECTIVE_ID': 2, 'OBJECTIVE': 'SIP Payment', 'CAMPAIGN_DOCS_ID': 121, 'DOCUMENT': 'App_download_urdu_1.html', 'LAST_CYCLE': '2'}] I need to convert above list as follows: [{'ID': 61 ,'DATA':{'CAMP_DETAIL_ID': 1462, 'CAMP_START': datetime.datetime(2020, 1, 1, 0, 0), 'CAMP_END': datetime.datetime(2020, 2, 1, 0, 0), 'ISACTIVE': 1, 'ACTIVETRACKING': 1, 'TRACKINGCYCLE': 5, 'MAILSUBJECT': 'MCBAH Testing Campaign', 'CAMPAIGN_CODE': 'Testing', 'CAMPAIGN_DESCRIPTION': 'First Testing Campaign', 'ACCOUNT_SNO': 1810028081, 'CUSTOMER_EMAIL': 'm.fawadkhalid@gmail.com', 'MOBILE_NO': '923000704342', 'ACCOUNT_NAME': 'MOHAMMAD FAWAD KHALID', 'MAILSTATUS_APP': 'D', 'CAMPAIGN_OBJECTIVE_ID': 2, 'OBJECTIVE': 'SIP Payment', 'CAMPAIGN_DOCS_ID': 121, 'DOCUMENT': 'App_download_urdu_1.html', 'LAST_CYCLE': '2'}}] I tried to convert this as follows but in vain. from collections import defaultdict qr_dict = defaultdict(list) for qr in query_result: qr_dict[qr.ID].append(qr.qr) I am suffering with following error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-86-f76fa64c419a> in <module> 3 qr_dict = defaultdict(list) 4 for qr in query_result: ----> 5 qr_dict[qr.ID].append(qr.qr) 6 7 AttributeError: 'dict' object has no attribute 'ID' -
RelatedObjectDoesNotExist at /signup/ . User has no profile
i am getting error while signing up, it's throwing me error that, RelatedObjectDoesNotExist at /signup/ . User has no profile. i am getting error while signing up, it's throwing me error that, RelatedObjectDoesNotExist at /signup/ . User has no profile. RelatedObjectDoesNotExist at /signup/ . User has no profile. models.py class Profile(models.Model): """ Model that represents a profile. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) dp = models.ImageField(upload_to='dps/', blank=True, null=True) member_since = models.DateTimeField(default=timezone.now) email_confirmed = models.BooleanField(default=False) class Meta: ordering = ('-member_since', ) def __str__(self): """Unicode representation for a profile model.""" return self.user.username def screen_name(self): """Returns screen name.""" try: if self.user.get_full_name(): return self.user.get_full_name() else: return self.user.username except: # noqa: E722 return self.user.username def get_picture(self): """Returns profile picture url (if any).""" default_picture = settings.STATIC_URL + 'admin/staff/default.jpg' if self.dp: return self.dp.url else: return default_picture forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=100, ) username = forms.CharField(label='Username', max_length=30, min_length=1, ) class Meta: model = User fields = ('username', 'email',) views.py def signup(request): form_filling = True if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Verify Your Deebaco Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: … -
Running Celery tasks for 2 Django applications within a same project?
I have a Django project which requires Celery tasks to run for two of its apps. I was wondering if there was a way to have a single celery.py file which runs both of them. File tree: src |--api | |-- init.py | |-- otherFiles | |-- celery | |-- celery.py | |--xyz | |-- init.py | |-- otherFiles | |-- celery | |-- celery.py | |--otherApps If I were to run to Celery apps manually, I would run: source venv/bin/activate cd src celery worker -A api And in another terminal: source venv/bin/activate cd src celery worker -A xyz The two celery workers require access to the same databases. This is how my celery file looks like: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings") app = Celery("api") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The other replaces app = Celery('api') with app = Celery('xyz'). Is this the correct way to handle this? Can I create a single script and run both tasks from it? If not, what's the best way to daemonize this? Production server is running Ubuntu 18.04 and python 3.6.9, so I'm planning on using systemd although suggestions are welcome too. -
Django problem with movie types not displaying
Hi Stackoverflow people, you will help in the following matters. My models: class Movie(models.Model): HORROR = 1 COMEDY = 2 SCI_FI = 3 DRAMA = 4 ANIMATION = 5 EDUCATION = 6 THRILLER = 7 MUSICAL = 8 WAR = 9 HISTORICAL = 10 ROMANCE = 11 SPORTS = 12 WESTERN = 13 DOCUMENTARY = 14 NONE = 0 types = ( (HORROR, 'Horror'), (COMEDY, 'Comedy'), (SCI_FI, 'Sci-Fi'), (DRAMA, 'Drama'), (ANIMATION, 'Animation'), (EDUCATION, 'Education'), (THRILLER, 'Thriller'), (MUSICAL, 'Musical'), (WAR, 'War'), (HISTORICAL, 'Historical'), (ROMANCE, 'Romance'), (SPORTS, 'Sports'), (WESTERN, 'Western'), (DOCUMENTARY, 'Documentary'), (None, 'No information'), ) name = models.CharField(max_length=100, unique=True) type = models.IntegerField(choices=types, default=0) def __str__(self): return self.name My urls: path('moreDirectors/<int:id>/', views.DirectorsDetail, name='DirectorsDetail') path('Types/movie/<int:type_id>/', views.TypeMovies, name='TypeMovies'), My views: @login_required def TypeMovies(request, type_id): movie = Movie.objects.filter(type=type_id) return render(request, 'MyPage/MovieDetail.html', {'movie': movie}) @login_required def AllMovies(request): movie = Movie.objects.all() return render(request, 'MyPage/AllMovies.html', { 'movie': movie, 'type': Movie.types }), My templates: <ul class="movieCategories"> {% for type in type %} <li><a href="{% url 'MyPage:MovieDetail' type.0 %}"><h4>{{ type.1 }}</h4></a></li> {% endfor %} </ul> in templates I also tried {% url 'MyPage: MovieDetail' movie.id%} and movie.type.id And I am only afraid that it was not found The problem is that I have a list of film genres and when … -
How to get multiple values selected from the drop down to views.py
Am using the following code: index.html <div class="col-sm-3" style="margin-left: 30px;"> <select id="month" name="month" multiple> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> </div> Views.py def internal(request): try: year = '' month = [] year = request.GET.get('year') month = request.GET.get('month') print(month) response_list = [] except Exception as e: print(str(e)) return HttpResponse(json.dumps(response_list)) I am selecting more than one value in the front-end but when I fetch it in views.py only one options is getting fetched. How do I fetch all the values selected from dropdown Thanks for your help in advance! -
django-filter with DRF does not JOIN filter fields
Hi I'm having a weird issue with using 'django-filter' alongside the Django Rest Framework to filter an API. If I use the following queryset it works as expected: queryset = Project.objects.filter(assignments__user=self.request.user,assignments__role__name="Manager") My Projects model has a ManyToMany relationship with Assignments. Each assignment has a user field (FK to User model) and a role field (FK to a ProjectRole model). When I run this queryset I get back all Projects where the current user is assigned AND the role is Manager. When I try to acheive the same with the django-filters plugin however, it seems like I get back an OR joined expression (even though this should not be the default behaviour): class ProjectFilter(django_filters.FilterSet): class Meta: model = Project fields = ('assignments__role__name','assignments__user') class ProjectViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): queryset = Project.objects.all() return queryset serializer_class = ProjectSerializer filter_backends = [DjangoFilterBackend] filterset_class = ProjectFilter I setup two filter fields for user and role, but I get back every Project where EITHER the user is assigned (with any role) OR he is the Manager of. -
Adjust the appearance of the automatically created django input form
I have created an input form. form.py looks like this: class cls_ItemForm(forms.ModelForm): class Meta: model = cls_item fields = ['item_name', 'item_count'] labels = { 'item_name': 'item_name', 'item_count': 'item_count'} and the view.py like this: def newitem_view(request): aitemform = cls_item() return render(request, 'item/newitemform.html', {'aitemform ': aitemform }) def itemrequest(request): # here came the request from the button print(request.POST) print(request.POST.getlist('item_name')) item = cls_item(request.POST) print(item.item_name) return render(request, 'item/newitemform.html', {'aitemform ': aitemform }) # for testing the html script: <form class="form-inline" action ="{% url 'item:newitem' %}" method="post"> {% bootstrap_form ObjektEingabeForm layout='inline' %} {% csrf_token %} <button type="submit" class="btn btn-primary">create item</button> </form> now i have the problem that all input fields are directly under one another. So there is no space between the fields. how can i change the look? therefore I have modified the html script as follows: <form class="form-inline" action ="{% url 'item:newitem' %}" method="post"> {% for field in aitemform %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">{{ field.label_tag }}</span> </div> <input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default" id={{ field.name }}> </div> {% endfor %} {% csrf_token %} <button type="submit" class="btn btn-primary">create item</button> </form> Now the optics are of course the way I would like them to be. but the return of the values does not … -
Filtering Conditions in Python Serializer
I am trying to use a serializer to get all venues within a model that matches a boolean condition in its model. I am trying to get all venues that match the condition is "is Sponsored." Here is what I have so far: Model class Venue(models.Model): venue_name = models.CharField(max_length=500, blank=False) venue_photo = models.ImageField(upload_to= ‘venue_photo/', blank=False, default='') venue_logo = models.ImageField(upload_to= ‘venue_logo/', blank=False, default='') description = models.CharField(max_length=250, blank=True) phone = models.CharField(max_length=500, blank=True) ratings = models.FloatField(default="0.0", blank=True) sponsored_venue = models.BooleanField(default=False) signup = models.DateTimeField(default = timezone.now) last_signin = models.DateTimeField(default = timezone.now) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘venue') Serializer class VenueSerializer(serializers.ModelSerializer): venue_logo = serializers.SerializerMethodField() venue_photo = serializers.SerializerMethodField() opening_hours = OpeningHoursSerializer( many=True, source='openinghours_set', read_only=True) # shows these fields from each venue signed up def get_venue_logo(self, venue): request = self.context.get('request') venue_logo_url = venue.venue_logo.url if venue_logo_url: return request.build_absolute_uri(venue_logo_url) return "" def get_venue_photo(self, venue): request = self.context.get('request') venue_photo_url = venue.venue_photo.url if venue_photo_url: return request.build_absolute_uri(venue_photo_url) return "" class Meta: model = venue fields = ("id", "venue_name", "phone", "street_address", "venue_logo", "venue_photo", "street_address", "city", "state", "zip_Code", "lat", "lng", 'latlng', 'opening_hours', "ratings") -
DRF: Create custom permission classes
I have designed my own RBAC system for my Django app. Unlike the original Django's role-based that uses only permissions, content_types, groups, and users table, I designed mine so that it includes a model for defined operations (i.e. read, write, print), the objects (i.e. Post, Events, Documents), the roles (Writer Level 1, Events Manager) and the necessary relationships i.e. my own permissions table which takes in the object reference and a matching operation reference (i.e. Post | add). My problem now is I am not quite sure how to implement this in DRF. When I use permission_class = (DjangoObjectPermissions,) and someone sends a 'POST' request to the Post model/table, we all know Django will check if the user has Can add post permission. I want to do this as well but I want Django to refer to my RBAC models/tables. I want to write my own permission classes in my permissions.py but I might need a bit hint on how to implement this.