Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to download files using flask from my folder. How to download
@app.route("/download?/path:filename",methods = ['GET', 'POST']) def download(filename): return send_from_directory(filepath, filename =filename, as_attachment = True) This is the function Click on the File to Download : {{post.py_file}} This is the html tag -
Django KeyError at /
Hello Guys Im trying to make a Login page and I want it to be validated, I'm having hard time fixing it. I don't know what's going on. The problem is whenever I try to login with invalid user or not registered user I want it to throw me and error message. So I did this Now it throwing me a Error of django. KeyError at / 'username' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: KeyError Exception Value: 'username' Exception Location: /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/users/forms.py, line 32, in clean_password Python Executable: /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/bin/python3 Python Version: 3.9.5 Python Path: ['/home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/aakash/Documents/Projects/Imp ' 'Projects/Atom-Social-Media/lib/python3.9/site-packages'] Server time: Tue, 01 Jun 2021 07:08:02 +0000 Traceback Switch to copy-and-paste view /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/lib/python3.9/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/users/views.py, line 11, in register_view if form.is_valid(): Forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.forms import fields from django.forms.widgets import PasswordInput from django.contrib.auth.hashers import check_password User = get_user_model() unallowed_username = ['fuck', 'fuck123', 'bitch', 'yourdad', 'yourmom','suck'] class LoginForm(forms.Form): username= forms.CharField() password = forms.CharField( widget=PasswordInput( … -
django.db.utils.OperationalError: no such table: poll_position
Here It is showing an error while mapping the position table with the candidate if I use ForeignKey relationship then it is also showing an error can anybody tell what is the problem. models.py from django.db import models from django.contrib.auth.models import User class Position(models.Model): title = models.CharField(max_length=50, unique=True) def __str__(self): return self.title class candidate(models.Model): full_name = models.CharField(max_length=50) total_vote = models.IntegerField(default=0, editable=False) position = models.ForeignKey(Position, on_delete=models.CASCADE) def __str__(self): return "{} - {}".format(self.full_name, self.position.title) class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) def __str__(self): return self.fname error: OperationalError at /admin/poll/candidate/ no such table: poll_position Request Method: GET Request URL: http://127.0.0.1:8000/admin/poll/candidate/ Django Version: 3.2.3 Exception Type: OperationalError Exception Value: no such table: poll_position Exception Location: C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Anil\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Anil\\PycharmProjects\\E_Vote\\ovs', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 01 Jun 2021 07:10:50 +0000 -
How to enable all lookups for all fields in django-filters library
in django filters you need somtigs like filterset_fields = {'object_id': ['gte', 'lte', 'exact', 'lt']} to enable filtering but what if I want to enable all lookups filtering on all fields. pagination_class = PageNumberPagination filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] search_fields = '__all__' filterset_fields = {'object_id': ['gte', 'lte', 'exact', 'lt']} I tried filterset_fields = 'all' but I got only the 'exact' functionalities. also I have a problem in which when I do url/?id=2 I got the same data, so why __all__ doesn't work on the id? -
Django Teamplate Tabs Not Showing
I have a Django website which you can think of as a blog. In there, I have a route where you can create a new post. There is also a list page and a detail page, where you can see all the posts published, and see the contents of the post respectively. When creating a new post, I have not added CKEditor or any other WYSIWYG editor. But if I have any tabs in the post, it doesn't render. For example, if I write some code in VSCode and paste it in the TextField, even though the tabs render in the TextField, the tabs don't appear in the detail page. For example, if I write this in the TextField: foo = "bar" if foo == "bar": print("baz") This, in the detail page looks like this: foo = "bar" if foo == "bar": print("baz") This is the part of my detail page that renders the above on the screen: <div class="contents"> {{ object.contents | linebreaks }} </div> Could you help? -
How to add extra key-value to QuerySet lists?
I am working with Django,i need to retrieve data from multiple database, which has different database name but with same table column structure. So I use model.using(database).all()to get queryset and merge them into one. I want to add extra databasename to indicate the data's database name, this is my code. model: class Sections(models.Model): apply_id = models.PositiveIntegerField() pathology_id = models.CharField(max_length=128) user_id = models.PositiveIntegerField() updated_at = models.DateTimeField(blank=True, null=True) get_queryset: def get_queryset(self): slideset = [] database_config = ['database1', 'database2', 'database3'] for i, x in database_config: slides = Sections.objects.using(x).all() #### I want to add extra databasename column in every query object. for x1 in slides: x1.databasename = x ###### slideset.append(slides) # merge QuerySet query = functools.reduce(lambda a, b: a|b, slideset) return query.order_by("updated_at").reverse() the one return will be : { "apply_id": 1123, "pathology_id": 1235, "user_id": 1, "updated_at": "202106011430", # add extra databasename. "databasename": "database1". } Because the column can't be modify, so I had to leave Sections model unchange, just add extra key-value to query, can someone help me on that? -
PermissionError: [Errno 1] Operation not permitted: '/app/staticfiles/admin/css/widgets.css'
Someone can help me? I didnt know why this error happends i give permission to django file app in chown -R appuser /app More detail: i use docker-compose build and docker-compose up my project tree: https://i.ibb.co/WKwWFgw/aaa.png my files: Dockerfile: # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.9-alpine3.13 EXPOSE 8000 ENV PATH="/scripts:${PATH}" # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN apk add --no-cache jpeg-dev zlib-dev RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers && apk add postgresql-dev gcc python3-dev musl-dev \ && pip install Pillow && apk add gcc musl-dev python3-dev libffi-dev openssl-dev cargo # more pip RUN pip install psycopg2 #end more pip RUN pip install --upgrade pip RUN python -m pip install -r requirements.txt RUN apk del .tmp COPY /app /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser # During debugging, … -
how to convert Django uploadedfile.InMemory into numpy array or Image
#Views.py-- I want to convert uploaded image file into numpy array(cv2.imread) .Please help me ``` def upload(request): if request.method == 'POST' and request.FILES['image_file']: f = request.FILES['image_file'] myfile = str(f.read()) array_np = cv2.imread(myfile)``` -
Get all items with all properties using django multi-table inheritance and django rest framework (Cart Product)
I'm using PostgresSQL as DB, Django as backend and HTML, CSS, Javascript as Frontend. I have refer this question link but doesn't help me. Let me explain the whole scenario about my website. 1. I am building website like, if person brought a house then, a person need all household product, then my website will help him to get all the details of the single product like for ex. Fans (speed, RPM, Power consumption etc.), Side Table (Height, wood used, colour etc.) and more than tons of product. 2. Then my first page look like this. 3. Then the user go to the specific page (if click refrigerator link button -> List of Refrigerator(price, brand, specification)) 4. Then the user choose the specific item then he/she will redirect to the main page with selected item. (ref. image down below.) Now, my problem is that I can't access the details of the child table (reference table or link table)[Using Multi table Inheritance] As you can see on the above image I can't access (Refrigerator or other models) Details. Now my code goes here: models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class … -
Run Django/Python Ecommerce website & Php payment gateway on SSL with same domain
I'm newbie to django/python. I've successfully developed ecommerce website using django/python but now i want to deploy it on server using SSL with domain name using nginx so that if server restart i do not have to start the python server every time. Till now I have tried to run PHP payment gateway on 8443 port with subdomain and python on 443 port with main domain. If but nginx not pointing it to the actual python directory or something else and python or payment gateway not working. can anyone please help me to deploy both the things with the mentioned circumstances. Thanks in advance. -
How to export ForeignKeyWidget in django-import-export
I thought it would be possible to export a ForeignKey field.I tried but it isn't working. Where am I going wrong?? And first of all is it even possible??? class ExportAllIssuesResource(resources.ModelResource): book_id__reg_no = fields.Field(attribute='book_id__reg_no',column_name='reg no.') book_id__book_name = fields.Field(attribute='book_id__book_name',column_name='book name') borrower_id__name = fields.Field(attribute='borrower_id__name',column_name='student') borrower_id__student_id = fields.Field(attribute='borrower_id__student_id',column_name='adm') borrower_teacher__code = fields.Field(attribute='borrower_teacher__code',column_name='t_code',widget=ForeignKeyWidget(TeacherIssue,'code')) borrower_teacher__name = fields.Field(attribute='borrower_teacher__name',column_name='t_name',widget=ForeignKeyWidget(TeacherIssue,'name')) def export(self, queryset = None, *args, **kwargs): queryset = Issue.objects.all().filter(borrower_id__school = kwargs['school']) return super().export(queryset,*args, **kwargs) class Meta: model = Issue fields = ('book_id__reg_no','book_id__book_name', 'borrower_id__name','borrower_id__student_id','issue_date','borrower_teacher__code','borrower_teacher__name') export_id_fields = ('book_id__reg_no',) export_order = ('book_id__reg_no','book_id__book_name','borrower_id__name', 'borrower_id__student_id','issue_date','borrower_teacher__code','borrower_teacher__name') The view def ExportAllIssuesView(request): dataset = ExportAllIssuesResource().export(school = request.user.school) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All issues.xls"' return response The models. class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) class TeacherIssue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_teacher = models.ForeignKey(Teachers,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) -
IntegrityError (1048, "Column 'id' cannot be null")
I'm making kinds of the chat room with Django. But I got the following error when I send a text. Maybe I should link message_room_id and form but I can't. What is wrong with my code? models.py class MessageRoom(models.Model): post = models.ForeignKey(Post, verbose_name='MessageRoom Post', on_delete=models.CASCADE) inquiry_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=False, related_name='inquiry_user') def __str__(self): return str(self.id) class Message(models.Model): message = models.CharField(max_length=100) message_room = models.ForeignKey(MessageRoom, verbose_name='Message', on_delete=models.CASCADE) def __str__(self): return str(self.id) Views.py class MessageRoomView(LoginRequiredMixin, DetailView): template_name = 'adopt_animals/pets/message_room.html' model = MessageRoom form_class = MessageForm context_object_name = 'message_room' success_url = reverse_lazy('adopt_animals:message_room') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) message_list = Message.objects.all() context['form'] = MessageForm for message in message_list: return context def post(self, request, **kwargs): message_room = MessageRoom.objects.filter(id=self.kwargs['pk'], inquiry_user_id=self.request.user.id) form = MessageForm(request.POST) if form.is_valid(): # Try to link message_room_id and message.id form.message_room_id = self.kwargs['pk'] form.save() else: print(form.errors) return redirect('adopt_animals:message_room', pk=message_room[0].id) forms.py class MessageForm(forms.ModelForm): message = forms.CharField(label='message', required=True) class Meta: model = Message fields = [ 'message', ] message_room.html <form action="{% url 'adopt_animals:message_room' message_room.id %}" method="POST"> {% csrf_token %} {{ form.errors }} <div class="send-msg"> {{ form.message }} <button class="btn btn-warning" type="submit">Send</button> </div> </form> -
How to generate vertical table?
How can I generate the vertical table in pdf using WeasyPrint? Also, I want to show only 50 records per pdf page. If 50limit exceeds then-new the record should be displed in same pdf but on new page. Can I achieve this using WeasyPrint? Somebody, please help, I'm stuck on this. -
nativation bar in django
I tried to add navigation bar to my djagno site but it gives a error like "Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I use this this answer to make this navigation bar [stack over flow answer][1] Please give me a another option to do this or help to debug this code .anyway here is my base.html full file <!DOCTYPE html> <html> <head> <title>Django Central</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> ... {% block nav %} <ul id="nav"> <li>{% block nav-home %}<a href="{% url 'home' %}">Home</a>{% endblock %}</li> <li>{% block nav-about %}<a href="{% url 'about' %}">About</a>{% endblock %}</li> <li>{% block nav-contact %}<a href="{% url 'contact' %}">Contact</a>{% endblock %}</li> </ul> {% endblock %} ... <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } </style> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}" >Django central</a> <button … -
Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
Why this is showing a warning as it default take the primary key from the User model so should I also declare the primary key the Registration or candidate model again. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) # phone = models.BigIntegerField(max_length=10,primary_key=True) dob=models.DateField() user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) def __str__(self): return self.fname class candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.position) problem occured WARNINGS: poll.candidate: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. -
Get a value from the url to set it as a value of the form?
I'm making a poll app where you have 2 options yes or no (Boolean), I want to save not only a number of votes but also who voted so I decided to make a "pivot" model connecting the User model and the Poll model like this: models.py # Vote choices BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) class PollVotes(models.Model): user = models.ForeignKey(userModels.User, on_delete=models.CASCADE, blank=True) vote = models.BooleanField(choices=BOOL_CHOICES) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) Its easy to set the user value using form.instance.user = self.request.user this way: (views.py) class PollVote(CreateView): model = PollVotes form_class = VoteForm template_name = 'poll_vote.html' success_url = reverse_lazy('polls') def form_valid(self, form): form.instance.user = self.request.user form.instance.poll = ????? return super(PollVote, self).form_valid(form) I'm thinking of getting the poll pk from the URL, but don't know how to do it. Right now the URL gets a int value this way: path('poll/vote/<int:poll>/', PollVote.as_view(), name='poll-vote'), How to relate that int:poll to a PK of some Poll? And then setting the form.instance.poll as a Poll with the PK of the URL? Maybe it's the wrong approach, it's just what I think will be the easiest way. forms.py class VoteForm(forms.ModelForm): class Meta: model = PollVotes fields = ['vote'] widgets = { 'vote': forms.RadioSelect } -
how to handle 2 inlines in one save_formset in django admin
I have model class like class Notification(models.Model): title = models.CharField(max_length=255, default='', blank=True) body = models.CharField(max_length=1024, default='', blank=True) created_at = models.DateTimeField(auto_now_add=True) class NotificationGroup(models.Model): notification = models.ForeignKey(Notification, on_delete=models.CASCADE) group = models.ForeignKey('core.Group', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('notification', 'group') class NotificationUser(models.Model): notification = models.ForeignKey(Notification, on_delete=models.CASCADE) user = models.ForeignKey('core.User', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('notification', 'user') So i want to handle it in django admin like... class NotificationGroupInline(admin.TabularInline): model = nm.NotificationGroup raw_id_fields = ('group',) readonly_fields = ('created_at',) extra = 0 class NotificationUserInline(admin.TabularInline): model = nm.NotificationUser raw_id_fields = ('user',) readonly_fields = ('created_at',) extra = 0 @admin.register(nm.Notification) class Notification(admin.ModelAdmin): list_display = ('id', 'title', 'body') inlines = (NotificationGroupInline,) def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def save_formset(self, request, form, formset, change): super().save_formset(request, form, formset, change) when i add model object about notification i want to handle 2 models in save_formset sametime but i can handle only NotificationGroup model like # formset.cleaned_data [{'notification': <Notification: Notification object (7)>, 'group': <Group: Group1>, 'id': None, 'DELETE': False}] is there any solution handle all models? like this # formset.cleaned_data [{'notification': <Notification: Notification object (7)>, 'group': <Group: 푸시테스트>, 'id': None, 'DELETE': False} {'notification': <Notification: Notification object (7)>, 'user': … -
manage.py stops after exception occurs
def edit_question(request): req = json.loads(request.body) guided_answers=req["guided_answer"] for guided_answer in guided_answers: try: models.Answer.objects.filter(answer_id=guided_answer["answer_id"]).update( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], model_ans=guided_answer["model_ans"], ) except ObjectDoesNotExist or FieldDoesNotExist: models.Answer.objects.get_or_create( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], model_ans=guided_answer["model_ans"], ) return success({"res": True}) what my code above is doing is trying to update the model answer and question marks if it exist and if not it creates a new model answer and question marks the above code works the issue is that after i create a new object the manage.py will abruptly stop, i would like the code to continue even after the exception, i am aware that it should stop however i would like it to continue and no i cannot use update_or_create because it gives me errors which is why i am using this. -
Django admin input text color is white instead of black
since I am new to Django and I am facing this input text color problem in Django admin panel. input text color is white instead of black. how to solve this problem?enter image description here -
Form created dynamically always gets 403 forbidden on a django rest framework api POST
I have multiple text posts on my website. On clicking the edit button I dynamically create a form replacing the div to a form element. I have my POST api set up on the django side to get this form submit and edit the existing post. But my POST request always gets 403. First i assumed not having a csrf token is causing the problem. So i edited my js code to this- //form create const post_content_element = post.querySelector('div .text-content'); const post_content = post_content_element.innerHTML; let edit_form = document.createElement('form'); // Here I added the csrf token as a hidden input let inputElem = document.createElement('input'); inputElem.type = 'hidden'; inputElem.name = 'csrfmiddlewaretoken'; inputElem.value = '{{ csrf_token }}'; edit_form.appendChild(inputElem); edit_form.setAttribute('id', 'edit-form'); edit_form.setAttribute('method', 'POST'); let text_content = document.createElement('input'); text_content.setAttribute('type', 'textarea'); text_content.setAttribute('id', 'edit-content'); text_content.value = post_content; let submit = document.createElement('input'); submit.setAttribute('type', 'submit'); submit.setAttribute('id', 'edit-submit'); edit_form.appendChild(text_content); edit_form.appendChild(submit); still it gets 403 forbidden. My api looks like this- @api_view(['POST']) def edit_post(request): if request.method == "POST": # do something return Response(status=status.HTTP_201_CREATED) Please note I am using my User(AbstractUser) model for authentication. I am out of ideas. What could be the other reasons for this problem? -
I Faced an Error while trying to Logout from Admin Panel in Django
When I am trying to log out from the Django panel I got this error and don't know where this error is coming from, can anyone help me with this error. Error Image -
erro: __str__ returned non-string (type DetComponente) /
Hail Devs. I have had this erro during template rendering. I have tried several resources looking for the error and have not been able to resolve it. I would like some help as to which way to go. Thanks TypeError at /form_mat/ __str__ returned non-string (type DetComponente) Request Method: GET Request URL: http://127.0.0.1:8000/form_mat/ Django Version: 3.2 Exception Type: TypeError Exception Value: __str__ returned non-string (type DetComponente) Exception Location: C:\webcq\venv\lib\site-packages\django\forms\models.py, line 1253, in label_from_instance Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 models class DetComponente(models.Model): componentes = models.CharField (max_length=50, null=True) def __str__(self): return self.componentes class Componente(models.Model): componentes = models.ForeignKey (DetComponente, on_delete=models.CASCADE) descricao = models.CharField (max_length=50) def __str__(self): return self.componentes class EspecComponentes (models.Model): componentes = models.ForeignKey (Componente, on_delete=models.CASCADE) codigo = models.ForeignKey (Codigo, on_delete=models.CASCADE) espec_material = models.ForeignKey (EspecMaterial, on_delete=models.CASCADE) diametro1 = models.FloatField (blank=True) diametro2 = models.FloatField (blank=True) peso = models.FloatField (null=True, blank=True) class Meta: ordering = ['componentes'] def __str__(self): return str (self.componentes) views def view_mat(request, pk): data = {} data['db'] = EspecComponentes.objects.get(pk=pk) return render(request, 'materiais/view.html', data) -
How do I remove the JWT Authentication requirements from certain models? Django Rest API / Axios
I have a few models, some of them just holds images and information I want to display on the screen (BEFORE the user logs in) I followed a guide to setup my JWT authentication for users, and I created the other models myself. I'm getting Unauthenticated messages when I try to do a .get() on my other models, which I do not want them to need to be authenticated. I want anyone to be able to login, and see that information. What is a simple way, I can remove the authentication requirements from these models? I never set up any JWT for these models, so I am surprised the user model which has JWT is effecting these.. but anyways. I'm pretty new to coding. I cannot find anything on google to answer this question. How can I send some information through my axios get request to say, "HEY THIS DOESN"T NEED TO BE AUTHENTICATED." Like, a master key to get me through that requirement. enter image description here enter image description here enter image description here enter image description here -
I am lost here help me
I am trying to use python manage.py migrate but getting error so guide me please from django.db import models class Topic(models.Model): Top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.Top_name class WebPage(models.Model): topics = models.ForeginKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.UrlField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeginKey(Webpage) date = models.DateField() def __str__(self): return str(self.date) THIS IS THE ERROR:- File "E:\My_jango_code\sixth_project\sixth_app\models.py", line 15, in WebPage topics = models.ForeginKey(Topic) AttributeError: module 'django.db.models' has no attribute 'ForeginKey' -
How can I fetch data by joining two tables in django?
Looking for help got stuck at a point, I am new to python and django. There ARE two payments corresponding to one order, one COLLECTION and multiple TRANSFER and i need the payment corresponding to an order whose direction is COLLECTION only NOT transfered yet so that i can initiate TRANSFER against that order models.py class Orders(models.Model): id= models.AutoField(primary_key=True) payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')]) is_active = models.BooleanField(default=True) class Payments(models.Model): id = models.AutoField(primary_key=True) orders = models.ForeignKey(Orders, on_delete=models.CASCADE) direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), ('TRANSFER','TRANSFER')]) settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), ('NO','NO')]) is_active = models.BooleanField(default=True) qualified_orders = Orders.objects.filter(payment_gateway_code='CASHFREE', Exists(Payments.objects.filter(order=OuterRef('pk'), direction='COLLECTION', settlement_status='YES')), ~Exists(Payments.objects.filter(order=OuterRef('pk'), direction='TRANSFER'))) But above query is not working