Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the presentation of a DataTimeField field to a format '% Y-% m-% d% H:% M:% S' to be serialized
Good afternoon, I have the following model in Django, and the field last_update is a Faithful DateTme field that is represented as follows when I serialize it: "2019-08-06T14: 19: 05-04: 00" And I want to represent it like this: "2019-08-06 19:05:04" class Interface(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipo,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puerto,on_delete=models.DO_NOTHING,related_name='puerto_origen', null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipo,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puerto,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interface' class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) ip_gestion_origen=serializers.CharField(source='id_EquipoOrigen.ip_gestion',read_only=True) vendedor_origen=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) ip_gestion_destino=serializers.CharField(source='id_EquipoDestino.ip_gestion',read_only=True) vendedor_destino=serializers.CharField(source='id_EquipoDestino.vendedor',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) #Los campos que voy a mostrar en mi serializacion con la clase Meta class Meta: model=Interface fields=('id_interface','id_EquipoOrigen','EquipoOrigen','ip_gestion_origen','id_PuertoOrigen', 'PuertoOrigen','LocalidadOrigen','CategoriaOrigen','vendedor_origen','estatus', 'etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description', 'id_EquipoDestino','EquipoDestino','ip_gestion_destino','vendedor_destino','id_PuertoDestino','PuertoDestino','LocalidadDestino', 'CategoriaDestino','ultima_actualizacion',) class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interface.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination filter_class=InterfacesFilter -
Django Simple Query Filter
Trying to filter data by logged in user, but the code results in showing all users data instead of just the ones created by user. What am I missing here ? There is no issue with serializer. I am guess I am missing some fundamental here. views.py class TimelinePostList(generics.ListCreateAPIView): serializer_class = TimelinePostSerializer def get_queryset(self): queryset = Timeline_Post.objects.all() user = self.request.user queryset.filter(author = user) return queryset models.py class Timeline_Post(models.Model): slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) text = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) Actual results: { "count": 2, "next": null, "previous": null, "results": [ { "slug": "secon_post", "author": 8, "updated_on": "2019-08-06T18:47:43.915249Z", "text": "secon_post", "created_on": "2019-08-06T18:47:43.915249Z", "status": 0, "media": [] }, { "slug": "lkkej", "author": 5, "updated_on": "2019-08-06T18:04:11.175809Z", "text": "first Post", "created_on": "2019-08-06T18:04:11.175809Z", "status": 1, "media": [] } ] } Expected Results: { "count": 1, "next": null, "previous": null, "results": [ { "slug": "lkkej", "author": 5, "updated_on": "2019-08-06T18:04:11.175809Z", "text": "first Post", "created_on": "2019-08-06T18:04:11.175809Z", "status": 1, "media": [] } ] } -
How to Make Blog Title Unique to User?
I was wondering how to enforce that the blog post title created by a user does not match the name of any other blog posts created by that user. Here is my models.py, as I think this is where it should go, but I can add any other files as needed. Thanks in advance for any tips. models.py class Item(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) name = models.CharField(max_length=50) category = models.CharField(max_length=99) image = models.ImageField(upload_to='images/') #todo: validate size or resize here # ... edited out some fields for SO post slug = models.SlugField(editable=False) def save(self): if not self.id: #new item object, setting slug: self.slug = slugify(self.name) super(Item, self).save() -
How do I set initial request.user as initial modelform data?
I've tried many options but none have worked. I want to initialize a form with logged in user as initial data. #My form class AdaugaPorumbel(forms.ModelForm): class Meta: model = Porumbei fields = ['data_adaugare', 'crescator', 'serie_inel', 'anul', 'culoare', 'culoare_ochi', 'sex', 'ecloziune', 'rasa', 'linie', 'nume', 'tata', 'mama', 'compartiment', 'status', 'data', 'vaccinat', 'info', 'imagine', 'imagine_ochi'] widgets = { 'ecloziune': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'data': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'vaccinat': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'info': forms.Textarea(attrs={'class': 'form-control mt-15', 'rows': '3', 'placeholder': 'Vor apărea în pedigree'}), } # My view @login_required(login_url='/auth/login/') def porumbelnou(request): if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES, initial={'crescator': crescator}) if form.is_valid(): form.save() return HttpResponseRedirect('/porumbei/vizualizare') else: form = AdaugaPorumbel() context = { 'form': form, } template = loader.get_template("adaugare-porumbel.html") return HttpResponse(template.render(context, request)) # I've already try but still won't working if form.is_valid: form.save(commit=False) form.crescator = request.user form.save() ... On models, crescator field is a foreignkey set to settings.AUTH_USER_MODEL. -
Is there a way to inherit the template of an abstract parent model class in Wagtail?
I've got an abstract Page model that defines common fields for a type of page that I then subclass to restrict the types of subpages allowed. I'd like all of the subclasses of this abstract model to default to using the template defined in the abstract model, but it seems like they don't. class BaseListing(Page): empty_message = RichTextField() intro = RichTextField() template = 'listing.html' class Meta: abstract = True class BlogListing(BaseListing): subpage_types = ['BlogPost'] I'd like wagtail to default to using the template defined in the BaseListing model, but it looks for a blog_listing.html template unless I specifically set template on the BlogListing model like this: class BlogListing(BaseListing): subpage_types = ['BlogPost'] template = 'listing.html' -
Aggregate table data in django
I am working on a Django project, and I have a model with the following columns: course id, username date activity_type activity_action count where activity_type can be : video, problem, question and activity_action can be: viewed, solved, asked I am trying to figure out a Django query that given a course id, will return me the following: username number of videos viewed by user for the entire course number of videos viewed by user in last week number of problems solved by user for the entire course number of problems solved by user in last week .... the latest date of user activity is using a single query make sense, or should I simply pull data and manipulate it in code? -
How can I template filter backwards two different models?
I've got three models, "Property", "Owners" and "ContactsOwner", these last one is where I save the owners contacts. # APP: Owners - models.py class Owner(models.Model): name = models.CharField(db_column='Owner_Name', max_length=200) surname = models.CharField(db_column='Owner_Surname', max_length=30) nif = models.IntegerField(db_column='Nif_Number', blank=False, null=False, default='000000000') doc_number = models.CharField(db_column='Document_Number', max_length=20, blank=True, null=True) doc_type = models.CharField(db_column='Document_Type', max_length=20, blank=True, null=True, choices=DOCUMENT_TYPE_CHOICES) address = models.CharField(db_column='Address', max_length=200, blank=True, null=True) post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) nationality = models.CharField(db_column='Country', max_length=20, blank=True, null=True) notes = models.CharField(db_column='Notes', max_length=250, blank=True, null=True) property = models.ManyToManyField(Property) class Meta: db_table = 'Owner' def __str__(self): return self.name def get_absolute_url(self): return reverse("owners:owner_detail",kwargs={'pk':self.pk}) class ContactsOwner(models.Model): owner = models.ForeignKey(Owner, models.DO_NOTHING, db_column='Owner', related_name='owner_contact') # Field name made lowercase. type = models.CharField(db_column='Type', choices=CONTACT_TYPE_CHOICES, max_length=25, blank=True, null=True) # Field name made lowercase. number = models.IntegerField(db_column='Number', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='Email', max_length=100, blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'Contacts_Owner' verbose_name_plural = "Owners Contacts" # APP: Properties - models.py class Property(models.Model): property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase. address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase. post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase. bedrooms = models.IntegerField(db_column='Bedrooms', … -
Django (Python) The .py file is seen as a .txt file
Why is urlsp.py treated as a .txt file and not as a .py? I tried to remove and re-create the file and even reinstall the program but it doesn't work. Screen -
CSRF Warning! State not equal in request and response
I'm trying to use the google classroom api for a django project. For it I used the oauth2.0 which works until the authorization. But when it redirects and calls the oauth2callback function it gets an error in the flow.fetch_token(). The error is - MismatchingStateError at /google-class/oauth2callback/ (mismatching_state) CSRF Warning! State not equal in request and response. How do I solve this? I followed the instruction from here- https://developers.google.com/identity/protocols/OAuth2WebServer#creatingcred The urls - path('profile/',views.profile, name='profile'), path('google-class/',views.profile_g, name='profile_g'), path('piazza/',views.profile_p, name='profile_p'), path('google-class/oauth2callback/', views.oauth2callback, name='oauth2callback'), And in the views.py def profile_g(request): if request.method =='POST': if 'credentials' not in request.session: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES) flow.redirect_uri = 'http://127.0.0.1:8000/google-class/oauth2callback/' authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') request.session['state'] = state some = state print("/n" + "The state is =" + state + "/n") return redirect(authorization_url) else: return render(request,'api/profile.html') def oauth2callback(request): state = request.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES, state=state) flow.redirect_uri = 'http://127.0.0.1:8000/google-class/oauth2callback/' authorization_response = request.get_full_path() # print(request.get_full_path()) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials request.session['credentials'] = credentials_to_dict(credentials) if 'credentials' in request.session: # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( request.session['credentials']) service = build(API_SERVICE_NAME,API_VERSION, credentials=credentials) # Call the Classroom API results = service.courses().list(pageSize=10).execute() courses = results.get('courses', []) if not courses: print('No courses found.') else: print('Courses:') for course in courses: print(course['name']) return … -
Django how to mark_safe specific tag in text
I have some text and I want to mark_safe only a specific tag. I wrote a filter, but cant understand how to return a right result. from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() @register.filter(name='strong_safe') @stringfilter def strong_safe(value): list = value.split() res = [] for l in list: if l.startswith('<strong>'): res.append(mark_safe(l)) else: res.append(l) return ' '.join(res) I know that join convert save_str to str, also I read about format_html and format_html_join but can't understand how to use it in an appropriate way in my code. -
Incorrect Credentials
I create custom user model that extends from AbstractBaseUser. I try to connect this model with API using rest framework the register EndPints, getUser and logout is working fine. But when i try to login user it show this message 'Incorrect Credentials' i try to find the problem and I discover that method authenticate don't work for some resnes This is My Code urls.py from django.urls import path, include from knox import views as knox_views # import views from .views import RegisterAPI, LoginAPI, UserAPI urlpatterns = [ path('api/auth', include('knox.urls')), path('api/auth/register', RegisterAPI.as_view()), path('api/auth/login', LoginAPI.as_view()), path('api/auth/user', UserAPI.as_view()), path('api/auth/logout', knox_views.LogoutView.as_view(), name='knox-logout'), ] custom user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # cerate user manger (replace old user Table with User Table that we cerated) class UserManager(BaseUserManager): def create_user(self, phone, password=None, username=None,is_staff=False, is_admain=False, active=True,**extra_fields): if not phone: raise ValueError("User must have a phone number") if not password: raise ValueError("User must have password") user = self.model(phone=phone) user.set_password(password) user.username = username user.staff = is_staff user.admain = is_admain user.active = active user.save(using=self.db) return user def create_staff(self, phone, password=None, username=None,**extra_fields): user = self.create_user(phone, password=password,username=username,staff=True) return user def create_superuser(self, phone, password=None, username=None,**extra_fields): user = self.create_user(phone,password=password,username=username) user.staff = True user.admin = True user.save(using=self._db) return user # … -
I am getting forbidden error while i am sending file through ajax
i am trying to send a csv file and bunch of data through ajax getting Forbidden (CSRF token missing or incorrect.) error while sending csrftoken one more thing ,i checked i am getting different token in code and cookies so i tried. https://docs.djangoproject.com/en/2.2/ref/csrf/ docs as well but no luck could you please help me out here -
How to I do a INNER JOIN and WHERE, from second table, on a Django Model and return the JSON?
Trying to use the Django models and do a INNER JOIN on a specific column and then doing a WHERE on a column which is in the second table. I want the following command: SELECT * FROM Songs INNER JOIN Artists ON Songs.PageURL = Artists.PageURL WHERE IsSingle = 1 AND Artist like 'Singer%' ORDER BY Entry_At DESC Here is my models.py from django.db import models class Artists(models.Model): artist = models.CharField(db_column='Artist', max_length=400) # Field name made lowercase. pageurl = models.CharField(db_column='PageURL', primary_key=True, max_length=400) # Field name made lowercase. albumurl = models.CharField(db_column='AlbumURL', max_length=400) # Field name made lowercase. class Meta: managed = False db_table = 'Artists' unique_together = (('pageurl', 'artist'),) class Lyrics(models.Model): lyrics = models.CharField(db_column='Lyrics', max_length=400) # Field name made lowercase. pageurl = models.CharField(db_column='PageURL', primary_key=True, max_length=400) # Field name made lowercase. albumurl = models.CharField(db_column='AlbumURL', max_length=400) # Field name made lowercase. class Meta: managed = False db_table = 'Lyrics' unique_together = (('pageurl', 'lyrics'),) class Music(models.Model): music = models.CharField(db_column='Music', max_length=400) # Field name made lowercase. pageurl = models.CharField(db_column='PageURL', primary_key=True, max_length=400) # Field name made lowercase. albumurl = models.CharField(db_column='AlbumURL', max_length=400) # Field name made lowercase. class Meta: managed = False db_table = 'Music' unique_together = (('pageurl', 'music'),) class Songs(models.Model): index = models.IntegerField(db_column='ID') # Field name made … -
How to use two different templatetags in two apps in django?
Say I have a project and two registered apps. Inside my apps I created templatetags package with custom tags that I want to use in corresponding html templates: Project | | --App1 | |----templatetags | |----custom_tags.py |----__init__.py --App2 | |----templatetags | |----custom_tags.py |----__init__.py And it looks like django sees only one templatetags folder. I use {% load custom_tags %} in html templates in both apps. When there is only one templatetags folder then corresponding custom tags work (so there is no error in custom_tags.py). I tried to rename one file to eg 'custom_tags_app1' and then {% load custom_tags_app1 %} in html templates in app1, but then it throws error saying: 'custom_tags_app1' is not a registered tag library. Must be one of: . . custom_tags ... When I renamed it I tried to import 'custom_tags_app1' in the shell and it worked What am I missing here? What should I do to make it work, when they both work independently, but don't work together? -
Django error:view must be a callable or a list/tuple in the case of include()
Well im new to Django and im following outdated course (its free obv) and ran up to this error. What can i change in my code> Here are codes from views.py and urls.py from both folders: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("This is teh index view!") #next one from django.urls import include, path from msg import views urlpatterns = path('', r'^$',views.index,name = "index") #next one from django.contrib import admin from django.urls import path from msg.urls import urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('msg/', urlpatterns), ] after trying to makemigrations i get this error : TypeError: view must be a callable or a list/tuple in the case of include(). -
Django: Moving .py files into a folder to tidy up
I have a Django project and I thought it would be good to tidy things up and put all my .py files into a folder. My directory structure initially was the fairly straightforward: [site] ├── [mysite] │ ├── __init__.py │ ├── admin.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── manage.py And now I have moved all of those .py files except __init__.py into the folder py. [site] ├── [mysite] │ ├── __init__.py │ └── [py] │ ├── admin.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── manage.py To ensure that this will work I went through and changed all the references to files to their new location. For example in manage.py I changed: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") to if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.py.settings") I did this for all the references I could find. But the problem I am facing now is admin.py does not seem to be referenced or imported anywhere and when I make changes to it now it does not cause my test server to restart, so it is obviously disconnected from the project. Is there some way to point Django to the new … -
inserting API data into html via django models
I have created a function that allows me to loop through some data from an API I am using. I have tested this outside the Django model and works as intended. Now I would like to put my code within a Django model so i can use the data within an HTML page. I would like each of the values to be used within html tags as I am creating a table of jira tickets. I have tried to work along with the following: Using APIs within Django and how to display the data from a previous test, which worked. It seems that I cant do it with the function I have created. The below is the function i have created. def get_jira_tickets(): jira_url = 'https://domain.atlassian.net/rest/api/2/search?jql=project=CS' jira_r = requests.get(jira_url, auth=( 'paulb@domain.com', 'API_KEY')) data = jira_r.json() client_name = '[client_name]' client_ID = '[client_ID]' for ticket in data['issues']: ticket_number = ticket['key'] summary = ticket['fields']['summary'] assignee = ticket['fields']['assignee']['name'] status = ticket['fields']['status']['name'] updated = dateutil.parser.parse(ticket['fields']['updated']) ticket_url = 'https://domain.atlassian.net/browse/' + ticket['key'] client = ticket['fields']['customfield_10907'][0]['value'] if status != 'Closed' and client_name in client and client_ID.upper() in client: ticket_dict = { 'ticket_number': ticket_number, 'summary': summary, 'assignee': assignee, 'status': status, 'updated': updated, 'url': ticket_url, 'client_id': client } return ticket_dict … -
Stuck while iterating in the django template
I have this dictionary:- a = {'title': ['Turning a MacBook into a Touchscreen with $1 of Hardware (2018)', 'Supercentenarians are concentrated into regions with no birth certificates', 'Open list of GDPR fines so far'], 'url': ['https://www.anishathalye.com/2018/04/03/macbook-touchscreen/', 'https://www.biorxiv.org/content/10.1101/704080v1', 'https://github.com/lknik/gdpr/blob/master/fines/README.md'], 'type': ['story', 'story', 'story'], 'n': [0, 1, 2]} I passed it into the template. Now, what I want is to get the first 'title' along with the 'type', with its 'url'. I tried the following code:- <ul> {% for i in n %} <br/> {{i}} <li>{{title.i}}</li><br/> <li>{{url.i}}</li> {%endfor%} But couldn't get the desired output. My desired output is:- Title: Turning a MacBook into a Touchscreen with $1 of Hardware (2018) URL: https://www.anishathalye.com/2018/04/03/macbook-touchscreen/ TYPE: story In this way a continuous list of Titles followed by url and type. The output I get is a blank screen. Please help me out. -
Temporarily disabling foreign key constraint checking during bulk_create in django with mariadb backend
I'm attempting to generate large amounts of dummy data programmatically in django and Model2FK references two models, Model1 and Model2 which have more than 10M records. I have been using bulk_create to generate the Model2FK data, but generating 10,000 objects with a batch size of 1,000 takes ~120 seconds. This isn't efficient enough to generate the data in a reasonable amount of time (it currently would take over a week to generate all the data I require). I suspect that this is slow because django or mariadb is performing checks on the foreign keys for each created object, and this is resulting in long lookup times as the database looks up both references to ensure they exist. Since I am generating the data myself I know that the keys exist and would like to skip this step. I've tried using SET FOREIGN_KEY_CHECKS=0; in mariadb to disable foreign key checks, but it seems to only update for that mariadb session, and so doesn't reflect in my django script. Furthermore, I'd like to be able to manage this entirely in my django script if possible so that I do not need to connect to the database each time I need to run … -
google social authentication django rest api
I am setting up a django rest api and need to integrate social login feature.I followed the following link Simple Facebook social Login using Django Rest Framework. # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '****' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '*****' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email'] Above is my settings file configuration of google. After setting up all, facebook authentication working finely.In the case of google authentication , when i uses the access token of same account of which developer account is created(configured in settings.py) is given , social authentication is working.But when i uses access token of different account following error is occuring AuthForbidden at /user/oauth/login/ Your credentials aren't allowed Why it is happening so? Do i need to configure anything in the google developer account? -
Set global exception handler from inside a thread (in Django)
I know about this python bug, which does not allow sys.excepthook to be used from inside a thread. A recommended workaround is to surround the thread's run method with try/except. However, since I am using Django, I am already locked in in Django main thread. So: Is there any way to globally catch exceptions in Django? -
Django in one serialize pull out child objects
This my models class Dictionary(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parentId = models.UUIDField(editable=True, null=True) name = models.CharField(max_length=100) date_create = models.DateTimeField(auto_now=True) date_end = models.DateTimeField(auto_now=False, null=True) class Teacher(models.Model): name = models.CharField(max_length=100) message = models.CharField(max_length=300) status = models.OneToOneField(Dictionary, on_delete=models.CASCADE) this is my urls from django.urls import path from . import views urlpatterns = [ path('get', views.GetViewSet.as_view({'get': 'list'})), ] This is ViewSet class GetViewSet(viewsets.ModelViewSet): MyApiObj = null @property def api_object(self): return namedtuple("ApiObject", self.request.data.keys())(*self.request.data.values()) def get_serializer_class(self): GeneralSerializer.Meta.model = apps.get_model(app_label=self.MyApiObj.app, model_name=self.MyApiObj.object) return GeneralSerializer def post(self, request): self.MyApiObj = self.api_object return self.select_api() def select_api(self): queryset = QueryHelper.select(self.MyApiObj) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Serializer class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None fields = '__all__' My post parameters to django { "app":"leads", "object":"Teacher", "settings":{ }, "data":{ } } answer: [ { "id": 1, "name": "John", "message": "Hi everyone", "status": "e3b86ed4-8794-413b-994c-b1ec0a43eebe" } ] Problem is Dictionary(status) model give me id(uuid) but i need whole object without creating new serializer for Dictionary. i do univeral serializer for all models in my app Try this: class DictionarySerializer(serializers.ModelSerializer): class Meta: model = Dictionary fields = '__all__' class GeneralSerializer(serializers.ModelSerializer): status = DictionarySerializer(required=True) class Meta: model = None fields = '__all__' But it is not good for me because 1) Without other serializer 2) … -
List all the compositions by a specific composer in their profile details page
I want a public page showing the profile of a specific user (so I cannot grab the user id from the logged-in users). I'm not able to select their specific compositions. I am using a custom user model, so that I have a User class and then a Profile class which is linked to the User via OneToOneField (see code below). I also have a Composition class, which is linked to a specific composer via a ForeignKey. I am able to get the details of a specific profile and I'm also able to print out all the compositions (using Composition.objects.all()). My models.py: email = models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) [...] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) [...] def get_absolute_url(self): return reverse('profile', args=[str(self.id)]) class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def get_absolute_url(self): return reverse("composition-detail", kwargs={"id": self.id}) def __str__(self): return "%s" % (self.title) My views.py: compositions = Composition.objects.filter(composer__id=id) context = { "object_list": compositions } return render(request, "profile.html", context) My urls.py: path('profile/<int:id>/', views.profile_details, name='profile') My template.html: {% for composition in object_list %} <li><a href="{{ composition.get_absolute_url }}">{{ composition.title }}</a></li> {% endfor %} [...] I'm expecting to see the compositions by … -
Retrieve automatically-set values from DRF serializer
I have a model where certain fields are automatically set (timestamp, pk). # models.py class thisModel(models.Model): timestamp = models.DateTimeField(auto_now_add=True) topic = models.CharField(max_length=50) message = models.CharField(max_length=100, default='') Below is my serializer: # serializer.py class thisSerializer(serializers.ModelSerializer): class Meta: model = thisModel fields = ('pk', 'topic', 'timestamp', 'message',) When creating my model, I need only specify the topic and message. data={} data['topic'] = 'paper' data['message'] = 'This is a message' serializer = thisSerializer(data=data) if serializer.is_valid(): # True serializer.save() # I would like to retrieve the PK and Timestamp here The model is created, but I have no way of retieving that model as I have no unique identifier for it. Doing serializer.data['topic'] and serializer.data['message'] returns these fields as intended. Doing serializer.data['pk'] returns an error: KeyError: 'pk' Any idea on how to retrieve these fields? -
How to validate form after putting in custom values in the view?
I am using custom forms where based on a button the user clicks, a different form loads. All of that is working but the form doesn't correctly validate it. I have changed the post form button to run my own ajax script. I pull the data from the form and then I post it along with the value of the certain option that they clicked. I then have the view get the correct form based on that option, and try to see if it is valid or not. The issue is, I can't get the data into the form the way I need for it to check it correctly. Here's the code views.py def step_form(request): if request.method == 'POST': step_type_id = request.POST.get('step_type_id') print(step_type_id) step_type = StepType.objects.get(pk=step_type_id) flow_id = request.POST.get("formData[flow]") print(flow_id) flow = Flow.objects.get(pk=flow_id) print(flow) order = request.POST.get("formData[order]") url = request.POST.get("formData[url]") passed = request.POST.get("formData[passed]") if passed == 'false': passed = False elif passed == 'true': passed = True else: passed = None print(passed) desired_result = request.POST.get("formData[desired_result]") fixture = request.POST.get("formData[fixture]") form_data = {'flow': flow, 'order': order, 'url': url, 'passed': passed, 'desired_result': desired_result, 'fixture': fixture} form = StepForm(step_type_id, form_data) print(form) if form.is_valid(): step = Step.objects.create(flow=flow, step_type=step_type, desired_result=desired_result, fixture=fixture, passed=passed, url=url ) step.save() return …