Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My data is generated dynamically using django pass through view.py but how can I select those element in HTML using jquery or javascript?
My data is generated dynamically using Django pass through view.py but how can I select those element in HTML using jquery or javascript? because all my element will have the same class and id -
Djagno-REST-framework-datatables didn't show anything
I'm trying to practice Django with REST api, but when I try to run nothing happened. It still show the processing sign. Here is my reference:https://github.com/izimobil/django-rest-framework-datatables I try different version of jquery but seems it is not a solutions. Here is my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css"> <link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"> </head> <body> <div class="row"> <div class="col-sm-12 text-center"> <h4 class="bg-primary text-white p-2" style="margin: 15px;">Full example with foreign key and many to many relation</h4> <div class="btn-group btn-group-toggle" role="group" aria-label="Decades"> <button class="btn btn-success btn-decade">All time</button> </div> </div> </div> <div class="row"> <div class="col-sm-12"> <table id="datatables" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Link</th> <th>Context</th> <th>Time</th> <th>Action</th> </tr> </thead> </table> </div> </div> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="//cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var table = $('#datatables').DataTable({ "processing": true, "serverSide": true, "ajax": { "url":"/newsapi/?format=datatables", "type": "GET" }, "columns": [ {"data": "id"}, {"data": "name"}, {"data": "link"}, {"data": "context"}, {"data": "created_time"}, { "data": null, "defaultContent": '<button type="button" class="btn btn-info">Edit</button>' } ] }); }); </script> </body> </html> Serializers.py: from rest_framework import serializers from stock.models import Stock class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = '__all__' Views.py class Get_news_List(APIView): def get(self, request): stock = Stock.objects.all() serialized = StockSerializer(stock, many=True) return Response(serialized.data) -
python django: pre-select dropdown of custom field
I am newbie to django python. I am trying to create CRUD using custom fields. Un update page, It shows foriegn key value instead of dropdown. Here is my code Model.py: class RoleModel(models.Model): rol_id = models.AutoField(primary_key=True) rol_name = models.CharField(max_length=255) class Meta: db_table = "tbl_roles" def __str__(self): return self.rol_name class UserModel(models.Model): usr_id = models.AutoField(primary_key=True) user_rolidfk = models.ForeignKey(RoleModel, blank=True, null=True, db_constraint=True, on_delete=models.CASCADE) usr_name = models.CharField(max_length=255) usr_email = models.EmailField() usr_picture = models.FileField() usr_aboutme = models.TextField() usr_datetime = models.DateTimeField(auto_now_add=True) class Meta: db_table = "tbl_users" def __str__(self): return str(self.user_rolidfk) + ' - ' + ', '.join([rol.rol_id for rol in self.user_rolidfk.all()]) def __unicode__(self): return self.usr_name forms.py: class RoleForm(forms.ModelForm): class Meta: model = RoleModel fields = "__all__" class UserForm(forms.ModelForm): class Meta: model = UserModel fields = ['usr_name', 'user_rolidfk'] Views.py: def useredit(request, id): users = UserModel.objects.get(usr_id=id) roles = RoleModel.objects.all() form = UserForm() data = {"users": users, "roles": roles, "form": form } return render(request,'user_edit.html', data) user_edit.html: {{ users.user_rolidfk }} {{ form.user_rolidfk }} -
Django ORM for SQL SELECT query
cursor.execute("SELECT id FROM student where name=%s", [s[2]]) student_id = cursor.fetchone() I have s[2] value as 'Jack' I am trying to convert this into Django ORM, but getting empty queryset. Could you please help me with this. My ORM for above query is as below: student_id = Student.objects.filter(name=s[2]).values_list('id') While printing the student_id I am getting empty queryset. <QuerySet []> I need to get the id of the student present on s[2] which in this case is 'Jack'. Thank you, -
Is there a way on Serializer perform create to save a field which is a Foreign Key
I have two models Timesheet and Employee now on my use case I want to save automatically the employee field of the timesheet using the perform_create but the api returns an error of "ValueError at /api/timesheet_entry/\nCannot assign \", , ]>\": \"Timesheet.employee\" must be a \"Employee\" instance. What I was trying to do is save the Timesheet's employee field to the Employee's login field using the id. below are the information on the models, serializer and the viewsets. class Timesheet(models.Model): start_date = models.DateTimeField(verbose_name="Start Date", null=True, blank=True, default=None, editable=True, help_text="", unique=False, db_index=False,) end_date = models.DateTimeField(verbose_name="End Date", null=True, blank=True, default=None, editable=True, help_text="", unique=False, db_index=False,) employee = models.ForeignKey('Employee', on_delete=models.PROTECT, related_name="timesheet_entry_employee", verbose_name="Employee", null=True, blank=True, editable=True, unique=False) comment = models.CharField(verbose_name="Comment", null=True, blank=True, default=None, editable=True, max_length=255,) total_hours = models.DecimalField(verbose_name="Total Hours", null=True, blank=True, default=0.00, max_digits=19, decimal_places=2,) and class Employee(models.Model): name = models.CharField(verbose_name="Name", max_length=255,) login = models.ForeignKey(User, on_delete=models.PROTECT, related_name="employee_login", verbose_name="Login", editable=True) hourly_cost = models.DecimalField(verbose_name="Hourly Cost", null=False, blank=False, editable=True, max_digits=19, decimal_places=2,) charge_out_rate = models.DecimalField(verbose_name="Charge Out Rate", null=False, blank=False, max_digits=19, decimal_places=2,) and in the serializer class TimesheetEntrySerializer(WritableNestedModelSerializer): employee = PrimaryKeyRelatedField(many=False, read_only=False, allow_null=True, queryset=models.Employee.objects.all()) viewset's perform create def perform_create(self, serializer): request = self.request.user.id employee_user = Employee.objects.filter(employee__login__id=request) return serializer.save(employee=employee_user) -
Translations in Django 2.2 is not working
I'm working on a project using Python(3.7) and Django(2.2) in which I have to make the site available in 2 languages (English and Chinese). I have searched a lot and tried every possible solution but no success. Here's what I have tried: Install gettext on my system and link it Add the following setting in settings.py: Add middleware 'django.middleware.locale.LocaleMiddleware', after Session and before Common, then add USE_I18N = True & USE_L10N = True, after that mentioned the languages as: LANGUAGES = ( ('en', _('English')), ('zh-hans', _('简体中文')), ) then add locale path as: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) Then run the command as: django-admin makemessages -all it creates the directory as: └── zh_hans └── LC_MESSAGES └── django.po After that, I add the translations in django.po and ran the command as django-admin compilemessage which generate the file django.mo I added a url for i18n as: re_path(r'^i18n/', include('django.conf.urls.i18)) and below is my template which is loading by render from view as: {% load i18n %} <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" … -
Django clean method of model doesn't gets called when saving the data
So I having this model where I am storing the information that my entity is sending . class NewProvisionalEmployeeMail(models.Model): offer_id = models.AutoField(primary_key=True) email = models.EmailField(max_length=70, null=False, blank=False, unique=False) token = models.TextField(blank=False, null=False) offer_sent_by = models.CharField(max_length=50) position_assigned = models.CharField(max_length=50, null=False, blank=False, default="Developer") def __str__(self): return str(self.offer_sent_by) +" to " + str(self.email) def clean(self): if(NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).exists()): NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).delete() What was expected : Before saving data to this model, I expect the clean method to be called automatically. I have tried this with my other models over there it was working but its not working over here. This is the part where I am saving the data. def sendoffer(request): context = {} hostname = request.get_host() + "/dummyoffer" if request.method=='POST': email = request.POST.get('email') position = request.POST.get('opt') context['success_message'] = "Mail has been sent!!!" token = get_secret_key(email) msg=EmailMultiAlternatives('ATG',"Hello\n we are from atg.dev.party\n Click on this link to get offer","jecrccanteen@gmail.com",[email]) message = "http://" + hostname + "/" + token msg.attach_alternative(message,"text/html") msg.send() newusermail = NewProvisionalEmployeeMail(email=email, token=token, offer_sent_by=request.user.username, position_assigned=position) newusermail.save() return render(request, 'mainapp/offer.html',context) newusermail.save() is the part where the data is going to be saved and before that I expect clean method to be called which checks for email if it already exists in our database and if it does we … -
Multiple emails configurations to send emails (if admin have multiple emails then admin need to choose )in Django using python
sending an email from one email is working fine, but if we want send an email to user from multiple emails(i have 3 emails from that i need to choose any one and receiver get email whichever i chose ) so please help me I'm new to Django and Python -
Django - Displaying model data on Elasticsearch search result
I am making a booking website, and I have implemented elasticsearch. I got the search working just fine, but now I am kind of stuck on a problem. What I'm trying to do is display the lowest price for the apartment the user has searched for, in the search results. The prices are stored in the "ApartmentPrices" model : class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title This is my document and view for the actual search : search view : def search(request): apartments = Apartment.objects.all() q = request.GET.get('q') if q: apartments = ApartmentDocument.search().query("match", title=q) else: apartments = '' return render(request, 'search/search_elastic.html', {'apartments': apartments, "q": q, }) elasticsearch document: apartments = Index('apartments') @apartments.document class ApartmentDocument(Document): class Django: model = Apartment fields = [ 'title', 'id', 'bedrooms', 'list_date', ] I have tried passing in apartment_id to the search view, but I cannot get it to work. Can anyone point me in the right direction please ? How do I access model data from a ES query ? Thank you ! -
Sending input names in Django form having javascript code
I have the following code: <form id="buttonForm" action = "/goSomeWhere" method="post" > <input type="submit" name="bnext" value="Next Page" > <input type="submit" name="bprevious" value="Previous Page" > </form> When either one of this two buttons are submitted I receive "bnext" or "bprevious" values in Django View request.POST so I can further construct the logic that I need. But when I'm trying to insert some javascript for the second button I loose those values: <input type="submit" name="bnext" value="Next Page" > <input type="submit" name="bprevious" id="bpid" onclick="disable()" value="Previous Page" > function disable() { document.getElementById("bpid").disabled = true; document.getElementById("buttonForm").submit(); } There is a way to do this and still receiving input names values ? -
django-oscar error MTPRecipientsRefused at /checkout/preview/ How to fix it
hi what happen with SMTPRecipientsRefused at /checkout/preview/ anyidea ??? django-oscar Environment: File "/usr/lib/python3.6/smtplib.py" in sendmail 881. raise SMTPRecipientsRefused(senderrs) Exception Type: SMTPRecipientsRefused at /checkout/preview/ Exception Value: {'oscar@hotmail.com': (550, b'5.1.1 <oscar@hotmail.com>: Recipient address rejected: hotmail.com')}[enter image description here][1] -
changing name of a form in template tag without effecting models.py in django
hello i want to change the name in a template while rendering a form in django i'm able to change it in template only if i made change in my models.py but i want to know if is there any way where i can change the name of a particular form field without effecting my models.py i'm able to change the way form field can render only if i have changed the models.py but whenever i do so i have got an error saying no such table: login_record class Record(models.Model): choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative', 'AB Negative'), ('AB Positive', 'AB Positive'), ) blood_TYPE = models.CharField(max_length=20, choices=choice1, default='O Positive') staff = models.CharField(max_length=20, default=' ') id_no = models.CharField(max_length=20, default=' ') donar_name = models.CharField(max_length=30) units = models.FloatField(default=0, validators=[MinValueValidator(0)]) date = models.DateField() class Meta: ordering = ['-date'] def __str__(self): return self.id_no here is my models.py class DonateForm(forms.ModelForm): choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative','AB Negative'), ('AB Positive','AB Positive'), ) blood_group … -
How can i use the "user" table on mysql instead of the "auth_user" table which is the default from the django site?
How can i use the "user" table on mysql instead of the "auth_user" table which is the default from the django site? def login_user(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): user_id = form.cleaned_data.get('user_id') password = form.cleaned_data.get('password') user = authenticate(user_id=user_id, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {user_id}") return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"form": form}) code from views.py -
How do I get the current user from the queryset filter method?
I want to show a list of store information for the current user model.py class User(AbstractUser): email = models.EmailField(max_length=100, blank=True, null=True) class Store(models.Model): u_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) store_name = models.CharField(max_length=30) business_number = models.IntegerField() serializers.py class StoreSerializer(serializers.ModelSerializer): current_user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Store fields = ('url', 'id', 'u_id', 'store_name', 'business_number', 'title', 'content', 'image', 'current_user') views.py class MyStoreDetailView(generics.ListCreateAPIView): permission_classes = [IsOwnerOrReadOnly] queryset = models.Store.objects.filter(u_id=request.uer) # how to get current user serializer_class = serializers.StoreSerializer -
Can't login with super user created account in Python 3.8
Before i go forward, I know this is a commonly asked question but I have searched the top questions related to this, and none of it seems to be helping.. Following: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ What I have done: py manage.py createsuperuser Created user I have confirmed the user is a superuser with: from django.contrib.auth.models import User active_staff = User.objects.filter(is_active=True, is_staff=True) This will then list the super users Although, when I do something like: u = User(username="admin") u.is_staff >> False u.is_superuser >> False Why is this? I also then manually set to true, save(), then check, and it's now True. Try to log in, doesn't work. restart shell and check, it's back to false. I tried the accepted answer here: Can't login to django admin after creating a super user with a custom user model This: Admin page on django is broken None have helped. If there is anything i need to copy/paste from my Djnago app to help, pleaes let me know. I am new with Python and Django so I'm not exactly sure what to add to this question. -
Access denied error only on heroku remote machine through requests python
I am facing this issue where when I access the page source of a url from my local machine it works fine but when I run the same piece on code on a heroku machine it shows access denied. I have tried changing the headers ( like adding Referers or changing the User-Agent) but none of those solutions are working. LOCAL MACHINE ~/Development/repos/eater-list master python manage.py shell 1 ↵ 12051 21:15:32 >>> from accounts.zomato import * >>> z = ZomatoAPI() >>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi') >>> response[0:50] '<!DOCTYPE html>\n<html lang="en" prefix="og: http' >>> response[0:100] '<!DOCTYPE html>\n<html lang="en" prefix="og: http://ogp.me/ns#" >\n<head>\n <meta charset="utf-8" REMOTE MACHINE ~ $ python manage.py shell Python 3.5.7 (default, Jul 17 2019, 15:27:27) [GCC 7.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from accounts.zomato import * >>> z = ZomatoAPI() >>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi') >>> response '<HTML><HEAD>\n<TITLE>Access Denied</TITLE>\n</HEAD><BODY>\n<H1>Access Denied</H1>\n \nYou don\'t have permission to access "http&#58;&#47;&#47;www&#46;zomato&#46;com&#47;ncr&#47;the&#45;immigrant&#45;cafe&#45;khan&#45;market&#45;new&#45;delhi" on this server.<P>\nReference&#32;&#35;18&#46;56273017&#46;1572225939&#46;46ec5af\n</BODY>\n</HTML>\n' >>> ZOMATO API CODE There is no change in headers or requests version. class ZomatoAPI: def __init__(self): self.user_key = api_key self.headers = { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) ' … -
NoReverseMatch at URL
I've been trying to create a movie survey in Django for an assignment, and I am currently working on the function. I can't seem to understand why won't it recognize the URL I pass. I tried removing the hardcoded URL as shown in the Django tutorial on the framework's site, but that doesn't make the error go away. Here's an excerpt from urls.py: urlpatterns = [ url(r'^$', views.index, name="index"), path('movie=<int:movie_id>&user=<int:user_id>/', views.movie, name='movie'), path('ratings/', views.ratings, name='movie'), path('rating/<int:movie_id>/', views.rating, name='movie'), path('movie=<int:movie_id>&user=<int:user_id>/vote/', views.vote, name='vote'), path('register/',views.register, name='register'), ] This is my movie view( supposed to present a movie and a star rating radio for the user to rate the movie), where the URL is constructed and passed to HTML: def movie(request,movie_id,user_id): movie = get_object_or_404(Movie, pk=movie_id) voteURL = '/polls/movie=' + str(movie_id) + '&user='+str(user_id)+'/vote/' context = { 'mymoviecaption':movie.Title, 'moviePoster': 'https://image.tmdb.org/t/p/original'+tmdb.Movies(movie.TMDBID).images().get('posters')[0].get('file_path'), 'myrange': range(10,0,-1), 'myuserid':user_id, 'voteurl': voteURL, 'mymovieid':movie_id } #print(nextURL) translation.activate('en') return HttpResponse(render(request, 'movieview.html', context=context)) The HTML excerpt, where the vote view is called: <form action="{% url voteurl %}" method="post"> {% for i in myrange %} <input id="star-{{i}}" type="radio" name="rating" value={{i}}> <label for="star-{{i}}" title="{{i}} stars"> <i class="active fa fa-star" aria-hidden="true"></i> </label> {% endfor %} <input type="submit">Vote!</input> </form> The vote view( should save to database and redirect to the … -
Django form from JavaScript
I'm trying to create a server using Django where the user creates figures such as markers, lines, polygons, circles, etc in a map, because of that I'm using Leaflet.js. After the user creates what he wants I want the geometry figures (Latitude and Longitude of every figure) and Leaflet have an option for that, however you must download but I don't want so I changed a part of the source code into this. document.getElementById('export').onclick = async function(e) { var data = drawnItems.toGeoJSON(); // make the request: var rsp = await fetch("path/to/server/upload/url", { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); console.log("server responded with: ", await rsp.json()); } I'm not good at web developing so I lack of knowledge using Django and JavaScript. So my question is the following (probably a noob question): Is there a way to create a form for the geometry figures in order to manipulate it in Python? The entire code is the following: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script> L_NO_TOUCH = false; L_DISABLE_3D = false; </script> <script src="https://cdn.jsdelivr.net/npm/leaflet@1.5.1/dist/leaflet.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.5.1/dist/leaflet.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/> <link rel="stylesheet" … -
How to get access to model data through two intermediate models?
There are four models: class ObjectDataAdditional(models.Model): #various fields and: normal = models.ForeignKey( 'ObjectDataNormalized', on_delete=models.CASCADE, null=True, related_name='additional_normal' ) class ObjectDataNormalized(models.Model): #various fields class LinkedData(models.Model): many = models.ManyToManyField( ObjectDataNormalized, related_name='many_related', ) def __str__(self): return u', '.join([str(a.pk) for a in self.many.all()]) class LinkedInfo(models.Model): linked_data = models.ForeignKey( LinkedData, on_delete=models.CASCADE, related_name='linked_data_related' ) normalized = models.ForeignKey( ObjectDataNormalized, on_delete=models.CASCADE, related_name='normalized_related' ) main = models.BooleanField( default=False, null=False, ) Here I get data i need: info = LinkedInfo.objects.all().order_by('linked_data_id', '-main').select_related( 'linked_data', 'normalized', ).prefetch_related( 'normalized__normal_object', 'normalized__additional_normal' ).annotate(max_percentage=Max( 'normalized__normal_object__additional_object__percentage_technical_readiness')) final_data = [] temp_data = [] if info: last_link_pk = info[0].linked_data.pk for i, x in enumerate(info): if x.linked_data.pk == last_link_pk: temp_data.extend(create_temp_array(x, x.normalized.additional_normal)) last_link_pk = x.linked_data.pk else: final_data.append(temp_data) temp_data = [] temp_data.extend(create_temp_array(x)) last_link_pk = x.linked_data.pk if info.count() - 1 == i: final_data.append(temp_data) return Response(final_data) Create hierarchy of objects on value of main field in model LinkedInfo: def create_temp_array(data, additional_result=None): additional = data.normalized.additional_normal.filter(normal=data.normalized.pk).values() result = [{ 'linked_data_id': data.linked_data.pk, 'is_main': data.main, 'normalized_object_id': data.normalized.pk, 'name_data': data.normalized.name_data, 'year_data': data.normalized.year_data.year, 'build_code': data.normalized.build_code, 'ministry_code': data.normalized.ministry_code, 'territory_code': data.normalized.territory_code, 'fcp': data.normalized.program_code, 'max_percentage_technical_readiness': data.max_percentage, 'additional': additional }] return result data.normalized.additional_normal.filter(normal=data.normalized.pk).values() executes each call of method create_temp_array() (as it should) but I just can't find another way to put data from additional_object to created array. Each object ObjectDataNormalized may have a few objects ObjectDataAdditional … -
How to change django admin permissions based on a field value?
I have a model where a Professor belongs to a certain department Class Professor(models.Model): name=models.CharField(max_length=50) code=models.CharField(max_length=9) dept=models.ForeignKey('Department', on_delete=models.CASCADE) Where the model for the department is just its name with multiple professors pointing to it. Would there be a way to set view or edit permissions depending on the value of the department name? Say, if I want professors that belong to department A to only be editable by people with permissions to A, and professors belonging to department B to be editable by people with permissions to B and so on, what would be the way to implement it in the admin? -
How to provide read-only access for unauthorized users to my React/Django app?
I have a social media-type web app and want to have some read-only access even when a user isn't logged in. For example, if the user votes on a poll, I want nothing to happen but the user should still be able to see it. I am using token authorization. I'm wondering, should I do a check on the front-end somehow to see if a user is logged in (perhaps checking for the existence of a token in local storage) and not perform a fetch if they're not? Or should I somehow, in the frontend, handle receiving a 401 response from the backend for trying to access a protected resource? Or should I handle it on the back end and send back a 200 response and let the front end handle receiving a different version of a 200 response? I'm using Django and React -
How can I change the template used for django-ckeditor to browse?
Djago-Ckeditor use a default html template rendered when url /ckeditor/browse/. I want to know if I can change the html templete for one of my own that handle the same features but with a pretty design. This is the default template: image of the window displayed Also if it is possible to add a delete button as well. -
How do I set up a ThemeForest theme in a Django project?
I recently got started with Django, took a few courses on it and got the basic idea in terms of project structure, urls, templates, static files etc. To avoid learning frontend development (and build my app faster), I thought a bootstrap theme would be a good option. I got this https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469 which has bootstrap4 in the title, however, it seems that integrating it into the project is not as simple as placing the scss, js and vendor files into my static folder. The 'getting started' resources suggest that it runs on NodeJS, and has a whole backend of its own. I'm not asking for a bespoke full guide on how to do it, but it'd be nice to know if the two things are compatible or I if should move on and try some other frontend solution instead. Cheers! -
Transfer date and time from Django model to Javascript and save the object again
I have a serializer class and a view which convert Django model and it can be shown in a template. # models.py class Book(models.Model): title = models.CharField(max_length=65, null=True, blank=False) published_at = models.DateTimeField(blank=True) # serializer.py class BookSerializer(serializers.ModelSerializer): published_at = serializers.SerializerMethodField() def get_published_at(self, obj): published_at = obj.published_at return published_at class Meta: model = Book fields = ('title', 'published_at') Using the serializer class, one can send the data to a template. Here, the value of published_at is in the ISO date format. Such as: 2019-10-17T21:57:56Z I need to show it in an HTML/Javascript form as local time and then again send the date object to Django to update the published_at field. How can this be achieved? -
Is there a way to reload ViewSet on each GET request for new data in DRF?
I am trying to generate a random object from my Model. The problem is that it will only work one time, then I have to restart the server to get a new object. It just keeps giving me the same object until the restart. I have been looking for solution on stack overflow but haven't found any. Views.py def dailyaskist(category): qs = Task.objects.filter(category=category) max_num = len(qs) while True: pk = random.randint(1, max_num) task = Task.objects.filter(pk=pk).first() if task: return task.pk class DailyTaskEcommerceViewSet(viewsets.ModelViewSet): category = 'ecommerce' task_pk = dailyaskist(category) queryset = Task.objects.filter(pk=task_pk) serializer_class = TaskSerializer serialisers.py class StepSerializer(serializers.HyperlinkedModelSerializer): task_id = serializers.PrimaryKeyRelatedField(queryset=Task.objects.all(), source='task.id') class Meta: model = Step fields = ('title', 'description', 'done', 'task_id') class TaskSerializer(serializers.HyperlinkedModelSerializer): steps = StepSerializer(many=True, read_only=True) class Meta: model = Task fields = ('title', 'description', 'video', 'done', 'steps') models.py Categories = ( ('ecommerce', 'Ecommerce'), ) class Task(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=360) video = models.CharField(max_length=30, default='') category = models.CharField(choices=Categories, default='', max_length=30) done = models.BooleanField(default=False) def __str__(self): return self.title class Step(models.Model): task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(max_length=360) done = models.BooleanField(default=False) def __str__(self): return self.title I want to receive a new object (task) each time I make a GET request using the DailyTaskEcommerceViewSet. Thanks in …