Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Twilio package giving me a 403 forbidden when using "twilio_view" decorator
I'm using the @twilio_view from the django-twilio package. Here is code I want to be working: @twilio_view def new_sms(request): if request.method == "POST": ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) message_confirmation = "Hopefully this test works." resp = MessagingResponse() resp.message(message_confirmation) return HttpResponse(str(resp), content_type='text/xml') My settings are DEBUG = False & DEBUG_PROPAGATE_EXCEPTIONS = False & DJANGO_TWILIO_FORGERY_PROTECTION = True I tried to troubleshoot by reading this https://django-twilio.readthedocs.io/en/latest/gotchas.html#help-i-get-http-403-forbidden I am using ngrok.io to test the webhook and continue to get a 403 when using the @twilio_view decorator, when I instead use @csrf_exempt, code executes successfully. How can I get this code working when DJANGO_TWILIO_FORGERY_PROTECTION is True. I am using django-twilio version 0.13.0.post1 Django 2.2 and Twilio 6.37.0 -
Control multiple range sliders Django form
What I want: Multiple Range sliders (the number changes based on user selections) on one page, moving the sliders should update the value and display this in a span element as well as update the model. The problem: Unfortunately I don't know how to change the values of sliders when there are multiple sliders that are created with a forloop. The span element does not get update and the value element of the slider also does not change when I move the slider handle of a slider. Html: <form method="post"> {{ formset.management_form }} {% for form in formset %} <div class="custom-slider-container"> <label>{{ form.name.value }}</label> <span id="demo-{{ forloop.counter }}" class="range-val"></span> {{ form.weight }} </div> {% endfor %} </form> Views.py: initial = Driver.objects.filter(simulation=chosenSim, type='KEY_OUTPUT') formset = sliders_formset(request.POST or None, queryset=initial) if 'sliders_confirm' in request.POST: if formset.is_valid(): instances = formset.save(commit=False) for form in instances: form.save() return HttpResponseRedirect(request.path_info) Forms.py sliders_formset = modelformset_factory(Driver, fields=['name', 'weight'], extra=0, widgets={'weight': RangeInput(attrs={'class': 'custom-slider', 'max': 20})}) script: (I know this is incorrect, but I was playing around abit to see what would happen) <script> var sliders = document.getElementsByClassName("custom-slider"); for (i=1; i<sliders.length; i++) { var slider = document.getElementById("myRange-"+(i)); var slider_val = document.getElementById("myRange-"+(i)).value; var output = document.getElementById("demo-"+(i)); output.innerHTML = slider_val; slider.oninput = … -
Django admin: get_actions is executed 3 times
I have a Django 2.0 app. The code goes like this: a model MyModel which is registered in admin with MyModelAdmin class, inline element added to the model in list view in admin which contains a submit button ( POST ) and a select dropdown. overloaded get_actions method in the same admin class which does not do anything, just prints a message that it has been executed. class MyModelAdmin(<superclass>): list_display = ["field_1", "reserve", ..., "fiend_n"] def reserve(self, my_object): button = '<button type="submit" name="btn_%s" class="btn">Reserve</button></form>' % my_object.id name = 'reserve_%s' % my_object.id reserve_select_widget = MyOtherModel(choices=choices, name=name, id=my_object.id) reserve_select_widget.prefix = my_object.id form_string = reserve_select_widget.as_p() + mark_safe(button) return form_string def get_actions(self, request): actions = super().get_actions(request) print("IN get_actions") return actions All this works as expected, besides one thing: get_action gets executed 3 times on submit button click (I see the output of the print statement 3 times, and whatever else I add to it gets executed 3 times also). 3 is not a number of the records in the DB for MyModel or MyOtherModel (it's the same "3 times" behaviour for any number of records, including case of empty table for MyOtherModel). It's not a number of records displayed on the screen, it's not … -
How to count occurrences in Django query and return list with attribute
I want to run a query, and return a list containing unique object name and their frequency. I have come across a few posts explaining this, but can't seem to fund one that utilizes the object name attribute. for example: powderList = Build.objects.values('powder').annotate(total_count=Count('powder')).order_by('total_count') returns: {'powder': None, 'total_count': 0}, {'powder': 1, 'total_count': 2}, {'powder': 2, 'total_count': 2} Which is very close to what I want, however this is displaying the id of powder. I would like to access an attribute of powder (powder.name) so that it would output instead: {'powder': None, 'total_count': 0}, {'powder': Titanium, 'total_count': 2}, {'powder': Steel, 'total_count': 2} I have tried: powderList = Build.objects.values('powder.name').annotate(total_count=Count('powder')).order_by('total_count') powderList = Build.objects.values('powder').annotate(total_count=Count('powder.name')).order_by('total_count') My next plan is to use a for loop to itterate through the dict and find the name using the id, but this will be hitting the database everytime. Is there a more efficient proper way to do this? My models look like this: class Build(models.Model): #(DMLS) PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) plannedAuthor = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE) powder = models.ForeignKey('Powder', null=True, blank=True, on_delete=models.CASCADE) class Powder(models.Model): PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=50,) -
How can I make my signals work and resolve this problem?
Hi I'm trying to develop a website for an online store and I don't know why, for some reason, my models.py and signals.py are not coming into affect. When I ran the makemigrations command, it was ok, but when I ran the migrate command, it said "No migrations to apply". As a result, when I'm logging into my admin page, I'm getting an error, i.e OperationalError at /admin/accounts/userstripe/ no such table: accounts_userstripe What can I do now? Can anyone please help me out? My models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) My signals.py: import stripe from django.conf import settings from django.contrib.auth.signals import user_logged_in from .models import UserStripe stripe.api_key = settings.STRIPE_SECRET_KEY def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id print user.UserStripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email), ) new_user_stripe = UserStripe.objects.create( user = user, stripe_id = customer.id, ) except: pass user_logged_in.connect(get_or_create_stripe) -
RelatedObjectDoesNotExist at /users/. I am trying to make user relation but it's not working properly.
class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name If I remove orders = request.user.customer.order_set.all() from views.py @login_required(login_url='login') @allowed_user(allowed_roles=['customer']) def users(request): orders = request.user.customer.order_set.all() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders': orders, 'total_orders': total_orders, 'Delivered': delivered, 'Pending': pending} return render(request, 'accounts/users.html', context) -
Embeded pdf File is not displaying in Django
I was trying to display and photos and pdf files in a django project using but pdf file is not displaying Here is what i was doing This is view function @login_required def view_documents(request): students = Student.objects.filter(user=request.user) return render(request, 'student/view_documents.html',{'students':students}) and then I used for tag in template {% for student in students %} #lines of code {% endfor %} and to display the pdf file i have used <embed src="{{student.adhar_card_pdf.url}}" width="800px" height="400px" type="application/pdf"/> but it was showing some kind of error like localhost refused to connect i also used iframe <iframe src="{{student.adhar_card_pdf}}" style="width:718px; height:700px;" frameborder="0"></iframe> But image is displaying in the browser using same code without any error <embed src="{{student.photo_jpg.url}}" width="230px" height="250px" /> Why pdf file is not displaying ?? Please help me Thanx in advance. This is how it is displaying pdf -
How to validate document(pdf) in the InlineFormSetFactory for the test case in Django
forms.py class TestDocumentInline(InlineFormSetFactory): model = TestDocument fields = ['document_test_type', 'test_notes', 'test_document'] factory_kwargs = {'extra': 1, 'can_delete': True} test_forms.py @pytest.mark.django_db class DocumentInlineTest(TestCase): def test_valid_testdocument(self): test_inline = TestDocumentInline(request=self.factory, instance=self.test, parent_model=Test) test_formset = test_inline.get_formset() formset = test_formset({ 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '2', 'form-0-document_test_type': "Test", 'form-0-test_notes': "test_notes", 'form-0-test_document': "dir/testDoc.pdf", }, prefix="form") self.assertTrue(formset.is_valid()) How to validate document(pdf) in the InlineFormSetFactory for the test case in Django Currently, testcase getting falied in 'form-0-test_document': "dir/testDoc.pdf", -
Django html IF statement not comparing model variables
Trying to nest an IF statement in FOR loops to segment videos by a parent variable. However, my if statement doesn't seem to be recognising matches. I can confirm that both output some matching numbers in their respective statements individually. Not sure what I'm missing here, any help would be appreciated. Profile.html {% for x in source %} <div class="content-section"> <div class="media-body"> <h2 class="account-heading">{{ x.video_id }}</h2> {% for y in records %} <h1 class="text-secondary">{{ y.sourcevideo.video_id }}</h1> {% if '{{ x.video_id }}' == '{{ y.sourcevideo.video_id }}' %} <video width="320" height="240" controls> <source src="{{ y.highlight }}" type="video/mp4"> Your browser does not support the video tag </video> {% else %} <h1 class="text-secondary">No Matches</h1> {% endif %} {% endfor %} </div> </div> {% endfor %} views.py class ProfileView(ListView): model = Highlight template_name = 'users/profile.html' context_object_name = 'records' ordering = ['-date_created'] @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_queryset(self): return Highlight.objects.filter(creator=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['source'] = Video.objects.filter(creator=self.request.user) return context -
How to with url parameters from two models?
I want to create real time chat with channels, and i should put parameters to my RoomDetail from 2 models to use them in the urls like path('<str:room_name>/<str:person_name>/',RoomDetail.as_view(),name='showchat') how to add additional User model to get username parameter and put it to my url? views.py class RoomDetail(DetailView): model = Room template_name = 'rooms/room_detail.html' context_object_name = 'room_detail' slug_field = 'invite_url' slug_url_kwarg = 'url' consumers.py class Consumer(WebsocketConsumer): def connect(self): self.person_name=self.scope['url_route']['kwargs']['person_name'] self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Joined Chat" } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.person_name+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) -
Disabled field causes form validation error in Django
There is a case where I need to reuse the same ModelForm (The name's EngagementForm) in several cases, but wanted to disable some of the fields depends on the case. So I applied disabled inside my forms.py: # Override Field Initialisation, used for disabling fields def __init__(self, *args, **kwargs): schedule_check = kwargs.pop('schedule', False) super(EngagementForm, self).__init__(*args, **kwargs) # If schedule argument set to True, disable the following fields if schedule_check: fields = ( 'project_code', 'project_name', 'user_credential', ) for i in fields: self.fields[i].disabled = True self.fields[i].required = False However, Django throws validation error when I perform submit. The form.is_valid() returns False, and while inspecting errors using Pdb I saw this: (Pdb) form.errors {'project_code': ['This field is required.'], 'project_name': ['This field is required.'], 'user_credential': ['This field is required.']} Check for their values, seems like disabled took away their values (or I might wrong here): (Pdb) form['project_code'].value() (Pdb) I've tried few solutions found online (including feeding in initial values for each fields) yet none of these could fix the issue here. FYI, this is the code in views.py: def schedule_form(request, pk): engagement = get_object_or_404(Engagement, pk=pk) if request.method == "GET": context = { 'title': "Schedule Task", 'form': EngagementForm( instance=engagement, schedule=True, ), } return render(request, 'forms/engagement_form.html', … -
Django query - using values on a fk returns the ID, how I can return __str__ instead (without specifying field name)
I'm using query set values to to return some field data, and currently when I use values to return a FK it returns the FK ID and not str I know I can return the value by using site__site_type__name but I dont want to do that in this particular use case I need to just use site__site_type and hopefully get name? example using the FK >>> device_data.values('site__{}'.format(name)) <QuerySet [{'site__site_type': 4}]> example using the name >>> device_data.values('site__{}__name'.format(name)) <QuerySet [{'site__site_type__name': 'Office'}]> >>> str is set on model class SiteType(models.Model): name = models.CharField(max_length=50) plural = models.CharField(max_length=50) icon = models.CharField(max_length=50) color = models.CharField(max_length=50) class Meta: ordering = ('name',) verbose_name = "Site Type" verbose_name_plural = "Site Types" def __str__(self): return self.name class Site(models.Model): location = models.CharField(max_length=50) ref = models.CharField(max_length=255, blank=True, null=True) site_type = models.ForeignKey(SiteType, verbose_name="Site Type", on_delete=models.CASCADE) -
remove (* char) from the required field label in form
I'm trying to change the label of the fields that are required in django form using labels in Meta class . so after writing the code using this doc , i have a problem because the name of the field changes but the -> * character <- stays there . Code : from django.utils.translation import gettext_lazy as _ class Meta: model = ... fields = ... widgets = ... labels = { 'email': _('email (necessary)'), 'username': _('name (necessary)'), # the result of this -> name(necessary)* } so , how can I remove this annoying * ? -
How to have a django model Textfield contain variables
so assume there is a model A and Django template template.html and there's a variable x which will be rendered to the template class A (models.Model): description = models.TextField() Now how can I create an object through django admin which will have to use the variable x which will be later rendered to the django template. django template will look like below <HTML> <head> </head> <body> <div>{{ a.description }}</div> </body> </HTML> object a and x is rendered to the template. Description may look like This is the description with value of x equal to <value_of_x> -
Why doesn't the Django formset appear?
I have one form and one formset on the same page. Prior to my deletion of information from django admin, I could see both the form and the formset. After I deleted some 'patient' information and updated my css file, the formset stopped showing. views.py def patient_new(request): patientForm = PatientForm() formset = LocationFormSet() if request.method == "POST": patientForm = PatientForm(request.POST) formset = LocationFormSet(request.POST) if patientForm.is_valid() and formset.is_valid(): patient = patientForm.save(commit=True) for form in formset: location = form.save(commit=False) location.patient = patient location.save() return index(request) else: print('ERROR FORM INVALID') return render(request, 'covidapp/patient_new.html',{'patientForm':patientForm, 'formset':formset}) html file <form class="form-horizontal" method="POST"> {% csrf_token %} <div class="jumbotron"> <div class="row spacer"> <div class="col-2"> <div class="input-group"> {{ patientForm.as_p }} </div> </div> </div> {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="col-6"> <div class="input-group"> {{ form.as_p }} <div class="input-group-append"> <button type="button" class="btn btn-success add-form-row">+</button> </div> </div> </div> </div> {% endfor %} <div class="row spacer"> <div class="col-4 offset-2"></div> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> html output I am not sure whether the hidden input is supposed to be my formset and why it is hidden. -
Unexpected behaviour using a shell script to run a command in python shell
I'm attempting to write a script for the initial setup of superuser in django. I have a docker container running django. docker exec -it "mydockername" bash -c echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('root3', 'admin3@myproject.com', 'root3')" | python manage.py shell This script is throwing an error File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax But if I execute the command echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('root3', 'admin3@myproject.com', 'root3')" | python manage.py shell inside of the docker container I don't have any problems and the superuser is created. -
how to create autocomplete using function-based view
I am trying to create autocomplete. I have an input field (class Coordinate) where code is required to input. Also i have static file (class Profiles). the idea is that when i type code it goes to class Profile and matches with geocode and hence can find country name based on code. I want to create autocomplete for input field so when i type code it brings suggestions based on country. For example: code input 011 equals to United Kingdom in class Profiles and etc. In models.py i have: class Coordinate(models.Model): code = models.CharField(max_length=150) class Profiles(models.Model): geocode=models.CharField(max_length=200) country=models.CharField(max_length=500) class Meta: managed=False db_table='profiles_country' def __str__(self): return '{}'.format(self.geocode) class Year19(models.Model): geocode=models.CharField(max_length=200) longitute=models.CharField(max_length=500) latitude=models.CharField(max_length=500) class Meta: managed=False db_table='year19' in forms.py: from dal import autocomplete class CoordinateForm(forms.ModelForm): code= forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Coordinate fields = ('__all__') widgets = { 'country': autocomplete.ModelSelect2(url='coordinate-autocomplete', attrs={ 'theme': 'bootstrap'})} def clean_code(self): code=self.cleaned_data.get("code") if not Profiles.objects.filter(geocode=code).exists(): raise forms.ValidationError ( "Not true") return code in views.py: from dal import autocomplete def geoview(request): form = CoordinateForm(request.POST or None) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) code = form1.code dataview=Profiles.objects.get(geocode=code) year19=Companies_data_2019.objects.get(geocode=code) context={'geodata':dataview ,} return render(request, 'cgeo/result.html', context) return render(request, 'cgeo/search.html', context={'form':form}) functon based view for autocomplete : def … -
Django - 'AnonymousUser' object is not iterable
Getting an error for AnonymousUser. What I code here is only for the authenticated user. But an unauthenticated user cannot add a product. I want to work it like, if user comes to the website and clicks on add to cart the product should be added to the cart. Then when he tries to sign in. The products should be in the cart. cart models.py # Create your models here. class CartItem(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f"{self.quantity} of {self.item.name}" def pre_save_cart_item(sender, instance, *args, **kwargs): instance.item_total = instance.quantity * instance.item.price pre_save.connect(pre_save_cart_item, sender=CartItem) class Cart(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='cart') items = models.ManyToManyField(CartItem) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) purchased = models.BooleanField(default=False) def __str__(self): return f"User: {self.owner}, items in cart {self.number_of_items}" def m2m_save_cart(sender, action, instance, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': instance.number_of_items = instance.items.count() items = instance.items.all() instance.total = 0 for x in items: instance.total += x.item_total instance.save() m2m_changed.connect(m2m_save_cart, sender=Cart.items.through) cart views.py # Create your views here. def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) cart_item, created = … -
docker-compose resets django db when requirements.txt change
I'm using docker-compose to develop a django project with postgres db. Using VS Code, I get two dockers running after Docker Compose Up. Every time I work on the project, the db is intact The issue is when any changes are made to requirements.txt, the db image resets, even though no changes were made to that image. I have to run python manage.py migrate and createsuperuser and the db is empty. I can understand that the web docker image must be recreated when there are changes to requirements.txt, but why does the db image resets? Is there a way to avoid this? I would hate to publish the production app and not be able to install additional libs in newer versions without losing the db. docker-compose.yml: version: '3' services: db: image: postgres environment: POSTGRES_USER: 'aaa' POSTGRES_PASSWORD: 'aaa' POSTGRES_DB: 'aaa' web: build: . volumes: - .:/code ports: - "8000:8000" depends_on: - db stdin_open: true tty: true Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ -
Send data to a Django channels consumer
I have the following basic Django Channels consumer: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('Connected!') And, in parallel, i have a normal Python script which connects to a websocket and receives some data in real time: from binance.client import Client import json from binance.websockets import BinanceSocketManager client = Client('', '') # get all symbol prices prices = client.get_all_tickers() trades = client.get_recent_trades(symbol='BNBBTC') # start aggregated trade websocket for BNBBTC def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Quantity, Order) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() I would like to do the following: instead of only printing the data received, the second script should send somehow that data to the Django Channels consumer. Whenever a user opens the page, that page should receive that data. If a second user opens the page at the same time, that second user should receive the data too. Is it possible to do this? Am i supposed to use another service? -
Tasypie Django - GroupBy and Count
I am trying to do a group by and count using tastypie in django. I have spent quite some time, but I get a very weird error and I am pretty sure it comes from tastypie. In practice, I just want to return a JSON with distinct locations and count. This is my model: class Incident(models.Model): location_name = models.CharField(max_length=255) latitude = models.FloatField() longitude = models.FloatField() This is what I do for tastypie: class IncidentResource(ModelResource): class Meta: API_LIMIT_PER_PAGE = 0 queryset = Incident.objects.all() resource_name = 'covid' limit = 0 max_limit = 0 include_resource_uri = False allowed_methods = ['get', 'post'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() validation = Validation() def get_object_list(self, request): location_group = Incident.objects.filter(possibly_new=True).values('location_name').annotate(total_incidents=Count('possibly_new')) # return location_group here is NOT working "invalid literal for int() with base 10: ''" -
How to use django groups in order to set group permission
I want to use django groups provided in user groups. The django group permissions set in admin panel. Suppose I created two groups teachers and students. I want to set permissions at generic view level. Some views can only be can view or can edit by either student or teacher. These permission were set in django admin as following: Now I created a createview as following: class CreateQuestionView(LoginRequiredMixin,generic.CreateView): model = Question success_url= reverse_lazy('questions:list') fields = ['title','description' ] def form_valid(self,form): form.instance.user = self.request.user #self.object.save() return super().form_valid(form) Now I want this view to be accessible by only teacher groups. I cant find a proper way to implement group permission.Something like @group_required may work in this case link but cant find any related documentation. What is correct way to implement this? -
Editing models and extending database structure in Saleor
I recently forked Saleor 2.9 for a web app I am building for an art gallery that wants to display their products for sale as well as give their artists some publicity. I want to be able to have a bunch of cards (like "our team" components) that pull data from an Artists table on the back-end that stores information about the artists' names, emails, origins, etc, and then display it on the front-end. I am struggling to see how to modify the models/DB to create a new "Artists" table with name, email, info, and then to create a manyToMany-like relationship with the products I've populated in the DC, giving the products a "created by" attribute. There are tons of models files throughout the /dashboard directory, and even when I make changes to the core models to create an artist class, I don't know how to get it to show on the dashboard so artists can be created/modified from there. I would like to make it so that the client (non-technical) can add artists and have them show up on the artists page I will make, somewhat like products show up on their pages (but obviously I cannot create a … -
Django: Last modified by and created by user automatic saving
The age-old question: How can I automatically save last_modifed_user in django models? I found in several places this general process how to do it using thread local. I'm hesitant to simply implement it that way because I'm not entirely sure of the consequences it has and because all these posts are old. Is using thread local still the "recommended" way of doing this in django 3? Or does django3 have a better options of doing it? -
Django, new model raises error when trying to access the server
I have the following model, Which is new: from django.db import models class Point(models.Model): latitude = models.FloatField(verbose_name="Latitude", blank=False) longitude = models.FloatField(verbose_name="Longitude", blank=False) elevation = models.FloatField(verbose_name="Location's Elevation", blank=True) class Location(Point): created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='create') location_name = models.TextField(verbose_name="Location Name", blank=False, unique=True,) location_info = models.ForeignKey(Point, related_query_name='new_location', on_delete=models.CASCADE, blank=False, ) I ran makemigrations and migrate and didn't ran into any errors. when running the server I got the following error: ProgrammingError at /points/ column NewLocationModel_location.point_ptr_id does not exist LINE 1: ...location" INNER JOIN "NewLocationModel_point" ON ("NewLocati...