Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use keyword arguments when subclassing django's model FileField
I'm trying to subclass Django's models.FileField but somewhere, the instantiation is going very wrong. Here's my code: class DatafileObjectField(models.FileField): def __init__(self, source_key=None, **kwargs): print('SOURCE KEY IS:', source_key) source = settings.DATA_SOURCES[source_key] kwargs["storage"] = import_string(source["storage"])(**source["storage_settings"]) super().__init__(**kwargs) class MyModel(models.Model): # THIS IS THE ONLY REFERENCE IN MY ENTIRE CODEBASE TO THIS FIELD # Yet somehow the field is instantiated by django without the source_key argument file = DatafileObjectField(source_key='my-data-source', help_text="Upload a data file containing mast timeseries") When I do: python mange.py makemigrations That print statement is issued twice: SOURCE KEY IS: my-data-source <output from checks> SOURCE KEY IS: None Followed by the inevitable error, because the second instantiation of the subclassed DatafileObjectField doesn't receive the source_key argument. Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 142, in handle ProjectState.from_apps(apps), File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 220, in from_apps model_state = ModelState.from_model(model) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 409, in from_model fields.append((name, field.clone())) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 514, in clone return self.__class__(*args, **kwargs) … -
retrieve elements with the same foreign key value django python
please, how can i get all elemnts with the same foreingnkey on my web page; i use mysql database to store all data; then i send queries to get all data from mysql database to my page html, i try to make a filter in but it didn't work. models.py: class tsf(models.Model): perimetre = models.FloatField(blank=False, null=True) production_tsf = models.ForeignKey(production, on_delete=models.CASCADE, null=True, blank=False) tsf_periode_1 = models.ForeignKey(periode_1, on_delete=models.CASCADE, null=True, blank=False) tsf_periode_2 = models.ForeignKey(periode_2, on_delete=models.CASCADE, null=True, blank=True) tsf_periode_3 = models.ForeignKey(periode_3, on_delete=models.CASCADE, null=True, blank=True) tsf_periode_4 = models.ForeignKey(periode_4, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.perimetre) if self.perimetre else '' views.py: def tsf_projet(request, id_production): new_tsf = forms.tsf_form() diction={'tsf_configuration':new_tsf, 'title':"configuration de la TSF" } if request.method== 'POST': new_tsf = forms.tsf_form(request.POST) if new_tsf.is_valid(): new_tsf.save(commit=True) perimetre = new_tsf.cleaned_data['perimetre'] tsf_periode_1 = new_tsf.cleaned_data['tsf_periode_1'] tsf_periode_2 = new_tsf.cleaned_data['tsf_periode_2'] tsf_periode_3 = new_tsf.cleaned_data['tsf_periode_3'] tsf_periode_4 = new_tsf.cleaned_data['tsf_periode_4'] diction.update({'perimetre':perimetre}) diction.update({'tsf_periode_1':tsf_periode_1}) diction.update({'tsf_periode_2':tsf_periode_2}) diction.update({'tsf_periode_3':tsf_periode_3}) diction.update({'tsf_periode_4':tsf_periode_4}) #return production_liste(request) prod = production.objects.filter() tsf_new=tsf.objects.filter() diction={'tsf_affichage':tsf_new, 'tsf_configuration':new_tsf, 'title':"configuration de la TSF", 'affichage_nom':prod} return render(request, 'simulation/tsf_projet.html', context=diction) html doc: {% for ts in tsf_affichage %} {% for af in affichage_nom %} {% if af.id == ts.production_tsf_id %} <!--comment je fais le filtre ?--> <tr> <td> {{ts.production_tsf.nom}} </td> <td></td> <td> {{ts.perimetre}} </td> <td></td> <td> {{ts.tsf_periode_1.taxe}} </td> <td></td> <td> {{ts.tsf_periode_2.taxe}} </td> <td></td> <td> {{ts.tsf_periode_3.taxe}} </td> <td></td> … -
NoReverseMatch at /account/login/ Reverse for '' not found. '' is not a valid view function or pattern name in django 3
I am new to Django3. Recently I am working on this project where I was using django authentication system for login. I was facing an issue: NoReverseMatch at /account/login/ Reverse for '' not found. '' is not a valid view function or pattern name. My following code is: settings.py: INSTALLED_APPS = [ 'social_account.apps.SocialAccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'social_mass_media.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ] WSGI_APPLICATION = 'social_mass_media.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'dashboard' views.py: from … -
Django TransactionTestCase - Main thread can't see model objects created in child thread
I am trying to run some tests in my Django application. I am basically testing the paho-mqtt publisher and subscriber working with my views. The subscriber needs to run indefinitely to listen to publisher's messages, so I run the subscriber in another thread, it listens to a topic and saves the objects accordingly. But the problem is, that my tests are run in my main thread, and even though I am subclassing TransactionTestCase (as recommended in many SO answers), I am still not getting the objects in main thread. Counting the objects in the child thread gives me 6, while counting them in the main gives 0. Here's the code: # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) topic = 'SENSOR/+' # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe(topic) class SensorReadingAPITest(TransactionTestCase): """ A class to test API endpoints of creation, updating, and retriving sensor readings. """ def setUp(self): self.api_client = APIClient() sensor = Sensor(name="test_sensor",threshold=28,alarm_systems="EM") sensor.save() self.sensor = Sensor.objects.get(name="test_sensor") print(self.sensor) #Connection to the client is established here self.client = mqtt.Client() self.client.on_connect = on_connect … -
django get primary key after saving modelform and pass it to the second form but second form can't be saved
I have a modelform that after saving the form i get the primary key and pass it to the second form but some how the second form data is not saved. I am not sure what i did wrong. ef create_new_survey(request): if request.method == 'POST': form = NewSurveyForm(request.POST) if form.is_valid(): new_contact = form.save() return HttpResponseRedirect(reverse(add_question, args=(new_contact.pk,))) else: form = NewSurveyForm() return render(request, 'create_new_survey.html', {'form': form}) def add_question(request, survey_id): if request.method == 'POST': person = Survey.objects.get(id=survey_id) form = QuestionForm(request.POST, instance=person) if form.is_valid(): form.save() return HttpResponseRedirect('/choice') else: form = QuestionForm() return render(request, 'question.html', {'form': form},) class Survey(models.Model): title = models.CharField(max_length=200) #creator = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Questions(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) def __str__(self): return self.enter_question -
Django session work in Chrome but not work in Firefox
This my view code email = request.session.get('email') user = User.objects.get(email=email) if (user.is_active == True): return redirect('home') this works perfectly in chrome browser -
How to create new Order with OrderItems
I'm trying to make a web application by Django framework. I have models Order, Product and OrderItem with M:M relationship. So I don't know how to put it together and create order with OrderItems. I tried something, but I can't create an OrderItem, only create Order. I will be happy for any advice. models.py: class Order(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Preaparing', 'Preaparing'), ('OnShipping', 'OnShipping'), ('Completed', 'Completed'), ('Canceled', 'Canceled'),) date = models.DateTimeField('created', auto_now_add=True) state = models.CharField(max_length=60, choices=STATUS, default='New') total_price = models.DecimalField(max_digits=12, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.CASCADE) transport = models.ForeignKey(Transport, on_delete=models.CASCADE) products = models.ManyToManyField(Product, through='OrderItem') def __str__(self): return f'{self.id}' class OrderItem(models.Model): quantity = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return f'{self.product.name},{self.order.user.lname + " "+ self.order.user.fname}' class Product(models.Model): name = models.CharField(max_length=40) manufacturer = models.CharField(max_length=50) quantity = models.IntegerField() price = models.DecimalField(max_digits=7, decimal_places=2) weight = models.IntegerField() color = models.CharField(max_length=30) description = models.TextField() date = models.DateTimeField('added', auto_now_add=True) categories = models.ManyToManyField(Category) def __str__(self): return self.name forms.py: class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' class OrderItemForm(forms.ModelForm): class Meta: model = OrderItem fields = ['quantity'] views:py def addOrder(request): if request.method == 'POST': form = … -
How to make selected option stay after refreshing the page?
I want selected option to stay after refreshing the page, but have no idea how to do that, as with other kind of serach fields it is easy to do with setting a value,but here should I somehow move a 'selected' statement or it is impossible to do with form GET? <form method="GET" class="mb-5 "> <select class="custom-select my-1 mr-sm-2" name="selectchair" id="inlineFormCustomSelectPref"> <option value="">Choose...</option> {% for chair in chairs %} <option value="{{ chair.Cid }}">{{ chair.Name }}</option> {% endfor %} </select> </form> -
DRF: based on the validation of field x, stop the validation of field y and delete from data
I have a form where the user can post a deal, and for that they can choose to either upload an image (x), or provide a link to an already uploaded one on the internet (y). So when either of the fields exists and is valid, I would like to dismiss the other field from validation. Here is a simplified Model: class Deal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deals', on_delete=models.CASCADE) title = models.CharField(max_length=1024, blank=False, null=False) slug = models.SlugField(max_length=1024, unique=True, blank=True) poster = models.ImageField() poster_url = models.CharField(max_length=1024, blank=True, null=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) And here's my serializer: class DealSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = Deal fields = '__all__' def validate_poster_url(self, value): poster = self.initial_data.get("poster") if value == "" and poster == "": # set to mutable self.initial_data._mutable = True self.initial_data.delete("poster") raise serializers.ValidationError( "Deal must either have a Poster or a Poster URL") return value def validate_poster(self, value): poster_url = self.initial_data.get("poster_url") if value != "": if poster_url == "": # set to mutable self.initial_data._mutable = True self.initial_data.delete("poster_url") raise serializers.ValidationError( "Deal must either have a Poster or a Poster URL") return value def create(self, validated_data): deal, _ = Deal.objects.update_or_create(**validated_data) return deal When I submit for example a poster_url, the poster … -
Annotate with Subquery "get" instead of "filter"
Why can i run an annotate with a Subquery featuring a filter query like this: invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.filter( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).values('code')[:1]), ) But when i try to use a get query method gives me the error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.get( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).values('code')[:1]), ) ## OR invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.get( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).code), ) ## BOTH GIVE THE SAME ERROR What's wrong here? Is it simply impossible to use a get query inside the Subquery? I can live with the filter option, but it would be more correct for me to use the get since i know for sure there's always one and only one match. -
Django form fields errors not showing in Ajax
I have a Django form that makes use of the AJAX. The form works as intended. The problem now is that Django form errors are not shown when invalid input is entered. I followed the Django forms API as described here. Is there a possible way out of this issue? main.js $(document).ready(function(){ $("#itemForm").on('submit', function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "post/ajax/myURL/", data: serializedData, success: function (data) { if($('input[type="checkbox"]').prop("checked") == true){ // some codes here $("#itemsTable tbody").prepend( // some codes here ) console.log("Checkbox is checked. Modal will not be closed"); } else if($('input[type="checkbox"]').prop("checked") == false){ // some codes here console.log("Checkbox is unchecked. Modal will now be closed"); } }, error: function (jqXHR, textStatus, errorText, data) { for (var name in data) { for (var i in data[name]) { $('#ajaxErrorMessage').fadeIn().text(errorText) ; } } setTimeout(function() { $('#ajaxErrorMessage').fadeOut("slow"); }, 5000 ); console.log(data.message) // more console logs here } }) }); }); views.py def create_item(request): # request is sent via ajax if request.is_ajax and request.method == "POST": form = ItemForm(request.POST) data = {} if form.is_valid(): data = form.save() # serialize the new item object in json data = serializers.serialize('json', [data, ]) # send data to the client side return JsonResponse({"data": … -
django 3.2 : autoslogfield return None
I installed autoslug on django3.2 my model: class Courses(models.Model): title = models.CharField(max_length=100, null=True) description = models.TextField(null=True) image = models.ImageField(upload_to=get_dynamic_path_course, null=True) price = models.PositiveIntegerField(null=True) slug = AutoSlugField(populate_from=get_populate_from, null=True, blank=True, allow_unicode=True) def __str__(self): return '%d : %s => , %s' % (self.id, self.title, self.slug) function : def get_populate_from(instance): return instance.title.replace(' ', '_') my problem: slug field is always None -
how to get a combined django query while preserving order
I have 2 separate Django queries: a=History.objects.values('video__id').filter(user_id=10,video__channel__id__in=s.values('channel_id')).order_by(‘-video__date’) b=Videos.objects.values('id').exclude(id__in=map(lambda n:n['video__id'],a)).filter(user_id=10,channel__id__in=s.values('channel_id')).order_by('-date') res=list(b)+list(a) This res gives me proper ordering . However,I need to combine these into single query while preserving order of each query. Used Union. Videos.objects.values('id').exclude(id__in=map(lambda n:n['video__id'],a)).filter(user_id=10,channel__id__in=s.values('channel_id')).order_by('-date').union(History.objects.values('video__id').filter(user_id=10,video__channel__id__in=s.values('channel_id')).order_by('-video__date')) but unable to get proper order. -
Created ojects are not shown through cmd django python
from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") t=Task(title="dhiraj") t.save Task.object.all() error says Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: sabin_task.title The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 256, in repr data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 262, in len self._fetch_all() File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 51, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: sabin_task.title models.py file … -
How can I make "has_object_permission( )" work?
I'm trying to create an object level permission for a user. The structure of my ddbb model is the following one: A Teacher owns a Classroom (id_teacher ForeignKey) A Classroom owns some Students (id_classroom ForeignKey) I want to let the access to Student information just for the teacher who owns the classroom where the Students are registered. Here are the API code and the permission code: class StudentAPI(RetrieveUpdateAPIView): permission_classes = [GetStudentPermission, ] def get(self, request): student_ = Student.objects.get(username=request.GET['username']) s_student_ = StudentSerializer(student_) return Response(s_student_.data) class GetStudentPermission(BasePermission): message = 'La información de este estudiante está restringida para usted' def has_object_permission(self, request, view, obj): cls_ = Classroom.objects.filter(id=obj.id_classroom.id).first() tch_ = Teacher.objects.get(classroom=cls_) user_ = User.objects.get(id=tch_.id_user.id) return bool(user_ == request.user) It seems like permission classes is not working at all because I can access to the information of each student being registered with any user account. Thank you beforehand -
How can I create GrapgQL API's with Django and Neo4J Database?
I am working on a project where I need to make GraphQL API's with Django Server (Graphene-Django) and Neo4J database. I have looked quite a lot over the internet, but I wasn't able to find any useful resources. If anyone can give a simple example of the flow or suggest some resources, please help. -
How to get Form data in django using cloud firestore?
Form picture ID is been selected but I'm not getting the values in the form, please check my code files. See in the picture in URL of the browser, update/id is selected, the problem is values are been fetched in the form. HTML: <form id="task-form" name="myForm"> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-building" placeholder="Building name" name="building" value="{{buildings.building}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-postal" placeholder="Postal Code" name="postalCode" value="{{buildings.postalCode}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-town" placeholder="town" name="town" value="{{buildings.town}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-street" placeholder="Street" name="street" value="{{buildings.street}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-house" placeholder="House No." name="houseNo" value="{{buildings.houseNo}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-info" placeholder="Additional Information" name="additionalInfo" value="{{buildings.additionalInfo}}"> </div> </div> </div> <div class="text-center mt-3"> <button type="submit" id="btn-task-form" class="btn btn-primary ">UPDATE</button> </div> </form> views.py def update_Building(request, id): docId = id; context = { 'buildings': db.collection('Buildings').document(docId).get() } return render(request,"EmployeeAdmin/updateBuilding.html", context) urls.py path('update/<str:id>/',views.update_Building,name='update_Building'), -
My login register panel disappear when reduced to mobile and tablet size
I am working on a website in which I have an HTML page for login, registration, dashboard. When I reduce the dimension of the website it disappears. I have separate HTML pages for the top and navbar section. Here Desktop View and this is Mobile/Tablet View. Please suggest any solution. This is my topbar.html page <!-- Top header start --> <header class="top-header th-2 top-header-bg"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12"> <ul class="top-social-media pull-right"> {% if user.is_authenticated %} <li> <a href="{% url 'dashboard' %}" class="sign-in"><i class="fa fa-fa-user"></i> Dashboard</a> </li> <li> <a href="javascript:{document.getElementById('logout').submit()}" class="sign-in"><i class="fa fa-sign-out"></i> Logout</a> <form action="{% url 'logout' %}" id="logout" method="POST"> {% csrf_token %} <input type="hidden"> </form> </li> {% else %} <li> <a href="{% url 'login' %}" class="sign-in"><i class="fa fa-sign-in"></i> Login</a> </li> <li> <a href="{% url 'register' %}" class="sign-in"><i class="fa fa-user"></i> Register</a> </li> {% endif %} </ul> </div> </div> </div> This is my navbar.html page <!-- Main header start --> {% load static %} <header class="main-header sticky-header header-with-top"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12"> <ul class="top-social-media pull-right"> {% if user.is_authenticated %} <li> <a href="{% url 'dashboard' %}" class="sign-in"><i class="fa fa-fa-user"></i> Dashboard</a> </li> <li> <a href="javascript:{document.getElementById('logout').submit()}" class="sign-in"><i class="fa fa-sign-out"></i> Logout</a> <form action="{% url 'logout' %}" id="logout" … -
Django Rest Framework: How to work with Foreign Key in Serializer?
I am new to Django and I have this DB Schema DB Schema I have coded schema in models.py from django.db import models from auth_jwt.models import User class Board(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) board_name = models.CharField(max_length=20) board_desc = models.CharField(max_length=120) def __str__(self): return self.board_name class Column(models.Model): column_name = models.CharField(max_length=100) board = models.ForeignKey(Board, null=True, related_name="board", on_delete=models.CASCADE) def __str__(self): return self.column_name class Todo(models.Model): todo_name = models.CharField(max_length=200) todo_desc = models.CharField(max_length=200) column = models.ForeignKey(Column, null=True, related_name="column", on_delete=models.CASCADE) def __str__(self): return self.todo_name serializers.py from rest_framework import serializers from .models import Board, Todo, Column class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ["id", "board_name", "board_desc"] class ColumnSerializer(serializers.ModelSerializer): board = BoardSerializer(read_only=True) class Meta: model = Column fields = ["id", "column_name", "board"] depth = 1 class TodoSerializer(serializers.ModelSerializer): column = ColumnSerializer(read_only=True) class Meta: model = Todo fields = ["todo_name", "todo_desc", "column"] depth = 1 But whenever I POST data to Todo Model it returns django.db.utils.IntegrityError: NOT NULL constraint failed: api_todo.column_id Post Data { "todo_name": "satyam", "todo_desc": "dsa", "column": { "column_name": "Todo", "board": { "board_name": "Todo", "board_desc": "Whatta Day!" } } } Views.py class TodoView(ListCreateAPIView): serializer_class = TodoSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user) def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response({"todo": serializer.data}, … -
Django web deployment [closed]
I have this site as a domain http://xxxx-officesuits.com:8000/ how can I deploy my newly created website to that domain? Send help! -
How to get object id before assignment to database in Django
I need an object's id before saving that object in the database. my code return none. -
Databases: Many to Many of a foregin key in a HASHTAG - FOLLOWER relation
Let's think I build Instagram platform. I have 2 models: class Follower(): hastags = ??? class Hashtag(): name = char... I want: To be able to fetch -all specific follower- hashtags. And reverse: fetch -all Followers- of a specific hastags. A Follower don't have to have an hashtag. An Hashtag exist only once a follower is adding it. -
Reverse django admin custom url with two parameters
I have the following custom admin url def get_urls(self): (...) info = self.model._meta.app_label, self.model._meta.model_name urlpatterns = [ path('<path:object_id>/CompareParameters/<int:parameter_id>', wrap(CompareParameters.as_view()), name='%s_%s_CompareParameters' % info), ] and I need to call it from an inline and it takes two parameters (the fact the view's name includes word parameters is just a coincidence) I have tried to do it like so def pair_parameter(self, obj): return mark_safe(f'<a style="padding: 5px; background-color: lightblue;" target="_blank" href="{reverse("admin:agregator_agregatorproduct_compareparameters", args=[obj.ProductId_id, obj.DistributionParameterId_id, ])}">Spárovavat parametr</a>') or like so def pair_parameter(self, obj): return mark_safe(f'<a style="padding: 5px; background-color: lightblue;" target="_blank" href="{reverse("admin:agregator_agregatorproduct_" + str(obj.ProductId_id) + "_" + str(obj.DistributionParameterId_id) + "_compareparameters")}">Spárovavat parametr</a>') and by a few other combinations with no success. What would be the right way to do it? The final URL looks eg like this .../admin/agregator/agregatorproduct/1854146/CompareParameters/9330 where the first arg is obj.ProductId_id and 2nd is obj.DistributionParameterId_id Thank you in advance. -
jsonResponse return id instead of the object name django
i'm trying to fetch data from jsonResponse into ajax , but in the foreign key field it returns object_id instead of the object name my models.py class Product(models.Model): item = models.CharField(max_length=50) class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) active = models.BooleanField(active=True) my views.py def alerts(request): if request.is_ajax: data = Item.objects.filter(active=False).values() print(data) return JsonResponse({'items':list(data)}) #print(data) returns this <QuerySet [{'id': 13, 'item_id': 14, 'active': False}]> i dont know how to return item name instead its id (item_id) $(document).ready(function(){ $('.btn-click').click(function(){ $.ajax({ url:'{% url 'maininfo:alerts' %}', dataType:'json', type:'GET', success:function(data){ var obj = data.items var mainObj = data.items; var k = '<tbody>' for(i = 0;i < data.items.length; i++){ k+= '<tr>'; k+= '<td>' + mainObj[i]["item_id"] + '</td>'; '</td>'; k+= '</tr>'; } k+='</tbody>'; document.getElementById('tableData').innerHTML = k; } }) }) }) <div x-data="{ dropdownOpen: false }"> <button @click="dropdownOpen = !dropdownOpen" class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click"> <i class="fas fa-bell"></i> </button> <div x-show="dropdownOpen" class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll "> <table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center"> <thead> <tr> <th width="30%">deactive items</th> </tr> </thead> <tbody id="tableData"></tbody> </table> </div> </div> is there something wrong within my json response ? or a better approach to achieve it -
How to properly configure authentication views? (Django)
There are two views index and index1 and my login view is def loginview(request): if request.user.is_authenticated: return redirect('index') else: return redirect('index2') urls.py urlpatterns = [ path('',loginview,name="login"), path('index/',index,name="index"), path('index2/',index2,name="index2"), ] The code works but I want to only access index and index2 after the user is logged on or logged out. When I navigate to localhost:8000/index and localhost:8000/index2, the page directs to the respective pages. How to restrict authorization on these pages?