Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango HttpResponseRedirect not passing "request" to function
I am using the DJango login/authentication functionality. I have extended it with a Profile using the Extending The Existing User Model approach. In the "Profile" is a variable called restrole. In the code below, restrole is being used to control the NEXT screen the user sees (as well as as the data on it): def user_login(request): if request.method == 'POST': # First get the username and password supplied username = request.POST.get('username') password = request.POST.get('password') # Django's built-in authentication function: user = authenticate(username=username, password=password) if user: # Check it the account is active if user.is_active: # Log the user in. login(request, user) myprofile = user.userprofileinfo restrole = myprofile.restrole if restrole == 1: return HttpResponseRedirect(reverse('authinduction:induct-owner')) elif restrole == 2: return HttpResponseRedirect(reverse('authinduction:induct-office')) elif restrole == 3: return HttpResponseRedirect(reverse('authinduction:induct-customer')) elif restrole == 4: return HttpResponseRedirect(reverse('authinduction:induct-field-work')) else: return HttpResponse("Unrecognized Role") This Part works fine I can get data from the "request" variable # First get the username and password supplied username = request.POST.get('username') <<< data is returned password = request.POST.get('password') <<< data is returned The problem When I execute one of the branches: if restrole == 1: return HttpResponseRedirect(reverse('authinduction:induct-owner')) It goes to the correct function, but "request" does not appear to have any data associated … -
how to change www to something else in Django urls?
I've created a rest API for my Django app but how I go to api.website.com rather than something like www.website.com/api Btw I'm using nginx if that has to do anything with this -
TzInfo error when unsing Func() on a DatetimeField
I have a model A: class A(models.Model): start_datetime = models.DatetimeField() end_datetime = models.DatetimeField() status = models.CharField(max_length=3) And I'm trying to count the number of "row" group by "day". So here is my query: queryset = A.objects.filter(status='OK').annotate(day=Func(F('start_datetime'), function='DATE')).values('day').annotate(total=Count('id')) And when I try to print the queryset: print(queryset) I got this error message: AttributeError: 'datetime.date' object has no attribute 'tzinfo' I understand why but I don't how to solve this. In my settings: LANGUAGE_CODE = 'en' TIME_ZONE = 'America/Montreal' USE_TZ = True USE_I18N = True USE_L10N = True Please advise. Thank you. -
How to extend Django filer image model field by category
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could someone help me with this topic? my code (all in myPlugins app): models.py from filer.models.abstract.BaseImage class CustomImage(BaseImage): category = models.CharField(max_length=20, blank=True, null=True,) class Meta: app_label = 'myPlugins' admin.py from django.contrib import admin from filer.admin.imageadmin import ImageAdmin from myPlugins.models import CustomImage class CustomImageAdmin(ImageAdmin): pass CustomImageAdmin.fieldsets = CustomImageAdmin.build_fieldsets( extra_main_fields=('author', 'default_alt_text', 'default_caption', 'category'), extra_fieldsets=( ('Subject Location', { 'fields': ('subject_location',), 'classes': ('collapse',), }), ) ) admin.site.unregister(ImageAdmin) admin.site.register(CustomImage, CustomImageAdmin) in settings.py I've added: FILER_IMAGE_MODEL = 'myPlugins.models.CustomImage' and I'm getting an error: File ".../mysite/myPlugins/admin.py", line 27, in admin.site.unregister(ImageAdmin) File ".../venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 118, in unregister for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
DJango authentication User search not working properly
What I am trying to do is the following: 1. Retrieve a User record (from the DJango authentication system) is in the DB 2. get the Username (from that record) 3. Use the "username" to look for a record in a *different* table. 4. If the record *is not* there (in the *different* table), then create one. I am getting an error on what looks like the query into the User table even though I have the following in the views.py from django.contrib.auth.models import User Also, it is not clear why the DoesNotExist error is taking place (when one is looking for the User in the authentication system). Why am I getting this error? TIA This is the error message This is how the "app" is structured views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from authinduction.models import Mstrauthownerrdx from django.contrib.auth.models import User def inductowner(request): username = request.POST.get('username') user = User.objects.get(username=username) myprofile = user.userprofileinfo num_results = Mstrauthownerrdx.objects.filter(logonid=username).count() if not ( num_results == 0 or num_results == 1 ): raise ValueError('Number of items found '+ num_results + ' is not valid') if num_results == 0: u = Mstrauthownerrdx.objects.create(logonid=username, emailaddr=user.email, worktype=1, memo='OWNER', active=1, formpagelastfilled=myprofile.lastpgprocno, formcomplete=myprofile.nextpgprocno, reclocktype=1, … -
checking if data existing in my array of dict
i'd like to check if data exists in all my fields and if there is None in one field return False for all the rest otherwise return True if all the fields are filled up. It's only returning True. Can Anyone help ret = {'complete': False} try: company_director = CompanyDirector.objects.filter(company__token=token).values( 'username','directorTitle','directorInitials', 'directorName','administrativeOrder', 'directorSurname','directorId','directorQualification', 'releventExperiance','education','directorInsolvent', 'directorProffesionalAssociation','profileImage','profileImageThumbNail', 'directorProffesionalAssociationList','releventExperiance','shareInBusiness', 'profileImage','qualifications','criminalOffence','capInBuss','spSkill').first() if company_director: ret['complete'] = True for field, value in company_director.items(): if (type(value) in [str, unicode] is None and len(value)) == "": ret['complete'] = False break; if str(exclude_items) in field: if (type(value) in [str, unicode] and len(value) > 0 and value is not None) or type(value) in \ [int]: ret['complete'] = True except ValueError as e: print (e) return Response(ret) -
Made image is not shown in html
Made image is not shown in html. I wrote in views.py @login_required def view_plot(request): left = np.array([1, 2, 3, 4, 5]) height = np.array([100, 200, 300, 400, 500]) plt.bar(left, height) filename = "output.png" save_fig=plt.savefig(filename) response = HttpResponse(content_type="image/png") save_fig.save(response, "PNG") return save_fig in html <body> <img src='/accounts/view_plot' width=300 height=300> </body> in urls.py urlpatterns = [ url(r'^view_plot$', views.view_plot,name='view_plot'), ] But now ,web page is like cracked image is shown. I do not know why this error happens. In Django app,output.png is saved. I doubt image is not made in view_plot.But i cannot know whether or not. What is wrong in my code?How should I fix this? -
Django Geojson Serializer does not return any "properties"
I am trying to load PostGIS data to GeoJSON using Django's serializing objects from this reference: GeoJSON Serializer I was able to successfully load the said data to a map with its corresponding geometrie. However the rest of its fields in the model does not exist in its GeoJSON properties field when I checked. Instead of an output: { 'type': 'FeatureCollection', 'crs': { 'type': 'name', 'properties': {'name': 'EPSG:4326'} }, 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-87.650175, 41.850385] }, 'properties': { 'name': 'Chicago' } } ] } If would get: { 'type': 'FeatureCollection', 'crs': { 'type': 'name', 'properties': {'name': 'EPSG:4326'} }, 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-87.650175, 41.850385] }, 'properties': { } } ] } I basically wanted the properties to be included so that I can manipulate it in the Leaflet layers. However, unable to serialize the other fields (or at least a specific field from my model), I won't be able to do this. How can I include for example trail_name in the output GeoJSON properties? models.py class Trail(models.Model): ogc_fid = models.AutoField(auto_created=True, primary_key=True, null=False) trail_name = models.CharField(max_length=100, blank=True, null=True) trail_id = models.CharField(max_length=100, blank=True, null=True) trail_type = models.CharField(max_length=300, blank=True, null=True) wkb_geometry … -
How to ordering by specific rules django
I want to order my objects in django by this rule: All characters with is_sold == True must be in the end of query result. I am use two query, to get both sold and not sold characters: characters = list(Character.objects.all().filter(is_sold=False).order_by('server__ranking')) characters += list(Character.objects.filter(is_sold=True).order_by('server__ranking')) Can i do this using only one query using order_by -
Django1.8 ClassBasedView success_url not working
I am trying to create a form save the data and redirect the page views.py class VolunteerCreateView(SuccessMessageMixin, CreateView): model = Volunteer form_class = VolunteerForm template_name = 'volunteer.html' success_url = reverse_lazy('home') success_message = 'Thank you!' volunteer.html <form method="post" class="myform" action="{% url 'volunteer' %}"> {% csrf_token %} <p> {{form.name}}{{form.age}} </p> <p> {{form.location}} </p> <p> {{form.email}} </p> <p> {{form.phone}} </p> <p class="as-comment"> {{form.about}} </p> <p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p> </form> </div> models.py class Volunteer(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() location = models.TextField() about = models.TextField() email = models.EmailField() phone = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{0}".format(self.name) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^volunteer/', web.views.VolunteerCreateView.as_view(), name='volunteer'), url(r'^$', web.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Everything works except the redirection part. The browser console shows 2 request first volunteer url(302 POST) other to home url(200 GET) but the page is not changed its the same page. What could be the reason for this. I am using Python3.5 Django1.8 -
Mommy receipe with m2m not working - 'RecipeForeignKey' object has no attribute 'pk'
I'm using model-mommy==1.4.0 within my tests in my django==1.11.6 project. Here's my receipe: group_employee = Recipe( Group, name="employee" ) user = Recipe( User, ... groups=[foreign_key(group_employee)], ... ) I use it in my test setUp() like this: self.user = mommy.make_recipe('apps.account.user') When I run the test I get: File "[...]/site-packages/model_mommy/mommy.py", line 351, in _handle_m2m if not value.pk: AttributeError: 'RecipeForeignKey' object has no attribute 'pk' I checked the mommy source code and yes, it's true, the RecipeForeignKey really doesn't have a pk value because it's on a meta level, the real object is inside it. I searched Google up and down but nobody seems to have at least a similar problem. Any ideas? Thx -
How can I load big numpy array to the PostgreSQL database in Django project with Docker container?
I have a very big numpy array. After printing it looks in this way: myArray = np.array(df_array) print(myArray) 2007-01-01 Estimates of Iraqi Civilian Deaths. Romania and Bulgaria Join European Union. Supporters of Thai Ex-Premier Blamed for Blasts. U.S. Questioned Iraq on the Rush to Hang Hussein. States Take Lead on Ethics Rules for LawsraeCanadian Group. 2007-01-02 For Dodd, Wall Street Looms Large. Ford's Lost Legacy. Too Good to Be Real?. A Congressman, a Muslim and a Buddhist Walk Into a Bar.... For a Much-Mocked Resume, One More Dig. Corporate America Gets the (McNulty) Memo. Completely. Floating Away From New York. National Mourning. The NYSE's Electronic Man. Developer Accuses Hard Rock of Rigging Sale. Shoney's Chain Finds New Buyer. Nucor to Acquire Harris Steel for $1.07 Billion. Will Bill Miller Have a Happier New Year?. 2007-01-03 Ethics Changes Proposed for House Trips, K Street. Teatime With Pelosi. Turning a Statistic On Its Head. War Protest Mom Upstages Democrats. An Investment Banking Love Story. Revolving Door: Weil Gotshal. Should U.S. Airlines Give Foreign Owners a Try?. 2007-01-04 I Feel Bad About My Face. Bush Recycles the Trash. A New Racing Web Site. What&#8217;s the Theme?. The Product E-Mails Pile Up. ... I … -
Pass xml file from django to javascript
I'm creating an .xml file and then trying to pass this file to javascript, so I could use it there. Here is my view function: def index(request): markers_set = Marker.objects.all() root = Element('markers') tree = ElementTree(root) for m in markers_set: name = Element('marker') name.set('id', str(m.id)) name.set('name', m.name) name.set('address', m.address) name.set('lat', str(m.lat)) name.set('lng', str(m.lng)) name.set('type', m.type) root.append(name) tree.write(open(r'Markers\static\Markers\data.xml', 'wb')) return render_to_response('index.html', {'xmldata' : r'D:\Geoinformation systems\Maps\Markers\static\Markers\data.xml'}) Here is a piece of index.html where javascript code is located: <html> <body> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(-33.863276, 151.207977), zoom: 12 }); var infoWindow = new google.maps.InfoWindow; <!--Here I'm taking data that is passed--> downloadUrl('{{ xmldata }}', function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName('marker'); ... }); } </script> </html> How should I pass/get the file, so not to failing loading it? -
ProgrammingError in Django when adding a new model-instance to the Database, what could be wrong?
When using the Django Admin panel, I am able to add new instances to Users and Groups. The same thing goes for all my apps, except for one. This one app, resultregistration, always gives me a ProgrammingError whenever I try to add a new model. For example, this app has a Competition-model where data about a sport competition should be stored. When I click "+ Add" I am taken to the correct site where I can add a new competition. However, when I press save I get: ProgrammingError at /admin/resultregistration/competition/add/ column "competition_category" of relation "resultregistration_competition" does not exist LINE 1: INSERT INTO "resultregistration_competition" ("competition_c... Of course, I assume something is wrong with the migrations. However, I have run python manage.py makemigrations appname, and python manage.py migrate appname, and that works fine. I get a message that there are "No changes detected", and "No migrations to apply". I have tried solutions posted on SO, but none of them worked. What is the general reason for this error? And does anyone know what could be wrong in this specific case? Could one get this error if something is wrongly defined in the model? Or does it have to be a migration problem? … -
How to get property names from super class in sub class python
I have a class like below class Paginator(object): @cached_property def count(self): some_implementation class CachingPaginator(Paginator): def _get_count(self): if self._count is None: try: key = "admin:{0}:count".format(hash(self.object_list.query.__str__())) self._count = cache.get(key, -1) if self._count == -1: self._count = self.count # Here, I want to get count property in the super-class, this is giving me -1 which is wrong cache.set(key, self._count, 3600) except: self._count = len(self.object_list) count = property(_get_count) As indicated in the comment above, self._count = <expression> should get the count property in super-class. If it is method we can call it like this super(CachingPaginator,self).count() AFAIK. I have referred many questions in SO, but none of it helped me. Can anyone help me in this. -
How can I not need to query the database every time?
How can I not need to query the database every time? From the bellow snapshot: I have five tabs, name as: 云主机,云硬盘,云主机快照,云硬盘快照,安全组: And in the bottom of the list, there is <<, <, >,>>, and GO buttons that can calculate the page_num. Then I can use the localhost:8000/app_admin/myServers-1-1-1-1-1 analogous link to query the data. 1-1-1-1-1 represents 云主机,云硬盘,云主机快照,云硬盘快照,安全组's page_num. In the views.py, there are key codes: def myServers(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid): data = get_res_myserver(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid) return render(request, 'app_admin/my-server.html', {"data":data}) ... def get_res_myserver(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid): # query all the data, and paginator there ... return data But, my issue is, every time I query the localhost:8000/app_admin/myServers-x-x-x-x-x, it will take a long time, sometimes more than 8 seconds(the time can not be shorter), its a long time for user experience. So, Whether there is a method that I only query my data once, then paginator can be multiple times? -
Passing with-declared variables to a custom function in Django template tags
I want to build a table of 5 columns and 8 rows with the data contained in a list of 40 elements: {% for row_num in 0|range:8 %} {% with startrange=row_num|multiply:5 endrange=row_num|multiply:5|add:5 %} {{ startrange }} {{ endrange }} <div class="row"> {% for item in items|slice:startrange,endrange %} <div class="col"> {% include "shop/item_card.html" %} </div> {% endfor %} </div> {% endwith %} {% endfor %} I have successfully defined multiply and add custom functions, and I have defined startrange and endrange. Now, I need to pass them to slice function. I've tried slice:"startrange:endrange" among other possibilities, but none seems correct. How can I pass 2 (or more) variables to a custom function? -
How to rename Table name in Django?
I just created a model named Carts and now I want to rename it to Cart only, how do I do it? I have tried doing this: python manage.py makemigrations <app_name> and then python manage.py migrate But its not reflecting the change in the database table: I am seeing the database as: python manage.py sqlmigrate <app_name> 0001 Please Help! -
Django No Post matches the given query?
A bit of magic : today i was woken up, power my laptop and start working for my project, but... When i pushed on button, django was return to me 404 error, and say "that No match queries". It a bit sad me, because yesterday all was work as well as never. This is my huge view: def p(request, pk): user = request.user topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) who_come = WhoComeOnEvent.objects.filter(which_event=topic.id) if request.is_ajax() and request.POST.get('action') == 'joinEvent': who_come_obj = WhoComeOnEvent.objects.create( visiter=user, which_event=post.topic ) visitors_usernames = [] for w in who_come: visitors_usernames.append(w.visiter.username) return HttpResponse(json.dumps(visitors_usernames)) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user # comment.save() #из-за этой блевотины было 2 записи в базу comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, post=post ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, # 'form': form, 'who_come': who_come}) else: form = CustomCommentForm() return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form, 'who_come': who_come}) the problem in post = get_object_or_404(Post, pk=pk), this code worked for month but now it shows 404 error. I don't know what the reason. Why it broken? I try to change post … -
Nginx showing default page instead of Django (Gunicorn)
Can't figure out where is the problem with my configuration. I have DigitalOcean VPS where I run Django project. I've configured Gunicorn and Nginx. Set correct IP address. Checked gunicorn status (ok). No errors in /var/log/nginx/error.log Even deleted default from sites-enabled and still see nginx default page. gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/nameofmyproject ExecStart=/home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/django/nameofmyproject/nameofmyproject.sock nameofmyproject.wsgi:application [Install] WantedBy=multi-user.target sites-available/nameofmyproject server { listen 80; server_name <my_ip_address>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/nameofmyproject; } location / { include proxy_params; proxy_pass http://unix:/home/django/nameofmyproject/nameofmyproject.sock; } } gunicorn status unicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2017-10-19 09:56:18 UTC; 1min 2s ago Main PID: 1372 (gunicorn) Tasks: 4 Memory: 138.0M CPU: 3.971s CGroup: /system.slice/gunicorn.service ├─1372 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work ├─1555 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work ├─1556 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work └─1557 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work Oct 19 09:56:18 ubuntu-16 systemd[1]: Started gunicorn daemon. Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] [INFO] Starting gunicorn 19.7.1 Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] [INFO] Listening at: unix:/home/django/nameofmyproject/nameofmyproject Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] … -
Django filter a day name in many to many field that contains list of days
class DayOfWeek(models.Model): name = models.CharField(max_length=45) class PermanentShiftSchedule(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) shift = models.ForeignKey(Shift, related_name='shift_permanent_schedule', on_delete=models.CASCADE) branch_employee = models.ForeignKey(BranchEmployee, related_name='branch_emp_permanent_schedule', on_delete=models.CASCADE) days_of_week = models.ManyToManyField(DayOfWeek, related_name='permanent_shift_days') Now I want to filter the PermanentShiftSchedule where days_of_week field contanins "Thursday" days_of_week field may contain multiple days names -
Error 404 on post request from AJAX call with django
I'm trying to integrate jquery formbuilder, but I'm constantly getting a 404 (Not Found) whenever I post the data. This is how my html looks like (where I render the form) <form id="custom-form"> <div id="fb-editor"></div> <button type="submit" class="btn btn-round btn-primary"> Submit Form </button> </form> the js file I call: jQuery(function($) { var $fbEditor = $(document.getElementById('fb-editor')), $formContainer = $(document.getElementById('fb-rendered-form')), fbOptions = { onSave: function() { $fbEditor.toggle(); $formContainer.toggle(); $('form', $formContainer).formRender({ formData: formBuilder.formData }); }, }, formBuilder = $fbEditor.formBuilder(fbOptions); $('.edit-form', $formContainer).click(function() { $fbEditor.toggle(); $formContainer.toggle(); }); $('#custom-form').on('submit', function (e) { e.preventDefault(); // Collect form data var formData = JSON.stringify(formBuilder.actions.getData('json', true)); console.log(formData); // Send data to server $.post('/ajax/save/', formData) .done(function (response) { console.log('form saved') }).fail(function (jqXHR) { console.log('form was not saved') }); // Prevent form submission return false; }); }); and this is the url: url(r'^ajax/save/$', views.ajax_formbuilder_save, name='ajax-formbuilder-save') This is the specific error I'm getting: POST http://127.0.0.1:8000/ajax/save/ 404 (Not Found) How should I solve this? Thanks! -
Django project set up with MySql and virtual environment from start
I am new to django so I need to start with django projects..I need information regarding how to start with django project using MySql database and virtual environment on Linux. -
Can not solving Reverse accessor clashes
I have a bug that I can not solve in django>=1.8,<1.9. I merged my changes and I get this: ERRORS: archive.Booking.articles: (fields.E304) Reverse accessor for 'Booking.articles' clashes with reverse accessor for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. archive.Booking.articles: (fields.E305) Reverse query name for 'Booking.articles' clashes with reverse query name for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. events.Booking.articles: (fields.E304) Reverse accessor for 'Booking.articles' clashes with reverse accessor for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. events.Booking.articles: (fields.E305) Reverse query name for 'Booking.articles' clashes with reverse query name for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. Here is my model: class Booking(events_models.AbstractBooking): period = models.ForeignKey('archive.Period', null=True, related_name='events', help_text='ref_artistic_period') distributions = models.ManyToManyField('archive.Distribution', related_name='bookings', through='archive.Booking2Distribution') def get_absolute_url(self): return reverse('archive:detail', kwargs={'slug': self.slug, 'pk': self.id}) class Meta: ordering = ['date_start',] Here is my base class with articles field: class AbstractBooking(SearchMixin, TranslationMixin, MediaMixin, PriceMixin, ImagesMixin, DownloadsMixin, AdminMixin, TicketMixin): ... articles = models.ManyToManyField('blog.Article', related_name='bookings', blank=True) ... I tried added articles field to my Booking class like below, but without success: articles = models.ManyToManyField('blog.Article', related_name='%(class)s_bookings', … -
send just a specific filed on ModelSerializer to client - django rest framework
I have a Serializer like below: class KlassStudentSerializer(ModelSerializer): student = ProfileSerializer() klass = KlassSerializer() class Meta: model = KlassStudents fields = ['pk', 'student', 'klass'] I want to send just klass values in a view and send just student in another view. How can I do that?