Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass variables between functions Django?
I have a function like this in views.py: def signin(request): if request.method == 'POST': uname = request.POST['username'] pwd = request.POST['password'] #and other code And then i have another function like this: def reservations(request): try: c = Utilisateur.objects.get(username = uname) reserve = Reserve.objects.get(client = c) return render (request, 'reservation.html', {'reserve':reserve}) except: return HttpResponse ('you have no reservations!') And i want to use the "uname" variable of the first function but it doesn't work any solution? -
what does models.Models.None mean in django templates?
I have three models. A User model, which is just the basic django User model, so I won't add the code for it. An Account model (which is a CustomUser model/extension of the basic django User): class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group) And, finally, I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField() topic = models.CharField(max_length=55) joined = models.ManyToManyField(User, related_name='joined_group') def __str__(self): return self.topic Now I'm trying to render my User information as well as the Account information in my django templates. Inuser_details.html I have the following account info written out: <div>Username: {{user.username}}</div> <div>Groups Joined: {{user.account.joined_groups}}</div> However, what's rendering is Groups Joined: groups.Group.None I don't really know what this means or why it's happening, and I also don't know how to render the Groups my User has joined. Any help would help. Thanks. -
ValueError --The view dashboard.views.saveBlogTopic didn't return an HttpResponse object. It returned None instead
I got this error when i tried to test my function inside views.py: Traceback (most recent call last): File "/home//lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home//lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response self.check_response(response, callback) File "/home/**/lib/python3.8/site-packages/django/core/handlers/base.py", line 332, in check_response raise ValueError( ValueError: The view dashboard.views.saveBlogTopic didn't return an HttpResponse object. It returned None instead. I tried several ways to solve the problem but i couldn't .Can you help me here here are my files: views.py : @login_required def blogTopic(request): context = {} if request.method == 'POST': blogIdea = request.POST['blogIdea'] request.session['blogIdea'] = blogIdea keywords = request.POST['keywrods'] request.session['keywrods'] = keywords audience = request.POST['audience'] request.session['audience'] = audience blogTopics = generateBlogTopicIdeas(blogIdea, audience, keywords) if len(blogTopics) > 0: request.session['blogTopics'] = blogTopics return redirect('blog-sections') else: messages.error(request,"Oops we could not generate any blog ideas for you, please try again.") return redirect('blog-topic') return render(request, 'dashboard/blog-topic.html', context) @login_required def blogSections(request): if 'blogTopics' in request.session: pass else : messages.error(request,"Start by creating blog topic ideas") return redirect('blog-topic') context = {} context['blogTopics'] = request.session['blogTopics'] return render(request, 'dashboard/blog-sections.html', context) @login_required def saveBlogTopic(request, blogTopic): if 'blogIdea' in request.session and 'keywords' in request.session and 'audience' in request.session and 'blogTopics' in request.session: blog = Blog.objects.create( title = blogTopic, blogIdea = request.session['blogIdea'], keywrods = request.session['keywrods'], … -
Django REST Framework router seems to be overriding my explicitly defined path in URLpatterns
new to coding so I'm sure this is a simple problem but I can't seem to figure it out. I've abbreviated the code so it's simpler to see the problem. urls.py router = routers.DefaultRouter() router.register(r'clients', views.ClientViewSet, basename='client') urlpatterns = [ #Bunch of other paths here. path('client/<int:pk>/contacts', login_required(views.contacts_by_client), name="client-contacts"), path('api/', include(router.urls)), ] views.py def contacts_by_client(request, pk): client = Client.objects.get(id=pk) contact_list = Contact.objects.filter(user=request.user, client=pk) context = { 'contacts': contact_list, 'client': client } return render(request, 'pages/contacts-client.html', context) class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=True, methods=['get'], name="Contacts") def contacts(self, request, pk=None): # Bunch of code here. My suspicion is that the router is creating a route name called "client-contacts" based on the action created in views.py, however, I don't understand why it would take precedence over the explicitly labeled url pattern that comes before it. I know I must be missing something super simple, but I can't figure it out. Thank you all for your help! -
Update data in db django after reload page with discord auth
I make authorize with my discord, when user auth I save data to my database but when user changes his nickname in discord, I dont get new version of nickname in database, how to fix this? -
Django: how to create slugs in django?
i want to create a slug in django, i have used the slug = models.SlugField(unique=True). Now when i create a post with a slug of learning-to-code it works, but if i create another post with the same slug learning-to-code, it shows an error like Unique Constraint Failed. But i want to create posts with the same slug, is there a way to make slugs unique only to the time a post was created? this is how my model looks class Article(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) slug = models.SlugField(unique=True) user = models.ForeignKey('userauths.User', on_delete=models.SET_NULL, null=True) How can i go about achieving this? -
How can I add required attribute?
I would like to add the required attribute in the product_title field. How can I do It? class add_product_info(forms.ModelForm): product_desc = RichTextField() class Meta: model = Products fields = ('product_title') labels = {'product_title':'Title'} widgets = { 'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}) } -
Struggling with aggregate and subtraction in Django and PostgreSQL
So I am having an issue with querys (getting the sum of an item(aggregate) and subtracting. What I am trying to do is 10 (soldfor) - 2 (paid) - 2 (shipcost) = 6 The issue is, if I add another (soldfor) (paid) or (shipcost) = it will add all of them up so the profit becomes double. Another example, If I have an item with the (paid) listed at 3.56 and another item with the same (paid) int, it subtracts the two from each new row. I have tried two queries and I cannot get them to work. What I get: 10 (soldfor) - 2 (paid) - 2 (shipcost) = 12, because two fields have the same exact input. So basically, if the two fields have the same number it adds or subtracts them to every row that have the same field with the same number. models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def … -
Query Django data base to find a column with a specific value and update that column value
I have tried very hard to understand how to update my data base, but struggling to even print out the value of the data returned. My code in views.py: #SET THE PLACEHOLDER DATE AND TIME AS A STRING AND CONVERT TO DATETIME #QUERY THE DATA BASE TO FIND THE ROW WHERE END_END_TIME = PLACEHOLDER DATE AND TIME #OUTPUT THE DATA TO THE TERMINAL #UPDATE THE END_DATE_TIME TO CURRENT DATE AND TIME date_time_placeholder = "2023-01-01 12:00:00" datetime.strptime(date_time_placeholder, "%Y-%m-%d %H:%M:%S").date() get_value = logTimes.objects.get(end_date_time = date_time_placeholder) print(get_value) The output: logTimes object (155) I can see in the admin site the code is working, it is finding the correct row, but I am not sure how to print the column data to the terminal instead of the just the object and ID. What I am trying to achieve ultimately is to update the end_date_time in this row to the current date and time using datetime.now(), I am not having any success, not for the lack of trying for hours. Any help is appreciated. -
Django Python LoadData: Error Problem Installing Fixture
First i have migrate and makemigrations and then I have dump data with this command : python manage.py dumpdata --exclude auth.permission --exclude contenttypes > dvvv.json and i have tried to flush database and when i put python manage.py loaddata dvvv.json it says this: pymysql.err.ProgrammingError: (1146, "Table 'webcnytc_prilert_tool.Prilert_confirmationemail' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 123, in loaddata self.load_label(fixture_label) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 190, in load_label obj.save(using=self.using) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 778, in save_base force_update, using, update_fields, File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 859, in _save_table forced_update) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 912, in _do_update return filtered._update(values) > 0 File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/query.py", line 802, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1559, in execute_sql cursor = super().execute_sql(result_type) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute return … -
DRF Add annotated field to nested serializer
I have two serializers that represent comments and their nested comments. I'm provide a queryset to viewset with annotated field likes. But my problem is that field only working in parent serializer. When i add this field to nested serializer i got error Got AttributeError when attempting to get a value for field likes on serializer CommentChildrenSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Comment instance. Original exception text was: 'Comment' object has no attribute 'likes'. Here is some my code. Thanks Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) Serializers.py class PostRetrieveSerializer(PostSerializer): comments = CommentSerializer(read_only=True, many=True) author = AuthorInfoSerializer(serializers.ModelSerializer) class Meta: model = Post fields = ['id', 'author', 'slug', 'title', 'body', 'tags', 'pub_date', 'comments'] class CommentChildrenSerializer(serializers.ModelSerializer): author = AuthorInfoSerializer(read_only=True) likes = serializers.IntegerField() class Meta: model = Comment fields … -
Saas cannot find stylesheet to import. Django project
I am trying to use bootstrap saas in my django project. I installed saas and bootstrap via npm sucessfully however when I try to compile my sass/scass to css I get an error below. I think i am somehow getting file directories incorrect project structure Error -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id
I am preparing an ecommerce project in Django. Now I'm trying to change some things When I run the python manage.py makemigrations and python manage.py migrate commands, I get an error that I can't understand. error django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id models.py class Brand(models.Model): name = models.CharField(max_length=10) image = models.ImageField(upload_to='brand') slug = models.SlugField(max_length=15, unique=True) date = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) main_image = models.ImageField(upload_to='product_images/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=1000) price = models.FloatField() #brand = models.CharField(max_length=50, default='Markon', verbose_name='Brand (Default: Markon)') brand = models.ForeignKey(Brand, on_delete=models.DO_NOTHING, default='Markon') sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)") bestseller = models.BooleanField(default=False) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) stock = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) used = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) -
What authentication actually does? [closed]
Let's say I'm building a web application and I can choose between 2 different ways of authenticating users. Outcome is same(same record in database, same user experience), but when I look how both ways are written I can see plenty of differences. I would want to know what could be differences between the 2 ways and should I choose more or less complicated. -
Is there a way to save a Django object and update other objects without a recursion loop?
I have a Django model: class Event(models.Model): fk = models.ForeignKey(Foreign, null=True, on_delete=models.SET_NULL) display = display = models.BooleanField(default=True) ... I'd like to override the save method to turn off display for other events that share the fk value. However, I keep reaching infinite recursion loops because if I override the save method and then save the other objects, it keeps calling the function. Is there a way to only run the save method on the first object that's saved and not keep creating recursive instances? -
Validator errors
I'm running my code through validator and it's coming back with four errors which I don't know how to fix as the code has been imported from django forms. Does anyone know how to fix these? <div class="form-group"> <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="0AxrgENq77DUAfiu7a1XIsQ2gveB9bBBO96oqSIrlW5OQxoV8EMCrmIIbAn31wa4"> <p><label for="id_username">Username:</label> <input type="text" name="username" maxlength="150" autofocus class="form-control" required id="id_username"> <span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></p> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" class="form-control" maxlength="100" required id="id_first_name"></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" class="form-control" maxlength="100" required id="id_last_name"></p> <p><label for="id_email">Email:</label> <input type="email" name="email" required id="id_email"></p> <p><label for="id_password1">Password:</label> <input type="password" name="password1" autocomplete="new-password" class="form-control" required id="id_password1"> <span class="helptext"> <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password.</li> <li>Your password can’t be entirely numeric.</li> </ul> </span></p> <p><label for="id_password2">Password confirmation:</label> <input type="password" name="password2" autocomplete="new-password" class="form-control" required id="id_password2"> <span class="helptext">Enter the same password as before, for verification.</span></p> <div class="d-grid"> <button class="btn btn-dark ">Register</button> </div> </form> </div> -
Is my DRF create function losing data before saving?
I have the following DRF viewset: class RecordViewSet(ModelViewSet): queryset = Record.objects.all() serializer_class = RecordSerializer filterset_fields = ['task', 'workday'] def get_workday(self, request): date = get_date_from_calendar_string(request.data['date']) obj, _ = Workday.objects.get_or_create(user=request.user, date=date) return obj.id def create(self, request): request.data['workday'] = self.get_workday(request) print(request.data) return super().create(request) The create() method is failing on a not-null constraint: django.db.utils.IntegrityError: null value in column "task_id" violates not-null constraint DETAIL: Failing row contains (159, Added via task panel., 0, 0, 0, null, t, f, null, 98). However, the print statement in create() shows that the data present in the submission: {'minutes_planned': 5, 'description': 'Added via task panel.', 'minutes_worked': 5, 'task': 148, 'workday': 98} I am not seeing the pk for task (148) in the error statement for some reason, indicating to me that it is getting dropped somewhere. I am not using any signals, or overriding save() in the model. What else could be causing this problem? I've just started using DRF, so it might be something obvious. ===== This is the model: class Record(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='records') workday = models.ForeignKey(Workday, on_delete=models.CASCADE, related_name='records') description = models.CharField(max_length=128, blank=True, null=True) minutes_planned = models.IntegerField(default=0) minutes_worked = models.IntegerField(default=0) minutes_worked_store = models.IntegerField(default=0) user_generated = models.BooleanField(default=True) completed = models.BooleanField(default=False) and the serializer: class RecordSerializer(serializers.ModelSerializer): task … -
error django.db.utils.IntegrityError: NOT NULL constraint failed
I am really stuck here. I went back and edited some models that I made a while ago and now I can't get anything to migrate without getting "django.db.utils.IntegrityError: NOT NULL constraint failed: new__accounts_instrument.room_id" The model that seems to be causing problems: ...\acounts\models.py class Instrument(models.Model): LEVEL = ( ('HS', 'HS'), ('MS', 'MS'), ) event = models.ForeignKey(Event, blank=False, null=True, on_delete=models.PROTECT) name = models.CharField(max_length=200, blank=False, null=True) abbreviation = models.CharField(max_length=10, blank=False, null=True) level = models.CharField(max_length=200, blank=False, null=True, choices=LEVEL) room = models.ForeignKey(AuditionRoom, default=None, on_delete=models.PROTECT) I've tried deleting the migration history but that throws other codes so I "undo" it. I've tried dropping the instrument table but that didn't seem to matter. I'm very grateful for any pointers as I am pretty frustrated at the moment. Please let me know if you need more code snippets... THANK YOU -
Reference a django variable in html to perform a function
I am trying to to output a function on the string that a user selects in a dropdown form. I have a custom template tag that works when you feed it the right variable, but am not sure how to pass on the selected item to it. <select> {% for drink in drinks %} <option id="dropdown" value="{{drink.drink_name}}">{{drink.drink_name}}</option> {% endfor %} </select> <li>{{drink.drink_name|drink_joins}}</li> I know the list gives me an error because drink.drinkname is out of the loop but this is the logic I'm going for. Also fetching the selected value with JavaScript (document.getElementById("dropdown").value) only gives me the first item from the dropdown so that is a problem too. Any remedies? -
Django container is rejecting nginx containers traffic
I have a pretty simple setup, a single django container in a pod and an nginx container in another pod. I'm using nginx because I want to move the django app into production and I need an actual web server like nginx to put an ssl cert on the site. The problem is that it seems like django is rejecting all of the traffic from the nginx container as the web browser gets 502 bad gateway error when browsing to localhost and the nginx logs show: *3 recv() failed (104: Connection reset by peer) while reading response header from upstream I already have 127.0.0.1 and localhost added to the allowed hosts in django settings. Below is the kubernetes file with the nginx config that I'm loading through a config map. I've tried about 30 different nginx.conf configurations, this is just the most recent and simplest one. apiVersion: v1 kind: Service metadata: name: my-nginx-svc labels: app: nginx spec: type: LoadBalancer ports: - port: 80 selector: app: nginx --- apiVersion: apps/v1 kind: Deployment metadata: name: my-nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 … -
How to get difference between two annotate fields in django orm
The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct. In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account queryset = PersonalAccount.objects.select_related( 'apartment', 'apartment__house', 'apartment__section', 'apartment__owner', ).annotate( balance= Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0)) - Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0)) ).order_by('-id') class PersonalAccount(models.Model): objects = None class AccountStatus(models.TextChoices): ACTIVE = 'active', _("Активен") INACTIVE = 'inactive', _("Неактивен") number = models.CharField(max_length=11, unique=True) status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE) apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL, related_name='account_apartment') class CashBox(models.Model): objects = None number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) status = models.BooleanField(default=True) type = models.BooleanField(default=True) sum = models.DecimalField(max_digits=10, decimal_places=2) comment = models.TextField(blank=True) payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL) owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner') manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager') personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True, on_delete=models.SET_NULL, related_name='cash_account') receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL) class Receipt(models.Model): objects = None class PayStatus(models.TextChoices): PAID = 'paid', _("Оплачена") PARTIALLY_PAID = 'partially_paid', _("Частично оплачена") NOT_PAID = 'not_paid', _("Не оплачена") number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) date_start = models.DateField(default=datetime.date.today) date_end = models.DateField(default=datetime.date.today) … -
Posting Date Data to Django Model
I was wondering if any of you guys here knew how to fix this error, I have been dealing with it for quite a few hours, it has to do with posting json date (a date from a html date picker) to a backend model using the django web framework. Please let me know if my question is unclear. ViewOrders.html <form id="form"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" name="drop_Off_Date" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date" >Submit Drop Off Date</button> </form> <script type="text/javascript"> var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop Off Date submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropOffDateInformation.dropOffDate = form.drop_Off_Date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'drop-off-date':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> Views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['drop-off-date']['dropOffDate'], ) return JsonResponse('Drop off date submitted...', safe=False) Models.py class DropOffDate(models.Model): dropOffDate = models.CharField(max_length=150, null=True) def __str__(self): return str(self.dropOffDate) Errors -
A good way to authenticate a javascript frontend in django-rest-framework
What's an excellent method to implement token-based httpOnly cookie authentication for my drf API for a javascript frontend I looked into django-rest-knox for token-based authentication but its built-in LoginView required the user to be logged in already. Why is that?. I want a good method to authenticate the user from the javascript frontend. Thanks! -
How to migrate from sqlite to postgres using a local sqlite database in Django?
I have a 'xxxxx.db' sqlite3 database and I want to move the data to PostgreSQL. I have done some research and seen a couple of options but none of them worked (PGloader etc.). What are some other options? I am using Windows but solutions in Linux are welcome as well. I have tried doing it in PowerShell(via Jupyter Notebook): !pip install virtualenvwrapper-win !mkvirtualenv [name] !pip install django !django-admin startproject [name] cd [name] !python manage.py startapp app !python manage.py inspectdb !python manage.py inspectdb > models.py !python manage.py migrate !manage.py runserver !python manage.py dumpdata > data.json But the dump does not include the data from my db, I have also changed the settings to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': absolute_path_to_db/db, } } Thanks in advance! -
How to make a drf endpoint that returns model fields with description and choices?
There are rest api endpoints being built for questionnaires, that accept only POST requests. The frontend should dynamically display the questionnaires based on their model fields, their descriptions, and possible choices. How to make such django rest framework endpoint, which returns model fields, their description and choices as json? It cannot be a hard coded json so when a model field description changes, it is reflected in the API response.