Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set command to populate django data through txt file DJANGO
thanks for your time: I got a model that has to be filled with 3 txt documents that got 40 rows each. the command should open each take the line, set the objects, save it, and be called again in a range 40: I'm beeing able to call it 40 times although i the 40 ones are tanking the same last line how can i set a count on the txt file to go to the next line when be called again? should i set a split to get the lines as a list? and set the line like a list index list[counter]? models.py: class MP4 (models.Model): nome = models.CharField(blank=True, max_length=100) url = models.URLField(blank=True, max_length=300) imagem = models.ImageField(blank=True, upload_to='') artista = models.CharField(blank=True, max_length=100, default='Unknown') seeder.py (command): class Command(BaseCommand): file_name = ['nome.txt', 'artista.txt', 'url.txt'] @classmethod def handle(cls, *args, **kwargs): counter = 0 for row in range(40): counter += 1 with open(cls.file_name[0]) as file: for linha in file: nome = linha with open(cls.file_name[1]) as file: for linha in file: artista = linha with open(cls.file_name[2]) as file: for linha in file: url = linha row = MP4( nome=nome, url=url, artista=artista, id=MP4.objects.latest('id').id + 1 ) row.save() nome.txt: Somewhere over the Rainbow ocean drive Michael … -
django rest serializer create save objects but return null
I am creating nested object in serializer it saves in the admin but in response return null value class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='question', null=True) index = models.CharField(max_length=250, null=True) value = models.CharField(max_length=250, null=True) serializer.py class QuestionSerializer(serializers.ModelSerializer): answer = AnswerSerializer(required=True) class Meta: model = Question fields = [#here my field name] def create(self, validated_data): answer = validated_data.pop('answer') instance = Question.objects.create(**validated_data) Answer.objects.create(question=instance, **question) return instance when I save in the postman, it returns this { "id": 28, #... "question": { "index": null, "value": null }, "user": 1 } but it indicates the value in the admin i do not know where I am missing something? How can I solve this issue? -
SQLite to PostgreSQL Not migrates - Django 3.0
Situation I have built Django 3.0 project with a couple of applications. Than I have created an application fro authentication acc All this has been done in an SQLite database Previously I have tried out a PostgreSQL database for the early application that was working fine but now when I switch of in the settings.py file the SQLite to PostgreSQL I get an error i I try to log in If I switch back the settings.py to SQLite everything works perfectly (ex.: authentication, logging in with user, user doing things on the website with it's own settings) I use decorators.py to keep logged in users visiting the login and signup pages and that gives error when I switch to postgresql. I only use here HttpResponse that the error message contains decorators.py from django.http import HttpResponse from django.shortcuts import redirect ... def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('NO AUTHORISATION TO BE HERE') return wrapper_func return decorator ERROR If I log in while settings.py uses PostgreSQL. If I log out everything works out fine again. If I use SQL lite I can … -
Django models reference another attribute within an attribute of the same class
I was trying to build a model for the profile details of the user of my django web app like: class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profilePicture = models.ImageField(blank = True, upload_to='profile_pics/'+self.user.id+'/') country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) I have an image field in the above model and I want to upload the incoming images to the path profile_pics/<id of the user whose profile is being set up>/ within my media storage path. I tried to do that by specifying the upload_to attribute of the image field as upload_to = 'profile_pics/'+self.user.id+'/'. I am using AWS S3 for my media storage and I have put the necessary settings in my settings as: AWS_ACCESS_KEY_ID = 'myaccesskeyid' AWS_SECRET_ACCESS_KEY = 'mysecretaccesskey' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I try to make the migrations, I get the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File … -
how to set config file for WSGIPassAuthorization On for token authentication in django with apache
I am hosting a ubuntu server for django application with djangorestframework with apache webserver. I have a problem with token authentication. All api's works fine on localhost but not works on the server. This response has come when calling to the server. {"detail":"Authentication credentials were not provided."} Some one told me to change its config file and add this line to config file because apache uses its own token authentication as default. WSGIPassAuthorization On So i have added this line to my config file and after that same response is coming. kindly tell me what to do next? views.py class ManageUserView(generics.RetrieveUpdateAPIView): serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self): return self.request.user Serializers.py class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ('id', 'email', 'password', 'user_type') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): """ Create a new user with encrypted password and return it""" print(validated_data) return get_user_model().objects.create_type_user(**validated_data) def update(self, instance, validated_data): """ Update a user, setting the password correctly and return it """ password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user site.conf <VirtualHost *:80> ServerName www.shabber.tech ServerAdmin official.kisaziaraat@gmail.com ServerAlias shabber.tech DocumentRoot /var/www/html … -
Django query for a related object
I have two models Post and UserBookmarks. models.py of Project/App1 from App2 import UserBookmarks class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=20) content = models.TextField(verbose_name="Post Content", max_length=2000) ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') models.py of Project/App2 bookmarkable_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) Now I want to check if the user has already added the post to his bookmarks as my views.py but I don't understand how my query for this has to look like. Currently im doing something like this: if UserBookmarks.objects.filter(user__post__bookmarks=request.user).exists(): messages.error(request, 'You already added this Post to your Bookmarks.') return redirect('post_detail', pk=post.pk) Can smb. explain to me how this query has to look like in order to check if its already existing or not. currently im getting the following error: Cannot query "peter123": Must be "UserBookmarks" instance. -
Django access ForeignKey field and get their values
I`m trying to build a small webshop platform where a user can create a shop, select a category of products and add products to it. To achieve my goal I created this simplified models.py class Organization(models.Model): org_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=255) owned_by = models.OneToOneField(UserProfile, on_delete=models.CASCADE) def __str__(self): return f'{self.company_name} ORG' def get_absolute_url(self): return reverse('org-view', kwargs={'pk': self.org_id}) class Category(models.Model): CATEGORIES = ( ('electric', 'Electronics'), ('food', 'FrozenFood'), ('shoes', 'slippers') ) cat_name = models.CharField(max_length=255, choices=CATEGORIES) def __str__(self): return f'{self.cat_name} Category' def get_absolute_url(self): return reverse('cat-view', kwargs={'id': self.pk}) class Product(models.Model): org_id = models.ForeignKey(Organization, on_delete=models.CASCADE, blank=True, null=True) cat_name = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) def __str__(self): return self.product_name In my views i want to keep the user on a single page where he can manage his shop. My current views.py: class OrganizationDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView, FormMixin): model = Organization queryset = Organization.objects.all() template_name = 'org/org_view.html' form_class = ProductForm def test_func(self): org = self.get_object() if self.request.user.profile == org.owned_by: return True return False def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data() pk = self.object.serializable_value('pk') product = Product.objects.filter(org_id=pk) return self.render_to_response(context) I need help to understand a few things: how to execute the queries to retrieve all of his products and be able to see the category … -
No transition from ASSIGNED viewflow
Previously i had an issue with viewflow as i was attempting to assign the process pk to a foreign key field. It seems like the issue has been resolved , however i am recieving another message error as seen below No transition from ASSIGNED It seems like the error may be coming from my flows.py : class Pipeline(Flow): process_class = PaymentVoucherProcess start = ( flow.Start( CreateProcessView, fields=["payment_code","bPBankAccount"] ).Permission( auto_create=True ).Next(this.approve) ) approve = ( flow.View( Signature, fields=["eSignatureModel"] ).Permission( auto_create=True ).Next(this.check_approve) ) check_approve = ( flow.If(lambda activation: activation.process.eSignatureModel) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request ).Next(this.end) ) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.payment_code) or my views.py: @flow_view def Signature(request): form = SignatureForm(request.POST or None) if form.is_valid(): esig = form.save(commit=False) signature = form.cleaned_data.get('signature') if signature: signature_picture = draw_signature(signature) signature_file_path = draw_signature(signature, as_file=True) esig.paymentVoucherProcess = request.activation.process esig.save() request.activation.done() return redirect(get_next_task_url(request, request.activate_next.process)) return render(request, 'cash/pipeline/jsig.html', { 'form': form, 'activation': request.activation }) Google doesn't give me much information on how to debug this , maybe someone with experience can assist me? I would greatly appreciate it! -
Python await outside async function
I'm trying to send data to my client from a Django channels consumer. I tried the following code: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) await self.send_json(Rate) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() The problem with my actual code is that i'm getting the following error: SyntaxError: 'await' outside async function I think this happens because i'm using await inside a synchronous function, which is process_message(). I doon't know how to send the variable Rate in any other way. Is there a workaround? Can someone help me fix this issue? -
Django query extended user model for authentication
I have an issue with authentication in django with an extended user model. I want the user to authenticate with a customer number, a username and a password. This are my models: class Mandant(models.Model): Mandant_id = models.AutoField('ID', primary_key= True) Mandant_accn= models.CharField('Kundennummer', max_length=10) Mandant_name = models.CharField('Bezeichnung', max_length=200) Mandant_street = models.CharField('Straße', max_length=200, null=True, blank=True) Mandant_zip = models.CharField('PLZ', max_length=10, null=True, blank=True) Mandant_city = models.CharField('Ort', max_length=200, null=True, blank=True) Mandant_iban = models.CharField('IBAN', max_length=200, null=True, blank=True) Mandant_bic = models.CharField('BIC', max_length=200, null=True, blank=True) Mandant_ustid = models.CharField('UstID', max_length=200, null=True, blank=True) Mandant_vf = models.DateTimeField('Gültig von', default=now) Mandant_vu = models.DateTimeField('Gültig bis', null=True, blank=True) Mandant_ia = models.DateTimeField('Hinzugefügt am', auto_now=True) Mandant_deleted = models.BooleanField('Gelöscht', default=False) def __str__(self): return self.Mandant_name class Meta: app_label ="meas" ordering = ['Mandant_ia'] class Meas_User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mandant_id = models.ForeignKey(Mandant, on_delete=models.CASCADE) I extended the django default user model with an onetoonefield in my Meas_User model. Now I tried to write a login view for my app users. But I dont get how to do a query like the in the following SQL statement SELECT User, Mandant FROM [User] INNER JOIN (Mandant INNER JOIN MEAS_user ON Mandant.Mandant_ID = MEAS_user.Mandant_ID) ON User.ID = MEAS_user.user_ID WHERE (((User.username)="lorem Ipsum") AND ((Mandant.Customer_Number)="1234")); I tried the select_related() function, but without success. My desired result … -
I want a single table-row containing big content to break into pages
I have created a table with rows which displays data fetched from a table. Problem is that when data in table row is large, while printing row gets shifted in next page leaving a big blank space in previous page like this. Blank space on first page and row shifted to next page code i have written in html file is : ''' <table class="table table-light"> <thead> <tr> <th scope="col"></th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {% for que in q_changed_a_lst %} <tr> <td><b><dl></dl><b></td> <td>{{que.question_set}}</div></td> <td>{{que.marks_set}} </td> </tr> {% endif %} {% endfor %} </tbody> </table> ''' and css : <style type="text/css"> table { page-break-inside:auto; } tr { page-break-inside:avoid; page-break-after:auto; } tr td { page-break-inside:avoid;} </style> ul tag works but here I have three columns so I cannot use ul or div tags Please help me so that the row should print part content in previous page and remaining content in next page. Thanks in advance. -
How to keep form input with the same function in 2 different pages
Guys i am new to django and want to learn how to keep the same entry field in 2 different pages. In forms.py: class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = Student fields = ['name',] In main.html i have : <form method="POST" > {% csrf_token %} {{ form}} <button class = "btn btn-primary" type="submit">OK</button> </form> In views.py def studinfo(request): form = StudentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) name = form1.name background=Student.objects.get(stud_name=name) context={'profile':background ,} return render(request, 'main/stud_info.html', context) return render(request, 'main/main.html', context={'form':form}) after submitting the form it is directed to stud_info.html where the results are shown based on the input value from the form on main.html. My question is how i can keep the form input in stud_info.html page with the same function as in main.html so that i do not have to return to main.html page to look for a new value? So far i tried simply copying the main.html form into stud_info.html how it only displays OK butoon and nothing. I would appreciate any help and guidance in finding the solution. Thanks in advance. -
How to have a progress bar with uploading a file in Django 3.0.4
This can easily be done with Ajax and Jquery, but this version of Django seems to be making it extra difficult. It requires the '{% csrf_token %}' and that automatically submits the file when submit is pressed. <form id="data_upload" action="/upload" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="input-group mb-3"> <div class="custom-file"> <input id="file_select" type="file" class="custom-file-input" id="inputGroupFile02" accept=".csv, .xslx" name="file" /> <label id="submit_label" class="custom-file-label" for="inputGroupFile02" aria-describedby="inputGroupFileAddon02" >Upload CSV or Excel file</label > </div> <div class="input-group-append"> <button id="upload_button" type="submit" class="input-group-text btn" id="inputGroupFileAddon02" disabled > Upload </button> </div> </div> </form> Here is my forum code, very standard. I'm wondering how I can have a progress bar in the front-end. I tried adding ajax to send the file so I could have a progress bar, but it sends an error and it ends up sending the file twice. Once by Django and once by Ajax. -
Can't Insert value in Django foreign key field
I have tried to insert Value in Foreign key fields in django. But It show's me error like this:- Cannot assign "'95'": "Catalog.author_id" must be a "Author" instance. But when I tried to insert with django shell It doesn't show me any error, It's Works fine. Please Help Me I have attached my codes that You can understand well Models.py class Author(models.Model): author_id = models.CharField(max_length=50, primary_key=True) name = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) def __str__(self): return str(self.author_id) class Catalog(models.Model): book_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=100) year_of_publish = models.CharField(max_length=5) price = models.IntegerField() author_id = models.ForeignKey('Author', on_delete=models.CASCADE, null=True) def __str__(self): return str(self.book_id) Forms.py class Catalog_Details(forms.ModelForm): book_id = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Enter book id'} ), required=True, max_length=50) title = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Enter title'} ), required=True, max_length=50) year_of_publish = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Enter Published Year'} ), required=True, max_length=5) author_id = forms.ModelChoiceField(queryset=Author.objects.values_list( 'author_id', flat=True)) views.py @login_required def catalog(request): if request.user.is_authenticated: if request.method == 'POST': form = Catalog_Details(request.POST) if form.is_valid(): author_id = form.cleaned_data['author_id'] m = Author.objects.get(author_id=author_id) c1 = Catalog(book_id=form.cleaned_data['book_id'], title=form.cleaned_data['title'], year_of_publish=form.cleaned_data['year_of_publish'],price=form.cleaned_data['price'], author_id=m) c1.save() form = Catalog_Details() else: form = Catalog_Details() return render(request, 'catalog.html', {'form': form}) -
ImageField not accepting vale from html file in DJANGO
I am making a custom CMS platform in Django. I want to upload a featured image from user. Here is my forms.py class CkEditorForm(ModelForm): .......... .......... featuredImage = forms.ImageField(required=True) My models.py class Post(models.Model): .......... .......... featuredImage = models.ImageField(upload_to="featured_image/") My HTML Template <div class="col-sm-6"> {{myForm.featuredImage}} </div> I used one more method in template but it didn't work for me- <input type="file" name="featuredImage" accept="image/*" required id="id_featuredImage"> Note- Image is successfully uploaded via Django admin panel, But not working when I try to upload via Templates (HTML file) Also, it was working when I use this method to render my form in html {{myForms.as_p}} But I want to render each form's input method as differently. {{myForm.category}} {{myForm.tags}} {{myForm.featuredImage}} -
Adding recently searched in Search box for a django website
I'm creating a website using django. And I want to put a search box in my website. So now if an anonymous user comes to my website and search for something and use some data and after sometime leaves the website without signing up.And comes back later and again start searching for the same thing what he was searching earlier then i want my website to show that search as "recently searched" or something like that, for that what should i do?? -
From Python function to Django template
I'm trying to get my head around Django and understand how I can show results of Python functions in Django's templates. As a simple example, let's say I have a model with a list of questions and I want to use a function to return the number of questions and for this result to be shown in a template. How can I do it? I tried to do it below but it doesn't work! Thanks in advance models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) views.py from django.shortcuts import render from django_app import models from django.views.generic import ListView from django_app.models import Question class TestListView(ListView): model = Question context_object_name = 'test_details' def Test(self): return Question.objects.count() urls.py from django.urls import path from django_app import views from django_app.views import TestListView app_name = 'django_app' urlpatterns = [ path('',TestListView.as_view(), name='Test'), ] question_list.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% for item in test_details %} {{Test}} {{item.question_text}} {% endfor %} </body> </html> -
What is the meaning of this function in django
def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) In a django project i used this function but i do not know why i used this -
How to assign process PK to a foreign key field in viewflow
Hello im trying to build an esignature workflow using viewflow. Im doing so by linking my process model , to an esignature model where i keep the signatures by a foreign key. However , im facing this error. Cannot assign "8": "ESignatureModel.paymentVoucherProcess" must be a "PaymentVoucherProcess" instance. My flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess start = ( flow.Start( CreateProcessView, fields=["payment_code","bPBankAccount"] ).Permission( auto_create=True ).Next(this.approve) ) approve = ( flow.View( Signature, fields=["eSignatureModel"] ).Permission( auto_create=True ).Next(this.check_approve) ) check_approve = ( flow.If(lambda activation: activation.process.eSignatureModel) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request ).Next(this.end) ) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.payment_code) Here is my models.py class PaymentVoucherProcess(Process): payment_code = models.CharField(max_length=250,default='sup') bPBankAccount = models.ForeignKey('BPBankAccount', on_delete=models.CASCADE) drop_status = models.CharField( null=True, max_length=3, default=None, choices=(('SCF', 'Successful'), ('ERR', 'Unsuccessful')) ) remarks = models.TextField(null=True) class ESignatureModel(JSignatureFieldsMixin): name = models.ForeignKey(User , on_delete=models.CASCADE) paymentVoucherProcess = models.ForeignKey('PaymentVoucherProcess', on_delete=models.CASCADE) Here is my external custom view i used to insert the esignature aspect into my workflow @flow_view def Signature(request): form = SignatureForm(request.POST or None) if form.is_valid(): esig = ESignatureModel() signature = form.cleaned_data.get('signature') if signature: signature_picture = draw_signature(signature) signature_file_path = draw_signature(signature, as_file=True) pk = request.activation.process.pk #attempting to assign the foreign key field error occurs here esig.paymentVoucherProcess = pk form.save() request.activation.done() return redirect(get_next_task_url(request, request.activation.process)) return render(request, 'cash/pipeline/jsig.html', … -
How to save serial number generated after form submission and displayed in django database?
I have created the model as class Personal_Detail(models.Model): message=models.CharField(max_length=100,blank=True, null=True) def __str__(self): return self.beneficiary_aadhaar_name and views as from django.contrib import messages import datetime import random @login_required def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name') apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name) apply_online.save() return render(request,'users/applyonline.html') I don't know how can i do the same for messages so that the displayed serial number after form submission will also get saved in the database.(for messages.success i don't know how to proceed like other cases) -
Apply default_value in Django Model to databases
I have a Django app connected to a MS SQL database. When I create a model, there are fields that will be auto-created or fields that have default value, like the ones below. class PrincipalFlash(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated_by = models.CharField(max_length=100, default='sys_admin') However, when I take a look at how the table is created in the database, it looks like below. CREATE TABLE [webapp].[api_principalflash]( [id] [int] IDENTITY(1,1) NOT NULL, [created_at] [datetime2](7) NOT NULL, [updated_at] [datetime2](7) NOT NULL, [updated_by] [nvarchar](100) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] It's only saying that these field are just NOT NULL without any default value. Hence, when I write data to this table directly (not via Django Rest API), it asks me the values for these fields. Do you guys know how to apply default_value from Django model to the database level? Thanks! -
Using a wiki with django
I have created a basic django site. It's currently in the testing phase. I need to add a wiki to this site, such that clicking a button on the main django site directs me to this wiki. I need the wiki to look similar to wikipedia. Now, wikipedia uses MediaWiki, based on PHP. My site is based on django. I tried installing and running media wiki on my localhost, but got a ton of errors. Maybe this is because I'm on Windows. Is there any other wiki I can use, which is perhaps more django-friendly? I know about 'django-wiki', but it hardly looks like a wiki. I know that this question appears to be too broad, but I just need suggestions and perhaps a starting point. I am on python 3.8.2 and django 3.0.3. -
Best way to code and to connect two models in python
I have created a "quote" app and in my next phase I would like to create a dropdown list with my "contacts". I'm only wondering what is the easiest, and best practices to create another class with the details of the contacts, or creating a new "app" to hold all the details of the contacts. -
Django Rest Framework Admin Site doesn't Load
Whenever I try to run python manage.py runserver and go to the admin site, I lose connection to the server immediately. The API Root page works fine it is just the admin page. The code is based on the Django Rest Framework Quickstart tutorial with the addition of a model, it's serializer and the respective view. All migrations have been made. (venv) ~\Back-End\iBMS>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 04, 2020 - 02:11:20 Django version 3.0.5, using settings 'iBMS.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (venv) ~\Back-End\iBMS> Here are my code files: #urls.py """iBMS URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from rest_framework import routers … -
Django rest framework Post request
I am creating django + react app and i want to pass data by django rest framework. models.py class User(AbstractUser): def __str__(self): return self.username class Address(models.Model): username = models.ForeignKey(User,related_name='address',on_delete=models.CASCADE) street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Addresses' def __str__(self): return '%s %s %s %s' % (self.street_address, self.apartment_address, self.country, self.address_type) serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('street_address','apartment_address','country') class UserSerializer(serializers.ModelSerializer): address = serializers.StringRelatedField(many=True) class Meta: model= User fields = ('email','username','password','address')``` views.py class UserViewSet(viewsets.ModelViewSet): serializer_class=UserSerializer queryset = User.objects.all() class AddressViewSet(APIView): def get(self, request, format=None): address = Address.objects.all() serializer = AddressSerializer(address, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AddressSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @classmethod def get_extra_actions(cls): return [] My get request looks good because it returns value but it looks like something wrong is with AddressSerializer(data=request.data)