Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channel consumer sending message twice to the frontend
I'm trying to build a simple chat application using django channels using simple websocket. it is working fine but when i'm sending message to other user it is appearing twice on both end I think consumer chat method is calling twice. i can't figure out how to solve this issue! group send function I think doing this it is echoing back its user and sending that particular message to other user as well Here is the consumer class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): room_name = data['room_name'] room = Room.objects.filter(room_name=room_name).first() sender = data['from'] receiver = data['to'] sender = User.objects.filter(username=sender)[0] receiver = User.objects.filter(username=receiver)[0] messages = Message.objects.fetch_last_10_messages(room.room_name,sender.id,receiver.id) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): room_name = data['room_name'] room = Room.objects.filter(room_name=room_name).first() sender = data['from'] receiver = data['to'] sender = User.objects.filter(username=sender)[0] receiver = User.objects.filter(username=receiver)[0] message = Message.objects.create( sender=sender, receiver=receiver, room=room, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) room = Room.objects.get_or_create_personal_room(me, other_user) self.room_name = … -
Django doesn't print array variable in template
In my django controller function I get "annotations" of a specific web server from database. For all annotations I build annotationsId, annotationsCode, annotationsName array. They are annotationsId = [1, 2, 3, 4, 5] annotationsCode = ['codicefiscale', 'partitaiva', 'telefono', 'data', 'targa'] annotationsName = ['codice fiscale', 'partita iva', 'telefono', 'data', 'targa'] I pass these arrays to view_process_show_saveandanalize.html through tmplAnnVar. My output is this <li><a class="dropdown-item active" href="#" data-active="1" data-annotation-web-server-id data-annotation-code data-func></a> </li> As you can see microdatas (data-annotation-web-server-id example) don't have a value. def show_results(request): #verifico che L'utente abbia scelto un server di annotazioni isChooseWebServer = False userId = int(request.session['id']) userWebServerDao = UserWebServerDAO() userWebServerRec = userWebServerDao.getUserWebServer(userId) userWebServerRec = userWebServerRec[0] idWebServer = userWebServerRec["web_server_id"] if idWebServer > 0: isChooseWebServer = True isThereAnnotation = False #ottengo la lista delle annotazioni del server scelto dall'utente annotationWebServerDao = AnnotationWebServerDAO() annotations = annotationWebServerDao.getAnnotationsWebServer(idWebServer) if len(annotations) > 0: isThereAnnotation = True annotationsName = [] annotationsCode = [] annotationsId = [] i = 0 for annot in annotations: print(annot) annotationsId.append(annot["annotation_web_server_id"]) annotationsCode.append(annot["annotation_code"]) annotationsName.append(annot["annotation_name"]) i = i + 1 print(annotationsCode) print(annotationsName) print(annotationsId) messageSaveAndAnalize = "" if isChooseWebServer is False: messageSaveAndAnalize = "imposta server annotazioni" elif isThereAnnotation is False: messageSaveAndAnalize = "Non ci sono annotazioni per il server scelto." tmplAnnVar = {} tmplAnnVar["messageSaveAndAnalize"] … -
Make a POST request to a View from a Django static Javascript file
I'm currently making a POST request to my view on Django. I am doing this in my HTML file. Post request: class EventDetailView(DetailView): model = Event def post(self, request, *args, **kwargs): return xyz HTML: <form method="post" onsubmit="return confirm('Confirm?');">... </form> How can I create this post request from a static Javascript file that my HTML file interacts with instead of from the HTML File. Thanks in advance for your help. -
Django and React : [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
I added the encryption type for the form 'multipart/form-data' same thing in axios call too, but i still get the same error. I have a model like this: class MyModel(models.Model): img = models.ImageField(upload_to='media',blank=False) in views.py: class MyModelView(viewset.ModelViewSet): serializer_class = serializer.MyModelSerializer def post(self,request): data = serializer.MyModelSerializer(data=request.data) print(data.is_valid()) # this is false, means there is an error print(data.errors) #This one will display the error shown in the title of this question if data.is_valid(): img = data.data['img'] return Response('Success') return Response('Fail') in serializer.py: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' in frontend side (React) function ImgComp(){ let [img,setImg] = useState({'image':''} let {image} = img function handleChange(e){ setImg( { ...img,[e.target.name]:e.target.value } ) } function submitForm(e){ e.preventDefault() axios.post('127.0.0.1:8000/mymodelurl/',img,{withCredentials:true,headers:{'Content-Type':'multipart/form-data'}}) return( <div> <form method='post' encType='multipart/form-data' onSubmit = {(e)=>submitForm(e)}> <input type='file' value={image} name='img' onChange={(e)=>handleChange(e)}/> </form> </div> } } if i debug the img i get something like : C:\\fakepath\\img.png any help is appreciated. -
How do I fully authenticate a test user in my test cases with django-two-factor-auth to access OTPRequiredMixin views?
I'm trying to write test cases for my class views that are secure behind django-two-factor-auth OTPRequiredMixin. I'm not sure how to write the setUp function to fully authenticate the user through OTP. I've tried self.client.force_login() but when I try to browse to that url in my test function, I am landing on the "Permission Denied" page that prompts to enable two-factor authentication for the user, instead of the expected url. Permission DeniedThe page you requested, enforces users to verify using two-factor authentication for security reasons. You need to enable these security features in order to access this page.Two-factor authentication is not enabled for your account. Enable two-factor authentication for enhanced account security. Here's an example of one of the class views: class ProjectCreateView(OTPRequiredMixin, CreateView): model = Project template_name = 'project_create.html' fields = ['name', 'description'] And here's an example of my setup and a test: class ProjectTestCase(TestCase): def setUp(self): self.user = get_user_model().objects.create( username='jsmith', first_name='John', last_name='Smith', email='johnsmith@test.com', password='secure' ) [...] self.client.force_login(self.user) def test_project_create(self): response = self.client.post( '/project/create/', {'name': 'Test Project', 'description': 'A basic test project'} ) self.assertEqual(response.status_code, 200) Thanks in advance for your insight and wisdom! -
Is there a way to pass a secret Heroku environment variable in my Django project to a static Javascript file?
I don't have a lot of website experience. I'm trying to get my site up and running. I have a secret environment variable on my Heroku app that I want to pass into a static file. Is there a way to do this securely? I've decided I don't care if bad actors can see the file, I just don't want them seeing the key. -
Second fetch in sequence of two doesn't seem to have access to data returned from first fetch
I want to query a (django) server for an (RESTful) API schema, then use that schema for subsequent list and CRUD operations as may be defined therein. I'm using OpenAPI to autogenerate the schema, server-side. Trying to get a client-side API working was taking too long, so I switched to just using fetch instead. The first fetch hits the endpoint that serves the API schema, and works fine. The problem arises when I try to dereference a string within the returned schema in my second fetch call - this one to retrieve a list of "widget" objects from my server. I found a way past this by simply assigning the string I needed to another const within the same function, then passing this to the second fetch. This works, but I don't understand why I need to do this to be able to use data from the first call. I'm able to reference it by console.logging it. I can see it using the browser's debug console. But, for whatever reason, a reference to anything in the object returned by the first fetch becomes undefined in the second (or any subsequent?) fetch. Can someone who understands javascript internals well explain this, … -
Create superuser without password
I have implemented custom user as follows: class UserManager(BaseUserManager): def _create_user(self, email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields): if not username and (is_superuser or not number or not shop): raise ValueError('Users must have a username') now = timezone.now() email = self.normalize_email(email) user = self.model( username=username, email=email, shop=shop, number=number, is_superuser=is_superuser, total_points=total_points, used_points=used_points, last_login=now, date_joined=now, is_staff=is_staff, **extra_fields ) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(**{'{}__iexact'.format(self.model.USERNAME_FIELD): username}) def create_user(self, email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields): return self._create_user(email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields) def create_superuser(self, email, username, password=None): user = self.model(email=email, username=username, shop=None, is_superuser=True, total_points=0, used_points=0, is_staff=True) user.is_superuser = True user.is_staff = True user.shop = Shop.objects.create(name="openformat") user.save(using=self._db) return user class AbstractUser(AbstractBaseUser): uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=64, unique=True) email = models.EmailField() number = models.CharField(max_length=20) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(null=True, blank=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] class Meta: abstract = True class User(AbstractUser, PermissionsMixin): shop = models.ForeignKey(Shop, null=False, blank=False, on_delete=models.CASCADE) total_points = models.IntegerField(default=0) used_points = models.IntegerField(default=0) objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.uid) def has_perm(self, perm, obj=None): return self.is_superuser def get_full_name(self): return self.username def get_short_name(self): return self.username def __str__(self): return self.username … -
Django Login form issue
Views.py def Tourist_login(request): if request.method == 'POST': form = Tourist_login_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username,password=password) print(user) if user is not None: login(request,user) messages.success(request,'logged in') return redirect('home') else: messages.error(request,"Invalid login credentials!") return redirect('touristlogin') else: return redirect('touirstlogin') else: form = Tourist_login_form() return render(request,'accounts/tourist_login.html',{'form':form}) In the above code , authenticate function returns none value. But if I'm passing input in form through superuser credentials then it is working fine. I'm not able why is it not taking the username and password passed by the user and only taking superuser username and password. -
Graph_helper.py Send on behalf of another user - Django
I have the following code (graph_helper.py), which I copied when completing the Microsoft Graph - Django. The create_event and create_online_event functions works fine for the logged in user. What I ideally need is rather than the calendar events coming from the logged in user, they come from another shared mailbox they have access to. I have tried adding into additional properties including organiser and isOrganiser but these didnt work. https://docs.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0 I also tried editing the below requests.post in the create_events to include the calendar id I want the invites to come from but still no luck. https://docs.microsoft.com/en-us/graph/outlook-create-event-in-shared-delegated-calendar?tabs=http#code-try-0 requests.post('{0}/me/events'.format(graph_url), headers=headers, data=json.dumps(new_event)) Appreciate any help I can get with this issue. I know I can sign in as the shared account but will be better if I can set this up to allow sending on behalf of the logged in user. Graph_helper.py import requests import json graph_url = 'https://graph.microsoft.com/v1.0' def get_user(token): # Send GET to /me user = requests.get( '{0}/me'.format(graph_url), headers={ 'Authorization': 'Bearer {0}'.format(token) }, params={ '$select': 'displayName,mail,mailboxSettings,userPrincipalName' }) # Return the JSON result return user.json() def get_calendar_events(token, start, end, timezone): # Set headers headers = { 'Authorization': 'Bearer {0}'.format(token), 'Prefer': 'outlook.timezone="{0}"'.format(timezone) } # Configure query parameters to # modify the results … -
Javascript code is not displaying in django
here Javascript code is not displaying in Django. even before I did lot of research on it but unable to find. I really don't know what to do here. please anyone guide me how to do this. This help will be precious for me. static/js/script.js: var bar = new ProgressBar.Circle(container, { color: '#ff0000', // This has to be the same size as the maximum width to // prevent clipping strokeWidth: 4, trailWidth: 1, easing: 'easeInOut', duration: 10000, text: { autoStyleContainer: false }, from: { color: '#ff0000', width: 5 }, to: { color: '#00cc00', width: 9 }, // Set default step function for all animate calls step: function(state, circle) { circle.path.setAttribute('stroke', state.color); circle.path.setAttribute('stroke-width', state.width); var value = Math.round(circle.value() * 100); if (value === 0) { circle.setText(''); } else { circle.setText(value); } } }); bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif'; bar.text.style.fontSize = '2rem'; bar.animate(1.0); // Number from 0.0 to 1.0 html file: <div id="container"></div> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] I'm getting correct output in command prompt but it is not displaying on template. output in cmd: "GET /static/js/script.js HTTP/1.1" 304 0 -
How to make a for loop break on counter in jinja2?
How can I make the for product in products loop break after the if condition is fulfilled 3 times. I have been trying to set up a counter but that isn't working... because set is not accepted inside of for loops. Though testing it out a bit more it isn't being accepted anywhere. When I use set it throws this exception or a variation of it: Invalid block tag on line 11: 'set', expected 'endblock'. Did you forget to register or load this tag? I am aware that I should put all the logic I'm using jinja2 for inside of the view and then pass it through the dictionary but it would take too much time to research everything about that and i just want to be done with this. Honestly I am really tired it is 6am and idk what to do. Thank you for your help in advance. :) HTML {% for category in categories %} <div> <h5 class="text-line"><a href="" class="store-category"><span>{{category.name}}</span></a></h5> </div> <!-- Cards Container --> <div class="shop-cards"> {% set counter = 0 %} {% for product in products %} {% if product.category.categoryID == category.categoryID %} <!-- CARD 1 --> <div class="card"> <image class="product-image" src="{% static 'images/product-4.png' %}"></image> … -
Django Vs Laravel for Web Development
I saw this But I am still confused. I started web development with vanilla PHP and was recently informed about a Python framework Django. So my question is, what's the point and benefit of using Django, PHP is designed directly to plug into a web page, whereas Django goes around the bush, and if you prefer a framework, there is Laravel, but for some reason, PHP is getting disrespected by developers. I understand that Python might be a more simple syntax, so easier to write and read, but is there anything else? And is worth learning Python, just for making web apps? Please trow your opinion and your advice will be very appreciated. Thanks -
Django for loop only parsing first row from json data on html template
I am able to access the entire json data when I make the call to the themoviedb api in the DOM, but when I try to loop/print it as an html template, it only parses the first row of the json object. How do I access the entire search results from the json object? def index(request): post = Show.objects.all().order_by('title') for lists in post: data = requests.get(F"https://api.themoviedb.org/3/search/tv?api_key={api_key}&language=en-US&page=1&include_adult=false&query={lists}") r = data.json() pprint(r) -
where is going data from <select> box
ive wrote a code to practice html and python i used django to build a add music page its for uploading musics the whole form used models and i know wheni i want to save sth its all related together but i added another option today for tags this option is not in form nor models its just in html file so what will happen if i choose and press submit and also if i want to make same in model how should i do {% extends 'pages/base.html' %} {% block content %} <!DOCTYPE html> <head> <meta name="description" content="page of adding music"> <meta name="keywords" content="music,upload_music"> <title>adding music</title> </head> <body> <p>here you can upload music</p> <form action="{% url 'pages:add_music' %}" method='post' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <div> <h3 style="border:2px blue; color:blue;">tags:</h3> <select style="padding: 4px;" id="tags" name="tags" multiple required="required" size='6'> {% for tag in tags %} <option value="{{tag}}">{{tag}}</option> {% endfor %} </select><br> </div> <button type='submit' value="submit" style="margin: 20px; background-color: yellow; color: green;">add</button> </form> </body> {% endblock %} -
Secure way to accept payments on Django Heroku?
I'm trying to accept payments on Django using Heroku. I've had a ton of issues using Stripe because I don't know much about client-side/server-side and every time I get something that works, I have to expose my private key. I feel like there's no resource out there for this. Does anyone have something that can help? -
Django inspectdb lost comment
I use mysql to test model.with django_comment_migrate save help_text to sql comment. Original model.py below: from django.db import models class Foo(models.Model): name = models.CharField(max_length=20, verbose_name='alias_name', help_text='alias_name') Run python manage.py inspectdb got result below, lost help_text. class App1Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20) class Meta: managed = False db_table = 'app1_foo' -
Django class variable to instance variable
It seems like name and tagline would be class variables, how have they managed to define name and tagline as instance variables. Creating an instance of blog would be like Blog(name='...', tagline='...'). Wouldnt the variable be available like so, Blog.name and Blog.tagline class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name -
DateField Django default does not apply to database:
When doing the basic models on my django app, I have encountered this issue: The model for a Product stands like this in my app: main_color = models.CharField(max_length=15) secondary_color = models.CharField(max_length=15) brand = models.CharField(max_length=30) catalog_inclusion_date = models.DateTimeField(default=datetime.now, blank=True) image_url = models.URLField(max_length=200) description = models.TextField() But the catalog_inclusion_date isn't working as intended. After migrating the models to the MySQL database and attempting to insert an entry on the table with this SQL sentence: INSERT INTO shoppingcart_cap(main_color, secondary_color, catalog_inclusion_date, brand, image_url, description, logo_color) VALUES ('Red', 'Black', 'Adidas', 'https://www.rekordsport.es/uploads/photo/image/4920/gallery_A02506_1.JPG', 'Kid cap', 'White') I get the following output: ERROR 1364 (HY000): Field 'catalog_inclusion_date' doesn't have a default value Thanks in advance. Edit: In MySQL, after doing DESCRIBE cap_table;, I get the following output: CREATE TABLE `shoppingcart_cap` ( `id` bigint NOT NULL AUTO_INCREMENT, `main_color` varchar(15) NOT NULL, `secondary_color` varchar(15) NOT NULL, `brand` varchar(30) NOT NULL, `catalog_inclusion_date` date NOT NULL, `image_url` varchar(200) NOT NULL, `description` longtext NOT NULL, `logo_color` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) -
AttributeError: transform not found in Countvectorizer , using sklearn
Trying to load my spam text detection Machine Learning model in API using Django framework. My error when sending request with text:"Ahmed,,, Awwad.. Test" File "path/to/API.py", line 39, in predict_text vector = selector.transform(clean_text) File "/usr/lib/python3/dist-packages/scipy/sparse/base.py", line 687, in __getattr__ raise AttributeError(attr + " not found") AttributeError: transform not found [30/Jun/2022 00:11:23] "POST /api/spamurai HTTP/1.1" 500 103644 This my model: #convert a collection of text to amatrix of tokens (Bag of words) from sklearn.feature_extraction.text import CountVectorizer from joblib import dump import pickle #process_text previously defined function to preprocess text in model msg_vector= CountVectorizer(analyzer=process_text) message_bow = msg_vector.fit_transform(df['text']) pickle.dump(message_bow, open("vector_text.pkl", "wb")) dump(MultinomialNB,'spam_model_text.joblib') I was using joblib in both dumping but i got many errors with countervectorizer and joblib so i am trying pickle and joblib In my API.py file I load my text vector and MultinomialNB file as follows: from joblib import load from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer MultinomialNB_file = os.path.join(BASE_DIR, 'tutorials/data', 'spam_model_text.joblib') CountVectorize_file = os.path.join(BASE_DIR, 'tutorials/data','vector_text.pkl') txt_model = load(MultinomialNB_file) selector = pickle.load(open(CountVectorize_file, "rb")) # # pre processing email text to be used in ML Model without affecting accuracy of model def process_text(text): #processing_code return clean_text # # function uses trainig utilities used in TEXT ML Model def predict_text(text): # … -
if statement for a specific field in django template
I'm rendering a form in a django template using this model: class Group(models.Model): name = models.CharField(max_length=100) description = models.TextField() members = models.IntegerField(default=0) has_max = models.BooleanField(default=False) max_size = models.IntegerField(default=10) DAYS = [ ('Sundays', 'Sundays'), ('Mondays', 'Mondays'), ('Tuesdays', 'Tuesdays'), ('Wednesdays', 'Wednesdays'), ('Thursdays', 'Thursdays'), ('Fridays', 'Fridays'), ('Saturdays', 'Saturdays'), ] meeting_day = MultiSelectField( verbose_name = 'Meeting day(s)', choices=DAYS, max_choices=6, max_length=100 ) start_time = TimeField(widget=TimePickerInput) end_time = TimeField(widget=TimePickerInput) def __str__(self): return self.name And onto this template: <form method="POST"> {% csrf_token %} {{form.as_p}} <button>POST</button> </form> I have a couple of issues going forward: My first issue is that I only want to have max_size be displayed in my template form if the user clicks has_max. Like a conditional, where once the user checks the box, changing has_max to True then they can enter in the max size of the group. My second issue is that the start_time and end_time to render in my template or on the admin side. I'm not sure how TimePickerInput works, but right now, there are no fields in my template form or admin form that have those time fields. Also, last thing, if I have both names the exact same (i.e., ('Sundays', 'Sundays'), is it necessary to have both? Or can … -
How to adjust the Django PymemcacheCache limit to be over 1MB
A similar question was posted here regarding adjusting the 1mb limit of memcached storage in Django settings. However, the answer was referring to django.core.cache.backends.memcached.MemcacheCache, which has since been deprecated. I tried implementing to provided solution with the django.core.cache.backends.memcached.PyMemcacheCache backend but the provided OPTIONS ('server_max_value_length') is unrecognizable. I can't find the available list of Options for the newer PyMemcache backend from django (at least not any that allow me to adjust the storage limit. My Settings looks like this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': 'cache:11211', 'OPTIONS': { 'server_max_value_length': 1024*1024*10 } } } I am deploying the app in a Python 3 Docker image with a docker-config.yml configuration. The config file relative to memcached looks like: cache: image: memcached ports: - "11211:11211" entrypoint: - memcached - -m 64 - -I 10m When caching views that return JSON Responses with < 1MB data, the caching works great and greatly improves speed. The main objective here is to speed up response times. As far as optimizing the query, its just a simple GET that filters off the authenticated users company. I think pagination would help speed up response time as well, seeing as this is a large list of data being … -
cant get CORS enabled on app inside django
I pip installed django-cors-headers it works on my base application, but wont work on my "rest_api" app. Access to fetch at 'http://localhost:8000/api/groups' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Settings: INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'rest_api', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
How to add the entry, which has foreign key, from frontend having only the pk of fk
Probably not the best heading, but I will try my best to explain the question. I have two models set up in my Django app: class Category(models.Model): class Meta: verbose_name_plural = "Categories" name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + " | " + str(self.author) def get_absolute_url(self): return reverse('post-details', args=(str(self.id))) with respective serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name'] class CategorySerializer(ModelSerializer): class Meta: model = Category fields = ['id', 'name'] class PostSerializer(ModelSerializer): category = CategorySerializer() author = UserSerializer() class Meta: model = Post fields = ['id', 'title', 'author', 'category', 'body', 'post_date'] and a default ViewSet for Post: from rest_framework.viewsets import ModelViewSet class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all().order_by('-post_date') I want to add a new entry by sending an axios POST request to my Django app from the Vue frontend and I would like to do it in such way: const formData = { title: this.title, category: this.category, body: this.body, author: this.$store.state.user_id, } axios({ method: "POST", url: '/api/blog/posts/', headers: {"Content-Type": "application/json"}, data: formData }) .then(response => … -
how can I transform this sql query for use in Django?
SELECT fija.id, concat(fija.nombres," ", fija.apellido1, " ", fija.apellido2) as Nombre, fija.rfc, fija.telefono, fija.fecha_inicio, puesto.puesto, puesto.codigo, group_concat(decl.id) as declaraciones FROM declaracionesSiDeclara.declaracion_infopersonalfija as fija INNER JOIN declaracionesSiDeclara.declaracion_catpuestos as puesto on puesto.id = fija.cat_puestos_id LEFT JOIN declaracionesSiDeclara.declaracion_declaraciones as decl on decl.info_personal_fija_id = fija.id group by fija.id;