Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django get file size and put it in serializer
serializers.py class ModFileSerializer(serializers.ModelSerializer): size = serializers.CharField(default=os.path.getsize('file'), max_length=16) class Meta: model = models.ModFile fields = '__all__' read_only_fields = ( 'size', ) models.py class ModFile(models.Model): downloads = models.IntegerField(default=0) file = models.FileField(upload_to='mods/') created_at = models.DateTimeField(auto_now_add=True) Here I have a serializer for the ModFile model and the only thing that's missing is the file's size, I know os.path.getsize() needs the exact location of the file so how do I actually access the file field from the model in order to pass in the getsize() function or is there a better way to do it? -
Django tests serializers: "django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N" and "django.core.exceptions.AppRegistryNotReady"
I am testing my serializer in Django Rest Framework with pytest. Here are my modules versions: python 3.8.8 django==3.2.5 djangorestframework==3.12.4 pytest==6.2.4 Here is my test_serializers.py file: from my_app.serializers import my_serializer class TestMySerializer: def setup(self): self.serializer = my_serializer @pytest.mark.parametrize( "input", [ { "a": ["test"], "b": ["test"], "c": ["test"], }, ], ) def test_valid_serializer(self, input): ser = self.serializer(data=input) assert ser.is_valid() @pytest.mark.parametrize( "input", [ {"a": ["test"]}, ], ) def test_invalid_formats(self, input): ser = self.serializer(data=input) assert not ser.is_valid() And of course my serializers.py file is: class my_serializer(Serializer): a = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) b = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) c = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) The test_valid_serializer test pass without any problem because the input is valid for the serializer. OK ✅ The test_invalid_formats should pass as well because the input is not valid for the serializer. But unfortunately this test doesn't pass and I have this error that occurs: django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Following this stackoverflow post, I add a DJANGO_SETTINGS_MODULE variable pointing to my settings.py file. When I try again my test, the following error occurs: django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps … -
Word Quiz - How to properly implement VIEW and HTML page Django
I am building a website for learning vocabulary in English. The website let users add words in English and an association on how to remember the word in Hebrew. I want to add a word quiz function. The user gets 4 random words from the database and has to choose the right word and if he answered correctly he gets the right answer I get a little tricky how to implement it and would be happy to help. What do I do wrong when I click on a word I get nothing? (I try to get the "message") def practice(request): words_list = Words.objects.filter(approved= True) # Take all the words that approved random_word_to_guess = random.choice(words_list) word_1 = random.choice(words_list) word_2 = random.choice(words_list) word_3 = random.choice(words_list) if request.method == "POST": guess = request.POST.get("guess") if request.POST.get("correct"): message = "Correct answer" return render(request, "practice.html", {'message': message},{'guess':guess}) else: message = "wrong answer" return render(request, "practice.html", {'message': message},{'guess':guess}) return render(request, "practice.html", {'word_1':word_1,'word_2':word_2,'word_3':word_3,'random_word_to_guess':random_word_to_guess,}) <h1> Practice </h1> </br> {{random_word_to_guess.English_word}} </br> </br> </br> <form name = "guess" action ="" method="post" class="from-inline"> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_1.Hebrew_word}}</button> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_2.Hebrew_word}}</button> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_3.Hebrew_word}}</button> <button name = "correct" type="button" … -
Django channels web chat not updating live
I built a live web chat that has 2 people interacting, the user and a friend. Everything works except I need to refresh it to actually see a new text. I have no idea what is not working, as I've done something similar before but with group chat and not 1 - 1. Here is the code: Consumer: class PrivateChatConsumer(WebsocketConsumer): # Fetch messages def fetch_messages(self, data): self.friend = self.scope['url_route']['kwargs']['friend'] self.user = self.scope["user"] messages1 = PrivateMessage.objects.all().filter(author__username=self.friend, friend__username=self.user) messages2 = PrivateMessage.objects.all().filter(author__username=self.user, friend__username=self.friend) messages = list(chain(messages1, messages2)) messages.sort(key=lambda x: x.timestamp, reverse=False) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) # New message def new_message(self, data): self.friend = self.scope['url_route']['kwargs']['friend'] author = data['from'] author_user = User.objects.get(username=author) friend = User.objects.get(username=self.friend) message = PrivateMessage.objects.create( author=author_user, content=data['message'], friend=friend ) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) # returns a list of json objects def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'author': message.author.username, 'content': message.content, 'friend': str(message.friend), 'time_stamp': str(message.timestamp), 'image': message.author.profile.image.url, 'id': message.id, 'is_online': message.author.profile.is_online } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message, } def connect(self): self.friend = self.scope['url_route']['kwargs']['friend'] self.room_group_name = 'chat_%s' % self.friend # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def … -
How can I import a django model from one project into another project, both the projects use same database
File structure - root/ project1/ app1/models.py project1/ project2/ app2/views.py project2/ Now I want to import a model from project1/app1/models.py into project2/app2/views.py . How can I achieve this? I had a larger django project earlier but I have to split the project into different micro-services due to dependency issues. -
Setting X-Frame-Options header for static HTML file in Django
In my Django project, I am serving an HTML file from the static folder. This HTML file is basically being used to render PDFs on the site. I want to set the X-Frame-Options header for this HTML file and, if possible, all the static files served from the Django server. I have already set the 'django.middleware.clickjacking.XFrameOptionsMiddleware' middleware in my settings.py file. This is only applying the X-Frame-Options to my views and not to my static files. Any suggestions on how to configure the X-Frame-Options for static files? Note: This header is needed for Clickjacking Protection and I need to make sure this particular HTML file cannot be clickjacked. -
django prefetch_related() attribute error
How to properly user prefetch_related with ManyToMany relation my model: class Subject(models.Model): subject_name = models.CharField(max_length=150) subject_code = models.CharField(max_length=50) year = models.ForeignKey(YearLevel, null=True, on_delete=models.SET_NULL) units = models.CharField(max_length=10) def __str__(self): return self.subject_name + ' ' + '(' + self.subject_code + ')' class Student(models.Model): student = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to= Q(is_student=True), on_delete= models.CASCADE) enrolled_subject = models.ManyToManyField(Subject) my view: def home(request): verses = VerseOfTheDay.objects.all() news = Announcement.objects.all() student_grade_form = AddStudentGradeForm() students = Student.objects.all().prefetch_related('subject_set') context = { "verse": verses, 'news': news, 'form': student_grade_form, 'students': students, } return render(request, 'sample.html', context) my html: {% for student in students %} <p> <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}"> {{student.student}} </a> </p> <div class="collapse" id="collapse{{forloop.counter}}"> <div class="card card-body"> {% for subject in student.subject_set.all %} {{subject.subject}} {% endfor %} </div> </div> {% endfor %} I am getting an error: AttributeError at / Cannot find 'subject_set' on Student object, 'subject_set' is an invalid parameter to prefetch_related() -
Django app does not display content, how to fix it?
The Blog button does not display information about the number of blogs written and the blogs themselves (when adding a blog number, nothing appears in the address bar.https://i.stack.imgur.com/Zv700.jpg -
Receiving "Select a valid choice. That choice is not one of the available choices." while using Djongo ForeignKey with Django
I got this weird error in Django Admin while using the ForeignKey from djongo.models. Not sure if I did anything wrong in the models file. Error Message Image Machine/models.py from djongo import models class Machine(models.Model): _id = models.ObjectIdField(primary_key=True) machine_type = models.TextField(null=False) machine_description = models.TextField(null=False) def __str__(self): return self.machine_type # Create your models here. class Errorcode(models.Model): _id = models.ObjectIdField(primary_key=True) code_name = models.TextField(null=False) machine_type = models.ForeignKey('Machine', on_delete=models.CASCADE) description = models.TextField(null=False) instruction = models.TextField(null=False) def __str__(self): return self.code_name class AdditionalFile(models.Model): error_code = models.ForeignKey('Errorcode', on_delete=models.CASCADE) file_name = models.TextField(blank=True) file_path = models.FileField(blank=True, upload_to='static/asset') def __str__(self): return self.file_name If any other files is needed to inspect the problem, I can add the code here. -
Change table name for django model in runtime
Example Django model with table name: from django.db import models class MyModel(models.Model): class Meta: managed = False db_table = "default_table_name" than i have a few filters(in the real world more than 1): qs = MyModel.objects.filter(id=42) Question How can i change model name ("default_table_name") dynamically, in runtime, request can have 'table_name' in 'query_params'? It doesn't work: 1 I can't change "db_table" directly: qs.model._meta.db_table = request.query_params.get('table_name’) 2 Raw query is too complicated. I don't want to convert all filters to SQL by myself. MyModel.objects.raw('SELECT * FROM %s WHERE id=42', [request.query_params.get('table_name’)]) -
Authenticating AJAX requests in Django for an already logged in user
I have a long form, so in order to prevent the dreaded retype all fields cause cat pounced on the power cord, I wish to save fields everytime a field is changed via AJAX. Its easy to set up an Ajax view that does not require authentication, however these forms do require authentication. A user would have already logged in when editing the form. So I have been reading about Django REST framework, which talks a lot about tokens. I am guessing this is for server to server comunication? When talking user to server, could one not just re-use the CRSF token in the form, and in the backend authenticate by checking the CRSF token like this: from django.middleware.csrf import CsrfViewMiddleware def check_csrf(request): reason = CsrfViewMiddleware().process_view(request, None, (), {}) if reason: # CSRF failed raise PermissionException() def AjaxFormChange(generic.View): def post(self, request): check_csrf(): # Do something to the model, e.g. obj = Foo.objects.get(id=request.POST['id']) obj.foo = request.POST['foo'] obj.save What is the recommended way of authenticating AJAX requests in Django for an already logged in user? -
CreateView and UpdateView based class are not working in Django Project
I have Django in Which there is app called Listing and it's model as follows but CreateView and UpdateView are not woking for model. I am also using mixins but I have implemented Custom User , so is that cuases a problem? ListingCreateView is working properly in frontend but new Listing in database is not created! Any other user is updating listing of others, UserPassesTestMixin not working import uuid from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() class Listing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) owner = models.ForeignKey(User, on_delete=models.CASCADE) ...other fields CreateView class ListingCreateView(LoginRequiredMixin, CreateView): model = Listing fields = blah blah blah def form_valid(): form.instance.owner = self.request.user return super().form_valid(form) UpdateView class ListingUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Listing fields = blah blah blah def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) def test_func(self): listing = self.get_object() #print(self.request.user, listing.owner) if(self.request.user == listing.owner): return True else: return False Tysm for solving in advance! -
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, …