Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have an error on django athentication system with authenticate () method
I have an issue with autenticate () method , please help me. it return to me '' the view didn't return an httpresponse . It returned none instead. def registrazione (request): if request.method == 'POST': form = FormSito(request.POST) if form.is_valid(): username = form.cleaned_data ["username"] password = form.cleaned_data ["password"] User.objects.create_user ( username = 'username', password = 'password' ) user = authenticate (request,User) else: form = FormSito() context = { form : 'form' } return render (request,"registration/form/registrazione.html", context) -
I am trying to write a factory. The error is mentioned below
SEPARATOR.join((model_name, attr)) for attr, value in factory_class._meta.declarations.items() if is_dep(value) AttributeError: 'Options' object has no attribute 'declarations' class Motors(models.Model): #models abc = models.ForeignKey( ABC, on_delete=models.CASCADE ) xyz = models.ForeignKey( XYZ, on_delete=models.CASCADE ) rejected_at = models.DateTimeField(auto_now_add=True) class MotorsFactory(factory.django.DjangoModelFactory): #factories abc = factory.SubFactory(ABCFactory) xyz = factory.SubFactory(XYZFactory) class Meta: model = Motors from pytest_factoryboy import register from .factories import MotorsFactory register(MotorsFactory) #conftest -
How to change function of Django source in our code
I want all inactive users also can login, in dajngo/contrib/auth/backends.py line 51 we have: def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ is_active = getattr(user, 'is_active', None) return is_active or is_active is None it should return True instead of is_active or is_active is None but i don't want change Django source. this is my login view: def login(request): if not request.user.is_authenticated: if request.method == "POST": phone_number = request.POST["phone_number"] password = request.POST["password"] user = authenticate(request, username=phone_number, password=password) if user is not None: login_auth(request, user) return HttpResponseRedirect("/account/") else: ctx = {'msg_bad':'wrong password or phonenumber!'} else: ctx = {} else: return redirect("/account/") return render(request, "account/login.html", ctx) is there way to solve this problem by returning True user_can_authenticate in this view or if we do that, it also work in account page and others ? or should do that solution everywhere ? -
Subset Django Tables across all Models
I am trying to figure a way to subset the Database that is > 10 GB in size. I tried tweaking around with Condensor and Jailer. The former has a space issue i.e can work effectively for DB under 10GB and I really couldn't figure out Jailer. So I went on with identifying relationships in my Django tables i.e Foreign key relationships. I have identified a primary key lets say : loan_application_number and looking for the same in all other tables that have access to it directly or indirectly. I am just having a hard time figuring out how can I subset my tables based on this key. I have minimal experience with the same and If anybody could guide me in the right direction. Before that I just need to understand if I can subset lets say two models: Model A : Loan Model B : Payments If Models A and B have lets say 10000 entries and have loan_application_no as their primary key. Then is there a way to get a 10% of these tables? -
How do I create a simple formset that works?
So the code I have: models.py class Department(models.Model): code = models.CharField(max_length=250, unique=True) code_meaning = models.CharField(max_length=250, ) def __str__(self): return "%s" % (self.code) urls.py path('departments/', DepartmentCreateView.as_view(), name='department'), department.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <div class="content-section"> {{ formset.management_form }} <form method= "POST"> {% csrf_token %} {% for form in formset %} {{ form}}<br><br> {% endfor %} <button class="btn btn-outline-info" type="submit">Save</button> </form> </div> {% endblock content%} views.py class DepartmentCreateView(CreateView): model = Department form_class = DepartmentForm template_name = 'department.html' def get_context_data(self, **kwargs): context = {'formset': DepartmentFormset} return context def form_valid(self, formset): formset.save() messages.success(self.request,'Changes were saved.') return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return HttpResponseRedirect(reverse('home')) forms.py class DepartmentForm(ModelForm): class Meta: model = Department fields = ('code', 'code_meaning',) My page shows the formset, but when I click on the submit button it just reloads, don't saves anything and the succes message is also not showed on my home page. (My other createviews where I have only one form works prefect) I very new to django so I don't know where I did something wrong ? Thanks in advance -
Behind the scenes of authenticate(),login(), and is_valid()
How these three differ from each other, I have seen the authentication() and login() in registration form, But i don't really understand these usage of these two in registration(Because i don't get an complete explanation form anywhere about this). From Django Doc, I understand that the valid() will make sure that, every field is perfectly validated according to the given and default requirements. But in some program I have seen the usage of valid() and followed with the login(). (I can't understand how that work without comparison of data) My Doubts How is these differ from each other? On first registration, by logic we have to store the credentials somewhere, and in login we have to compare that data with the stored data right. Then by these, what's happening behind the hood? Can anyone make it more clear for me about these three? And the usage?.Thankyou! -
How to query so that a field of each instance will show up instead of the actual instance
I am trying to query so that the value for a field in each model instance will show up with no duplicates. Here is the queryset in my django: queryset = Class.objects.filter(student=self.object.student).order_by('-date')[:10] However, this will give me a queryset of Class instances that this studnet is taking. What I want is a queryset of teacher(which is a field in the Class model). So, instead of Class#1, Class#2, Class#3, I want to have Teacher#1, Teacher#2, Teacher#3 corresponding to each class. Moreover, if there are any duplicates of teacher in the queryset, I want to show only one of them. If you need anything, please ask me. Thanks a lot. -
django user_groups table missing
I ahve a user model called TbUser and I have integrated a mysql legacy database with django. After doing migrations I have the follwing tables. django_seesion, django_migrations, django_content_type, django_admin_log, auth_permission, auth_group_permissions, auth_group When I log in to django admin page, and click on the TbUser then select a random user I am getting the following error. Exception Value: (1146, "Table 'db.tb_user_groups' doesn't exist") Should this table be created when migrations are run? -
SolarWinds N-central 5000 Query failed using zeep
I am trying to add Customer using zeep in Python3 in N-central Solarwind and getting error 5000 Query failed. def addcustomer(request): client = Client('http://server-name.com/dms/services/ServerEI?wsdl') settings_type=client.get_type('ns0:T_KeyPair') value = settings_type( 'customer_name','id_' ) response =client.service.CustomerAdd(Username=USER,Password=PASS, Settings=value) return render(request,'ncentral/addcustomer.html',locals()) This is what is written in Docs int customerAdd(String username, String password, List settings) throws RemoteException Adds a new Customer or Site to the MSP N-central. Parameters: username - the MSP N-central username. password - the Corresponding MSP N-central password. settings - A list of settings stored in a List of EiKeyValue objects. Below is a list of the acceptable keys and values. Mandatory (Key) customername - (Value) Desired name for the new customer or site. Maximum of 120 characters. Mandatory (Key) parentid - (Value) the (customer) id of the parent service organization or parent customer for the new customer/site. (Key) zip/postalcode - (Value) Customer's zip/ postal code. (Key) street1 - (Value) Address line 1 for the customer. Maximum of 100 characters. (Key) street2 - (Value) Address line 2 for the customer. Maximum of 100 characters. (Key) city - (Value) Customer's city. (Key) state/province - (Value) Customer's state/ province. (Key) telephone - (Value) Phone number of the customer. (Key) country - (Value) Customer's country. Two … -
Bulk create or update objects in database model in Django based on excel file
So I have following excel file: CustomerName ChannelName MarketName Cust-1 Chan-2 Market-1 Cust-1 Chan-2 Market-1 Cust-1 Chan-2 Market-1 Cust-1 Chan-3 Market-4 Cust-1 Chan-2 Market-5 Cust-2 Chan-2 Market-6 Cust-1 Chan-1 Market-7 Cust-1 Chan-2 Market-8 Cust-2 Chan-3 Market-9 Cust-3 Chan-4 Market-10 Which I load to dataframe using Pandas and then I iterate over rows to save every unique customer name market and channel combination I have in this file to my database.Which means that of the first 3 rows in the example only one object should be created since they are all the same. My customer model in Django is the following: class Customer(models.Model): """ Stores a single customer, related to :model:`customers.Market` and :model:`customers.Channel` and :model:`warehouses.Warehouse` """ market = models.ForeignKey(to="Market", default=None, on_delete=models.CASCADE, verbose_name="Market", help_text="Market id") channel = models.ForeignKey(to="Channel", default=None, on_delete=models.CASCADE, verbose_name="Channel", help_text="Channel id") name = models.CharField(max_length=128, default=None, verbose_name="Customer Name", help_text="Customer Name") def __str__(self): return self.name And this is how I am saving objects to the database pased on this dataframe: def transform_df_to_clientmodel(df): """Save all unique customers to database""" df.apply(lambda row: bulk_iterator_customer(row), axis=1) def bulk_iterator_customer(row): """ Create object in customer model Fetches object from database if exist and update with fields passed in defaults dict otherwise create new """ models.Customer.objects.update_or_create( name=row["CustomerName"], channel=models.Channel.objects.get(name=row["ChannelName"]), market=models.Market.objects.get(name=row["MarketName"]) … -
Managing migration of large number of fixtures in Django for unit testing
I currently have one fixtures for all my tests for my Django application. It is fine however updating units tests each time I add new object to my fixture is tedious. Objects count and equality of query set have to be updated. Many "get" method fails when duplicate appears for various reasons. Having a dataset filled with every possible use-case for each unit test seems like a bad practice. So I would like to have a fixture for each component of the app to test, e.g. if I have a model class "MyModel", it have a dedicated TestCase all its functionalities have unit tests and i would like them to have a dedicated fixture. The main interest would be that I automatically solves all three points mentioned above. However it has some drawbacks File management, I copy a directory into django's data directory for my fixture, I would need to manage multiple data directory. Redundance of some fixtures elements. Many element relies on the existence of other elements up to the user object, each fixture would need a prefilled database with some common objects (e.g. configured user) Django migrations. The two first points are not real problem but the task … -
django write dict to json and return json file object
I have some queryset from which I have to create json file and return file object as a response but while doing so I am getting server error. result = {'name': 'Test sample'} f = open("sample.json", "w") f.write(json.dumps(result)) f.close() return FileResponse(f, as_attachment=True, filename='sample.json') I think it should return json file object but it is not doing so. Its saying A server error occurred. Please contact the administrator. What am I missing here ? -
Django filter by date range and if no records in a date, return dummy records in that without being dead in loop
I have a very unique requirement and I have not noticed such a solution on Django documentation. Also, I don't want to use any loop after the database query even though I can achieve such a solution with loop over all the records. class Example(models.Model): date = DateField name = CharField and Let's say i have following records in the table [ {date: "2018-01-05", name="jhon doe"}, {date: "2018-01-11", name="jonathan someone"}, {date: "2018-01-21", name="someone developer"}, ] and my query: Example.objects.filter(date_range=["2018-01-01", "2018-01-31"]) As normal when we query with a date range, it returns all the records within that range. it's expected and normal. But I want it should come with a blank record when there are no records on a certain date range. As we notice I have only 3 records in that range, so I am expecting a result like this [ {date: "2018-01-01", name="Not Found"}, {date: "2018-01-02", name="Not Found"}, {date: "2018-01-03", name="Not Found"}, {date: "2018-01-04", name="Not Found"}, {date: "2018-01-05", name="jhon doe"}, {date: "2018-01-06", name="Not found"}, '''''to be continued in a range'''' ] Is there anyone who knows to prepare queryset like above this during filter? I need it like this coz, i am using a javascript tool in the frontend, … -
using __in operator in if condition
I have view with if condition: if request_status.id__in [3,5]: car.booked = False car.save() I want to use __in operator in it similar to this example Entry.objects.filter(id__in=[1, 3, 4]) Any help is appreciated. -
How to automatically add logged in user as creator of product
I have a form that can create a product. My problem is how do I add the logged-in user automatically? While logged-in, when I create a product and look at admin http://127.0.0.1:8000/admin the 'creator' object is blank --- or I have to choose the user manually. I want to relate a product with a user. models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) prodname = models.CharField(max_length=255, null=True) description = models.CharField(max_length=255, null=True) price = models.FloatField(null=True) image = models.ImageField(null=True, upload_to='images') views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from .forms import ProductForm, RegisterUserForm from .models import * def home_view(request): return render(request, 'home.html') def product_create_view(request): form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'product/product_create.html', context ) def register_view(request): form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() return redirect('product/login.html') context = { 'form': form } return render(request,'product/register.html', context) def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home-view') else: messages.info(request,'Username or password is incorrect') return render(request,'product/login.html') def logout_user(request): logout(request) … -
Do I define new models if they already exist in db? [duplicate]
I am new to Django. I am trying to write a code, which takes data from a database and shows it in a website. My question is, if the data already exist in the database and I only want to get them, do I need to define new models in the models.py? -
How to store model field data type based on choices?
Here in my model I want to set option value based on choice value. How can I do this or any other solutions ? class MyModel(models.Model): title = models.ForeignKey(Title, on_delete=models.CASCADE) option_name = models.CharField(max_length=200) option_value_choices = [ (1, "models.BooleanField"), (2, "models.DateField"), (3, "models.IntegerField"), (4, "models.CharFIeld") ] option_value_type = models.CharField(max_length=10, choices=opt_choices) option_value = .. ? -
how to make a field have choices from another model in django
I am creating a gradeviewing app for my School Project and I am confused on how do I need to build relationships of each models. I want a subject field on my StudentGrade model to have a list of choices coming from Student model but I only want to display/get the enrolled_subjects of the student instance model.py: class Subjects(models.Model): subject_name = models.CharField(...) subject_code = ... ... class Student(models.Model): student = models.ForeignKey(setttings.AUTH_USER_MODEL,...) enrolled_subjects = models.ManyToManyField(Subjects) ... class StudentGrade(models.Model): PERIOD_CHOICES = [ ... ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, limit_choices_to=Q(is_student=True)) period = models.CharField(choices=PERIOD_CHOICES, max_length=25) subject = // i want this to be list of subjects that the student has enrolled grade = models.DecimalField(max_digits=4, decimal_places=2) on the StudentGrade model, I want the subject field to be based on the enrolled_subjects of student instance how can I do that? -
How to update model except null values using PUT method in django?
I have a Post model which has many fields. I want to update a field only if it's not null which means it should have the value from the request. post = PostModel.objects.get(id = id).update() -
How do you create a dynamic form field in Django?
I want to create a dynamic form field that always filters a model and shows the filtered elements in a list in the form. Here is the code I have so far: class OrganisorClassStatusUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs) self.fields['off_day_student'] = forms.ModelChoiceField( queryset=Class.objects.filter(teacher=self.object.teacher).filter(is_new_set=True).filter(time=self.object.time).order_by('-date')[:10] ) The problem I have with this code is that the self.object refers to the form itself, not the model I am trying to update. This is important since I need to filter the queryset using some of the information in the model I am trying to update. Please ask me any question if you need anything. Thanks a lot. -
Validating a Regex pattern entered into form via user interface
I'm struggling to find how to validate a user entered Regex pattern. The use case here is that the user interfaces allows the user to create rules that merge any incoming Merchants that meet the regex pattern specified in a rule. So the user themselves enter the regex pattern. I hope that makes sense. merchants = Merchant.objects.filter(name__iregex=merge_rule.pattern) I get system errors when a bad regex is entered into the rule, so I'd like to validate against these. -
How do I connect to an mssql db that is on a windows computer from a linux VM inside these computers' intranet?
I have a client that has a desktop application for its employees. I've been tasked with porting this over to a web application that runs within their intranet. This web application obviously needs to connect to the db they currently have. But I am lost as to how to do this. It's an mssql db. I've never worked with mssql before. Nor have I made a web application that runs only within an intranet. Can anyone help? I'm writing this web app in django, for what it's worth -
How to POST multiple objects in one JSON request?
I am using django-rest-framework and recently I encountered a problem. I need to post such request and get 2 objects created: { "lease": 28, "date": [ { "from_date": "2021-06-01", "until_date": "2021-07-01" }, { "from_date": "2022-03-22", "until_date": "2022-04-23" } ] } Model looks like this: class DateUnavailable(models.Model): lease = models.ForeignKey(Lease, on_delete=models.CASCADE, blank=False, null=False) from_date = models.DateField(blank=True, null=True) until_date = models.DateField(blank=True, null=True) Currently my views.py looks like this: class DateUnavailableCreateView(generics.CreateAPIView): #POST permission_classes = [IsAuthenticated, ] def get(self, request): all_dates = DateUnavailable.objects.all() serializer = DateUnavailableSerializer(all_dates, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, *args, **kwargs): lease = request.data['lease'] dates = dict(request.data.items())['date'] flag = 1 arr = [] for date in dates: modified_data = modify_input_for_multiple_dates(lease, date) date_serializer = DateUnavailableSerializer(data=modified_data, many=True) if date_serializer.is_valid(): if date_serializer.validated_data["lease"].user != self.request.user: return (Response('You are not allowed to make changes to this schedule', status=status.HTTP_405_METHOD_NOT_ALLOWED)) date_serializer.save() arr.append(date_serializer.data) else: flag = 0 return (Response(arr, status=status.HTTP_201_CREATED) if flag == 1 else Response(arr, status=status.HTTP_400_BAD_REQUEST)) This view is the slight modification of the one that I used successfully for creating multiple file objects related to one object through ForeignKey. -
Django Accessing Child Data in Templates from Parent object
I am new to Django and am trying to do something that should be very straightforward (in my mind) but I've spent a few hours on this and haven't solved it yet. Goal: Within a template I would like to get a value from a field from a child object using the parent. In this case I am trying to get the lab_request object by knowing the parent sample. So far I have tried using both a ForeignKey in the Lab_Request model as well as a OneToOneField Specific area in the code where I believe I am going wrong is {{ sample.lab_request.placeholder_to_be_replaced }}. Sample is a parent and 'Lab_Requests' is a child. In thus case I have set it to OneToOneField but really I have this issue in another area where it will be a Parent to multiple Children. Code: #models.py class Sample(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) status = models.CharField(max_length=2, choices=SAMPLE_STATUS_OPTIONS, default="01") sample_number = models.CharField(max_length=19, unique=True, editable=False, default=get_sample_number) class Inspection_Request(models.Model): #Add stuff here placeholder_to_be_replaced = models.CharField(max_length=1) sample = models.OneToOneField(Sample, on_delete=models.CASCADE) inspector = models.OneToOneField(Inspector, on_delete=models.CASCADE, null=True, blank=True) #views.py class SampleHomeView(ListView): model = Sample samples = Sample.objects.all context_object_name = 'samples' template_name = '<app name>/sample.html' ordering = ['-sample_date'] paginate_by = 10 #sample.html {% … -
Hosting django channels on apache and daphne
I am trying to deploy django chat application on apache the same way. Can someone please help me with setting up the daphne server? I am totally new to deploying django channels. I have a linux virtual machine (ubuntu). The site is running but the websocket connection is not established. the error I see in the console is: (index):16 WebSocket connection to 'ws://chat.bagdigital.in/ws/chat/lobby/' failed: (anonymous) @ (index):16 (index):30 Chat socket closed unexpectedly chatSocket.onclose @ (index):30 here is my apache conf file. <VirtualHost *:80> ServerName chat.bagdigital.in #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error_chat_bagwebsite.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/pksingh/chat-app/chat-api/static Alias /media /home/pksingh/chat-app/chat-api/media <Directory /home/pksingh/chat-app/chat-api/static> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/media> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/chatapi> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/pksingh/chat-app/chat-api/chatapi/wsgi.py WSGIDaemonProcess bag_chat_app python-path=/home/pksingh/chat-app/chat-api python-home=/home/pksingh/chat-app/chat-api/venv WSGIProcessGroup bag_chat_app I have installed the redis server. And the socket connection is running fine if I run the django server at port 8000 normally without using apache. python3 manage.py runserver 0.0.0.0:8000 & Can someone help me with setting up daphne server here??