Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The view Kespaweb.views.contact didn't return an HttpResponse object. It returned None instead
hey guys am trying to make a code on sending mails from contact page and am stuck somehow tried sending mails from contact pageenter image description here -
Is CCAvenue payment gateway integration possible in REACT and Django
I'm trying to integrate CCAvennue to my website which has tech stack REACT and DJANGO, but I'm confused with documentation shared by CCAvenue. Please can someone simplify the implementation? -
Box Developer Account JWT Auth Related query
I am using BoxSDK for python. There I am using JWT authentication. I have created an app on Developer account for testing which uses authentication as OAuth 2.0 with JSON Web Tokens (Server Authentication). After creating this TestApp in developer account I am using it in some APIs to do some basic operations in Box. I also got an Service Account ID. related to my test app. All good till here. But I am facing issue when I am uploading a folder in my box account through browser and then try accessing that folder contents via Box API, its not accessible. The same is accessible when I am adding the service account ID as a collaborator in that folder. So I want to know if there is any option using which I dont need to do the above part i.e. adding service account ID as a collaborator in every folder that I want to access through API. Please suggest. Is this behavior only for test account? If I take Enterprise edition of Box, will this issue be solved? I need that whatever folder I upload in Box through website, it should be accessible vis API where I am using JWT … -
Deploying Django & React app in Azure failing to load
I have built an app with an Django back-end, a React front-end and a Postgres database, and I am in the process of deploying them to Azure for the first time. Key actions I have taken: used django-webpack-loader and webpack-bundle-tracker, so my front and back-end code can be deployed as one app set up Django app in Azure using the App service migrated my postgres database into Azure using the Azure Database for PostgreSQL flexible server Current outputs: deployed code successfully using github continuous deployment set my database, allowed_hosts, secreet_key and port values in application settings successfully migrated my django folders into the Azure environment using the Web SSH in the Azure portal when I run manage.py runserver 9000 in the Web SSH, I am able to connect My issue: When I visit my url, the page times out, with 'Application Error'. I'm troubleshooting the error in the logs, which return the output below. I have noted the error - TypeError: expected str, bytes or os.PathLike object, not PosixPath, but I'm stuck after this. Can anyone offer any suggestions? Azure Error logs: /home/LogFiles/2023_01_20_lw0sdlwk0000X9_default_docker.log (https://wittle-test.scm.azurewebsites.net/api/vfs/LogFiles/2023_01_20_lw0sdlwk0000X9_default_docker.log) 2023-01-20T10:10:15.109452667Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2023-01-20T10:10:15.109456467Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed … -
django-(1062, "Duplicate entry 'admin1' for key 'username'") [closed]
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() : try: form.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) I have got saved Custom User but Don't saving in palform but why is not showing database palform page. what was the problem? Can anyone help me? -
How can I annotate django-polymorphic models that have GenericRelations to other models with GenericForeignKeys?
I have a parent model named Content that inherits from Django polymorphic. This is a simplified example, but I have a Post model that inherits from Content. On the Content model, notice that I have a GenericRelation(Note) named notes. What I'm trying to do is annotate all Content objects with a count of the number of notes. It's the exact same result you would get in the below for loop. for content in Content.objects.all(): print(content.notes.count()) Below is a fully reproducible and simplified example. To recreate the problem Setup new Django project, create superuser, add django-polymorphic to the project, and copy/paste the models. Make migrations and migrate. My app was called myapp. Open manage.py shell, import Post model, and run Post.make_entries(n=30) Run Post.notes_count_answer() and it will return a list of numbers. These numbers are what the annotated Content PolymorphicQuerySet should show. Example: Post.notes_count_answer() [3, 2, 3, 1, 3, 1, 3, 1, 2, 1, 2, 2, 3, 3, 3, 1, 3, 3, 2, 3, 2, 3, 2, 1, 2, 1, 1, 1, 1, 2] The first number 3 in the list means the first Post has 3 notes. What have I tried (simplest to complex) basic >>> Content.objects.all().annotate(notes_count=Count('notes')).values('notes_count') <PolymorphicQuerySet [{'notes_count': 0}, {'notes_count': … -
local gitlab Auth 2.0 and django
Hello We made our own Gitlab installation on our server. I installed Readthedocs Local in the link below. In order to connect our accounts on gitlab with readthedocs, I was asked to make the following settings from the gitlab section in the readthedocs document. https://readthedocs.org/ https://dev.readthedocs.io/en/latest/install.html But interestingly, even though I set the settings on our own server gitlab.local, by default django goes to gitlab.com when I connect to gitlab via devthedocs.org. However, it should connect to gitlab.local on my server, how can I fix this problem? On page 34 of this document here https://readthedocs.org/projects/django-allauth/downloads/pdf/latest/ "The GitLab provider works by default with https://gitlab.com. It allows you to connect to your private GitLab server and use GitLab as an OAuth2 authentication provider as described in GitLab docs at http://doc.gitlab.com/ ce/integration/oauth_provider.html" I need your support in this matter. Thank you very much. Configure the applications on GitHub, Bitbucket, and GitLab. For each of these, the callback URI is http://devthedocs.org/accounts//login/callback/ where is one of github, gitlab, or bitbucket_oauth2. When setup, you will be given a “Client ID” (also called an “Application ID” or just “Key”) and a “Secret”. Take the “Client ID” and “Secret” for each service and enter it in your local … -
social-auth-app-django Google Login and React-Native
I'm using the social-auth-app-Django library on my Django Rest API (DRF) to authenticate users with social providers. I am using the expo-auth-session library (though this could be changed) in my React Native frontend to open a webbrowser instance for the client to use to log in with social providers (i.e. google). The issue is that once the login is succesful, the small window from the webbrowser instance instead of closing, redirects back to the App in the small browser window. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) for key in ['GOOGLE_OAUTH2_KEY', 'GOOGLE_OAUTH2_SECRET', ]: exec("SOCIAL_AUTH_{key} = os.environ.get('{key}')".format(key=key)) SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://localhost:19006/' urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('oauth/', include('social_django.urls', namespace='social')), ] index.tsx const signInGoogle = async () => { const redirectUri = AuthSession.makeRedirectUri({ useProxy: true, }); const result = await WebBrowser.openAuthSessionAsync( `http://localhost:8000/oauth/login/google-oauth2?next=${redirectUri}`, redirectUri ); console.log(result); }; Once the login is succesful, the small window from the webbrowser instance instead of closing, redirects back to the App/WebApp in the small browser window. -
using reverse url in javascript
I need to add event listener to standard django select field. The listener will (in the future) do htmx.ajax call ( https://htmx.org/api/#ajax ) urls.py from django.urls import path from .views import mailtemplate_GetSchema, refresh_schema from .views import surat_schema_table urlpatterns = [ path('htmx/surat_schema_table/<str:template_id>', surat_schema_table, name='surat_schema_table'), ] currently I have a test template. This template will not do ajax call, just display final url tobe called form template ( surat_form_htmx.html ) {% extends "admin/change_form.html" %} {% block after_field_sets %} <!--- add htmx --> <script src="https://unpkg.com/htmx.org@1.6.0"></script> <style> /* DivTable.com */ .divTable{ display: table; width: 100%; } .divTableRow { display: table-row; } .divTableCell, .divTableHead { border: 1px solid #999999; display: table-cell; padding: 3px 10px; } .divTableHeading { display: table-header-group; font-weight: bold; } .divTableFoot { background-color: #EEE; display: table-footer-group; font-weight: bold; } .divTableBody { display: table-row-group; } </style> <!-- EOF evt listener id_template --> Obj ID: <input id="loaded_object" id="loaded_object" type="text" size="20" readonly {% if not add %} value="{{ obj_id }}" {% endif %}> Selected Template: <input id="selected_template" name="selected_template" type="text" size="20" readonly > url: <input id="call_url" name="call_url" type="text" size="20" readonly > <script> const selectElement = document.querySelector("#id_template"); selectElement.addEventListener('change', (event) => { var result = document.getElementById("id_template").value ; var url_final={% url surat_schema_table result %} ; document.getElementById('selected_template').value = result; document.getElementById('call_url').value = … -
Is it possible in Django model tables to perform arithmetic operations on a record in another table?
How can I fill in a row or add a second table? I need to perform calculations with the last row from the first table and send the results to the second table. This is something reminiscent of processing data in two DataFrame . How can I add a table of values to the model after performing calculations on the data from the last row from another table model? Or is this only possible with the participation of the DataFrame functionality? class Model_1(models.Model): name_1 = models.IntegerField() name_2 = models.IntegerField() name_3 = models.IntegerField() name_4 = models.IntegerField() class Model_2(models.Model): name_5 = models.IntegerField() name_6 = models.IntegerField() queryset = Model_1.objects.all() values_m1 = queryst.name_1 * queryst.name_2 / queryst.name_3 - queryst.name_4 queryset = Model_2.objects.all() values_m2 = queryst.name_5 = values_m1 -
I have 2 index.html files in django project, how to show direct separately
I have 2 index.html files in django project, but in different apps. How can i show direct separately for each of them? def index(request): return render(request, 'index.html') -
Permit creation only if model is subclass of mixin
I would like to allow the creation of a comment only to those models that are sub-classing a specific mixin. For example, a Post model will have a reverse GenericRelation relation to a Comments model. The comments model is using a custom content types mechanism implemented on top of django's due to the fact that the project uses sharding between multiple databases. The reverse relationship from Post model to Comments is needed to be able to delete Comments when a Post is also deleted. Putting a simple coding example of what I would like to achieve: class Post(models.Model, HasCommentsMixin): some_fields = .... class HasCommentsMixin(models.Model): has_comments = GenericRelation('comments.Comment') class Meta: abstract = True What I would like would me a way to say inside a permission check of a Model: if class is subclass of HasCommentsMixin, allow the creation of a comment. So for the Post model, comments can be created. But if it's not a subclass the Mixin, comments should not be allowed. I hope I have provided a description that makes sense. I cannot share real code due to product license and protection. Thank you. -
Error in trying to connect Model to ModelForm in Django
I'm learning Django and am trying to make a request form to fill by using Django and an MySQL database and i am encountering issues trying to connect models.py to forms.py making a ModelForm with a database and table i have already created. It returns this error specifically (envworld) C:\Seen\Documents\envworld\myweb>python manage.py makemigrations Traceback (most recent call last): File "C:\Seen\Documents\envworld\myweb\manage.py", line 22, in <module> main() File "C:\Seen\Documents\envworld\myweb\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Seen\Documents\envworld\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Seen\Documents\envworld\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Seen\Documents\envworld\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Seen\Documents\envworld\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Seen\Documents\envworld\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Seen\Documents\envworld\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Seen\Documents\envworld\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Seen\Documents\envworld\myweb\formsite\admin.py", line 2, in <module> from .forms import RequestForm File "C:\Seen\Documents\envworld\myweb\formsite\forms.py", line 12, in <module> request = Request_Form.objects.get(pk=1) File "C:\Seen\Documents\envworld\lib\site-packages\django\db\models\manager.py", line 85, … -
Django Requests and Concurrency
I'm a little bit confused as to a few concepts regarding Django and concurrency. Suppose two users append data to the database or make a query at the same time. How do I determine what data to render for the user? I know each model has an id, but how is that associated with the user? Is this done mainly through the primary key field which you can add to Django views, or is this already done using Django sessions, and thus no need for management of primary keys or Django model ids? I've been researching for hours but I still don't understand this concept. -
Why individually rendered form fields not posting in Django?
I have a class based UpdateView that works fine if I render the form as {{ form.as_p }}. It updating the values, but looks bad. If I try to render the fields individually it does not updating the values. I can't figure out how to fix it, I'm not so familiar with class based views. I don't think there is a validation error (i don't know how to check it in class based views) because {{ form.as_p }} works well. Thank you in advance if someone can help me out! models.py class LeaderFeedback(models.Model): def __str__(self): return str(self.employee) employee = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="employed") leader = models.ForeignKey(User, on_delete=models.CASCADE, related_name="employer_leader") goals01 = models.CharField(max_length=100, null=True, blank=True) goals01_deadline = models.CharField(max_length=30, null=True, blank=True) goals01_value = models.IntegerField(null=True, blank=True) leader_comment = models.CharField(max_length=500, null=True, blank=True) views.py class UpdateLeaderFeedbackView(SuccessMessageMixin, UpdateView): model = LeaderFeedback form_class = PeriodicLeaderFeedbackForm template_name = 'performance/periodic/leader_feedback_edit.html forms.py class Meta: model = LeaderFeedback fields = '__all__' goals_value =( (1, "Nem teljesült"), (2, "Részben teljesült"), (3, "Megfelelő"), (4, "Maximálisan teljesült"), ) widgets = { 'goals01_value': forms.RadioSelect(choices=goals_value), 'leader_comment': forms.Textarea(attrs={"rows":"3", 'class': 'form-control'}), urls.py app_name = 'performance' urlpatterns = [ ... path('periodic/leader_feedback_edit/<pk>', login_required(UpdateLeaderFeedbackView.as_view()), name='update_leaderfeedback'), ... leader_feedback_edit.html <div class="card shadow p-2 my-2"> <div class="row"> <div class="col-md-5"> <h6 class="">Cél 1:</h6> {{ object.goals01 … -
I need to Prefetch data but only last in django
class AppliedEvent(models.Model): event_type = models.ForeignKey(EventType, on_delete=models.CASCADE, related_name='applied_events', null=True) seedbed = models.ForeignKey(Seedbed, on_delete=models.CASCADE, null=True, related_name='applied_events') seed = models.ForeignKey(Seed, on_delete=models.CASCADE, related_name='applied_events', null=True) user = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_events', null=True) class AppliedEventTime(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() event = models.ForeignKey(AppliedEvent, on_delete=models.CASCADE, related_name='times') applied_by = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_times', null=True) User have ability to add new event time by creating new AppliedEventTime instance. class AppliedEventMixin: request: Any def get_queryset(self) -> QuerySet: return AppliedEvent.objects.filter(user_id=self.context.request.user).select_related( 'user', 'event_type', 'seedbed', 'seed' ).only('user__username', 'event_type__name', 'seedbed__id', 'seed__id').prefetch_related( 'times' ) This is my query set mixin for django-extra controller @api_controller('/applied_event', auth=JWTAuth(), permissions=[IsAuthenticated]) class AppliedEventController(AppliedEventMixin): @route.get('/applied_event/{event_id}', tags=['applied_event'], response=AppliedEventOutSchema) def event_by_id(self, event_id: int): event = get_object_or_404(self.get_queryset(), pk=event_id) return event This is controller for API and point. class EventTypeNameSchema(Schema): id: int name: str AppliedEventTimeSchema = create_schema(AppliedEventTime, exclude=['id', 'event'], custom_fields=[('applied_by', UserOutSchema, None)]) class UserOutSchema(Schema): id: int username: str class AppliedEventOutSchema(ModelSchema): event_type: EventTypeNameSchema user: UserOutSchema times: List[AppliedEventTimeSchema] class Config: model = AppliedEvent include = ['id', 'seedbed', 'seed'] This is my schema. my question is, how can i prefetch only latest added AppliedEventTime instance related to AppliedEvent? -
How to display multiple database values in a single input?
I have a small problem for a few hours. I'm working on an app that uses django python. (I'm new to Django) I'm currently working on the Front-end, and I would like to display a first name and last name in an input. This works fine for two separate input but I would like to display the first name and last name in the same input. I do not know how to do <input style="background-color: blue;"{{form.user_first_name}}> Thanks -
Django - How can I collect several item/quantity for one order, and save it with one submit of form
I have this model: class ItemsInExternalOrder(models.Model): order = models.ForeignKey(ExternalOrder, on_delete=models.DO_NOTHING) item = models.ForeignKey(Item, on_delete=models.DO_NOTHING) quantity = models.IntegerField() created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self) -> str: return " ".join([f'{self.order}', f'{self.item}', f'{self.quantity}']) and the form : class ItemsInExternalOrderForm(forms.ModelForm): class Meta: model = ItemsInExternalOrder fields = ["order", "item", "quantity"] and HTML: <form action="" method="POST">{% csrf_token %} {{ form.as_p}} <input type="submit" value="Save"> </form> How can I collect several item/quantity for one order, and save it with one submit of form. I saw some examples with JS but I wonder if it is possible with Django Forms only and HTML. Thanks in advance, and apologies if this question is already asked, I just cant find answer without JS if it is possible. -
How to implement registration for Junior levels of users for my project
I'm developing an ecommerce related project in Django rest framework. In my project, there are three types of users, primary user, junior level user and clients. i will keep the registration open for primary users and the next level (junior level and clients) users should only be registered by primary users. primary user will create the credentials and send the invite for next level of users. I've no proper ideas for this. can anyone suggest some good ideas for this ? -
How to use Celery and/or Redis or RabbitMQ for sending email?
I need to implement sending emails via Celery and/or Redis or RabbitMQ. I have a todo app, with various model instances and one of them is done which is booleanfield. And when the task is to send emails to the user when the task is done or undone. So what should i do ? What do i need to show you in my code in order to be able help me? Thanks in advance, would be glad if you provide some tutorials, articles, docs for better understanding -
(1062, "Duplicate entry 'admin1' for key 'username'")
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() and user.is_valid(): try: form.save() user.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) Error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\charu\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\charu\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\charu\OneDrive\Desktop\cha\school social\myschool\polls\views.py", line 19, in studentreg user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=3) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 161, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 155, in _create_user user.save(using=self._db) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line … -
VSCode: [Django] How to navigate to the desired file via urls includes ike PyCharm
enter image description here How to realize it so that when I click on urls inside includes, it moves to the desired file like PyCharm I've already installed vscode extensions Pylance and Django -
NOT NULL constraint failed: tickets_category.name
I am creating a ticket app in my django project. When I try to create a ticket the NOT NULL constraint failed: tickets_category.name error shows up. I'm not sure why the value for category_name field won't pass correctly. How do I proceed? any help is much appreciated. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name views.py view for creating a ticket def createTicket(request): form = TicketForm() categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category, created = Category.objects.get_or_create(name=category_name) ticket = Ticket.objects.create( host = request.user, category=category, name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) … -
Django problema de vistas
Hola tengo un problema en django, hice un proyecto personal de un inventario. El problema es que entrando a un link directo, cualquier usuario registrado puede ver los productos de otro usuario http://000000/products/viewproduct/1, esta vista es para ver un producto, pero si cambio el numero al final, que es el id del producto en la base de datos puedo ver el que sea siempre y cuando exista, por ejemplo mi amigo tiene 5 productos con las id del 5 al 10 y yo solo del 1 al 4. si yo inicio sesion en mi cuenta y pongo http://000000/products/viewproduct/5 <- ahi le cambie el numero de id del producto y ese no es mi producto pero aun asi lo puedo consultar. Ese es mi problema y ya intente usando {% if request.user.is_authenticated %} pero no sirve. your text class ViewProduct(LoginRequiredMixin, DetailView): model = Product template_name = "products/view.html" context_object_name = "product" Esta es la vista creada -
Django DRF Model doesn't show foreign keys in admin panel
I have a model in my Django application for review. This model has two foreign keys to the product and user models. But when I go to the admin panel and try to add a new review I don't see the review models dropdown select for the foreign keys. I'm expecting to see the foreign keys fields rendered in my admin panel as dropdown selects like in the blue box in the picture below. Screenshot of my admin panel to add a new order object But the admin panel doesn't show those fields. It only shows the name, rating, and comment fields. Screenshot of my admin panel to add a new reivew object Here is my review model. class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True), product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True), name = models.CharField(max_length=350, null=True, blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating)