Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invalid character in identifier in django
I am writing a simple code in django Code: status = self.get_object() owner = status.owner_id print("status.status ", status.status) if (status.status == "Active"): subject = 'Yantraksh-RFQ Status' message = 'You have succesfully raised RFQ' # shipper_email reci = Teacher.objects.filter(user_id=owner).values_list("shipper_email", flat=True) email_from = settings_bak.EMAIL_HOST_USER send_mail(subject, message, email_from, reci, fail_silently=False) But it is saying > SyntaxError: invalid character in identifier I am not able to find any error in the syntax, please help! error log: File "D:\Downloads-HDD\My work -- agg\django_school\classroom\views\teachers.py", line 220 reci = Teacher.objects.filter(user_id=owner).values_list("shipper_email", flat=True) ^ SyntaxError: invalid character in identifier -
How To Initialize A Value in ForeignKey Dropdown from View in Django
I need to set the value of my ForeignKey dropdown = to a url parameter when the form is rendered. I am able to successfully set other form fields to this value, but not the ForeignKey. I am trying to initialize the 'reference' form field which is a foreign key using the reference_id value which is passed via the url. I can successfully assign this value to the three other fields in the form, but not to 'reference'. Models.py class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.description Forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') Views.py def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) except Orders.DoesNotExist: pass instance.reference = order instance.save() return redirect('add_manifest', reference_id=reference_id) #this is where my problem is form = CreateManifestForm(initial={'reference': reference_id}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return render(request, 'add_manifest.html', context) And just in case it's needed: urls.py url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'), There are no errors, but the field does not set to the value passed through the URL. Like … -
Django SingleTableView object has no attribute 'filter'
When I am rendering a table from a legacy MySQL database using the class-based (SingleTableView) view I recieve the following message: "...object has no attribute 'filter'" I am trying to visualize the table by following the solution from Nicolas Kuttler (https://kuttler.eu/en/post/using-django-tables2-filters-crispy-forms-together/?c=208349) and the solution from this ticket: How do I filter tables with Django generic views?. When I deployed the solution initially it worked well, meaning that I saw the filter, and the table, but at some point the error message appeared. As I am being a beginner in web-developing I have no idea on what am I doing wrong, therefore I would greatly appreciate an advise of the wise community =) #tables.py import django_tables2 as tables from .models import ValuesModel class ValuesModelTable(tables.Table): export_formats = ['csv', 'xls'] col1 = tables.Column(accessor='pk_t.pk_type.type1', verbose_name='Column One') .... class Meta: model = ValuesModel template_name = 'django_tables2/bootstrap.html' .... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #filters.py import django_filters class ValuesModelFilter(django_filters.FilterSet): col1 = django_filters.CharFilter(field_name='pk_t__pk_type__type1', lookup_expr='icontains', label='Column One') .... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #forms.py from .models import ValuesModel from crispy_forms.helper import FormHelper class ValuesModelListFormHelper(FormHelper): form_method = 'GET' model = ValuesModel form_tag = False +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #utils.py from django_tables2 import SingleTableView class PagedFilteredTableView(SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_quryset(self, **kwargs): qs = super(PagedFilteredTableView, self).get_queryset() … -
Django how to get file path defined in the custom field
I'm using Django 2.2 and Django REST Framework. I'm writing a custom DRF serializer field, extending the JSONField to perform validation using jsonschema. I have defined the path of the scheme in the myapp.serializers like class MySerializer(serializers.Serializer): j_data = JSONSchemaField(schema='json_schema/validate.json') The file is saved in the myapp/json_schema/validate.json and the JSONSchemaField is defined in a file outside the application. json_validate.py class JSONSchemaField(JSONField): def to_internal_value(self, data): // Get file path here. return super().to_internal_value(data) How can I get the path to the schema in the JSONSchemaField class? -
Django get certain object from paginated object. Like `after` in Apollo
I am trying to implement Ariadne to my django app. I got problem with pagination. Well i am using django's default pagination. Thing is i want to select after certain objects in paginated queryset. Here is my resolver. So there is an after argument which would be optional but when provided i have to fetch from paginated queryset right after it's value. In this case after="some-UUID" def resolve_artist_releases(artist, *_, single=None, first=10, skip=1, after=None, last=None): albums = artist.album_set.all() if single is None else artist.album_set.filter(single=single) p = Paginator(albums.order_by("-created_dt"), first) if last: p = Paginator(albums.order_by("created_dt"), last) return p.page(skip).object_list Can you guys help me on this? -
Model instances saved only partially
I have a fairly complex view with several subforms and formsets with both many-to-many and one-to-one relationships. When getting a form from context object, I'm hitting a weird issue that some of the data is not saved. Correct model instance is created with form.save(), I can see all the fields I filled out in form, but all that's added to the database is pk, all the fields are empty. The same happens when I'm saving with commit=False and then saving again, when I'm updating fields manually and then saving or when I'm using force_insert=True. Creating new instances in the same code block however are saved without an issue. This doesn't end here, when saving many-to-many relationships, child models are saved without a hitch, but most of the time, m2m through models are not created. I said most of the time, because every once in a while they are. But even if they're not, the id descriptor in database is incremented so what I'm seeing in the through table is few lines, much less than there should be with non-sequential id-s. What am I dealing with here, does anybody have a clue? I'm out of ideas what to try next. I … -
Django allauth Automatically set mail address as confirmed
I am using django-allauth together with an LDAP-backend. So whenever a users logs in, the mail address is set to the mail address stored in our directory server. I was able to disable email confirmation by setting ACCOUNT_EMAIL_VERIFICATION = "none" But now those users have an unconfirmed mail address attached to their account. More specifically: I am trying to set up a mailman 3 including webUI and connect that to LDAP. Users having the mail address unconfirmed, causes them to not be able to use this address to subscribe to mailing lists. Can I maybe somehow modify the AccountAdapter to automatically confirm mail addresses when a user logs in? -
websocket connection in new_web.js not triggering consumers in django
the new.js file which contains the websocket connection and which actually connects/activates the django channels isn't connecting i don't understand where exactly the issue i have tried connecting another socket connection for different consumer in different html page that is working perfectly fine WebSocket HANDSHAKING /new/ [127.0.0.1:61934] WebSocket CONNECT /new/ [127.0.0.1:61934] Add specific.bYAxHTPf!sBbGasUiKdHR channel to post's group connected one websocket is connecting perfectly fine where as when i fireup localhost:8000/w which is supposed to connect the other websocket its not connecting that to consumers HTTP GET /static/js/channels/new_web.js 304 [0.01, 127.0.0.1:62085] i can access the websocket connection within the template but this websocket is triggering my path in routing which in turn triggers my consumers new_web.js $(function(){ endpoint = 'ws://127.0.0.1:8000/like/' // 1 var socket = new ReconnectingWebSocket(endpoint) // 2 socket.onopen = function(e){ console.log("open",e); } socket.onmessage = function(e){ console.log("message",e) var userData = JSON.parse(e.data) $('#new_user').html(userData.html_users) } socket.onerror = function(e){ console.log("error",e) } socket.onclose = function(e){ console.log("close",e) } }); socket.onclose = function(e){ console.log("close",e) } }); routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from posts.consumers import PostConsumer,LikeConsumer application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( [ path("new/", PostConsumer), path("like/", LikeConsumer), ] ) ) }) consumers.py class LikeConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user … -
Cannot Solve "ValueError: attempted relative import beyond top-level package"
I am running the project and shows this error. I have googled and tried some of the solutions but doesn't seem to work. File "/home/bs-094/Dev/backend/busgroup-backend/src/bus_portal_backend/apps/inquiry/forms/inquiry_details.py", line 2, in <module> from ..models.inquiry import Inquiry ValueError: attempted relative import beyond top-level package My folder structure is busgroup-backend src bus_portal_backend apps inquiry models _init_.py inquiry.py forms inquiry_details.py It would be great help is anyone helps me solve the problem. I am fairly new to django. Thanks -
Django REST Framework custom serializer mixin not working
I'm using Django 2.2 and Django REST framework. In the serializer, I want to have few fields only for creating an instance and not for updating. Means, the user won't be able to change the value of that field once created. Since Django does not provide any default way to do it. I am writing a mixin which when used will use the create_only_fields from the serializer Meta to remove the fields from the request data with PUT/PATCH request. serializer_mixin.py class CreateOnlyFieldsMixin(object): def to_internal_value(self, data): data = super().to_internal_value(data) print(data) if self.instance: # Update request print(data) for x in self.Meta.create_only_fields: if x in data: data.pop(x) return data and using in the serializer like class MySerializer(CreateOnlyFieldsMixin, serializers.ModelSerializer): class Meta: model = MyModel fields = [ 'id', 'name', 'value' ] create_only_fields = ['name'] But now calling any endpoint, it gives an error Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. Putting CreateOnlyFieldsMixin after serializers.ModelSerializer gives no error but has no effect of the mixin. Appending to_internal_value directly in the serializer is working as expected. -
How to use a field value instead of pk in the url?
I want to show the username or name of the person I want to update details for, in the url of update view. The only method I know is to display pk in the url. Is there a method to replace pk with a field value? Thanks in advance. -
in update form when went to update profile picture getting MultiValueDictKeyError at /42/accountdetails 'picture'
In my app i have a details where user can view and update their details.I went to update profile pic and when i choose profile pic and click on update it returns MultiValueDictKeyError at /42/accountdetails 'picture' models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='media',default="None") views.py def accountdetails(request,pk): user=User.objects.get(pk=pk) initial_values= {'Firstname':user.first_name,'Lastname':user.last_name, 'Username':user.username,'Email':user.email} if request.method == "POST": form = Accountdetails(request.POST,request.FILES) if form.is_valid(): email = form.cleaned_data['Email'] Username=form.cleaned_data['Username'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.filter(pk=pk).update(first_name=firstname, last_name=lastname,username=Username,email=email) pro=Profile.objects.filter(user_id=pk).update(image= request.FILES['picture']) messages.success(request,'Updated Successfully!') return redirect('accountdetails', pk=pk) else: form = Accountdetails(initial=initial_values) return render(request,'accountdetails.html',{'user': user,'form':form}) forms.py class Accountdetails(forms.Form): picture = forms.ImageField(required=False) #i am posting only for imagefield -
Django shorten query on save to ForeignKeyField
I have 2 models Owners, Relationships Owners class Owner(models.Model): id = models.BigAutoField(primary_key=True) nickname = models.CharField(max_length=20, unique=True) Relationships class Relationships(models.Model): id = models.BigAutoField(primary_key=True) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_owner') target_owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_target_owner') To add rows to Relationships, I used below query. owner1 = Owner.objects.filter(nickname='hide').first() owner2 = Owner.objects.filter(nickname='john').first() Relationships.objects.create(owner=owner1, target_owner=owner2) It is pretty clear. But when I inspect on django-debug-toolbar, it queried to database 3 times. Get nickname=hide from owners table. Get nickname=john from owners table. Insert into hide and john into relationship table. I wonder that, is it a general way? Or, Is there any clear way to performing above query? Thanks! -
How to make a login and signup page using an existing model in Django==2.1
I am a making a student management system with django. I have a Student model which should be modified only by the registrar when a student takes admission. The registrar will use the inbuilt django admin page to add students. class Student(models.Model): first_name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) roll = models.CharField(unique=True, max_length=200, null=False, blank=False) email = models.EmailField(unique=True, null=False, blank=False) age = models.PositiveIntegerField(blank=True) gender = models.CharField(choices=GENDER, default='O', max_length=1) dob = models.DateField(null=False, help_text='YYYY-MM-DD', blank=False) admission_type = models.CharField(choices=ADMISSION_TYPES, default='B', max_length=1) Now I want to be able to use this model to make a login and signup page for students. In the signup page, the student enters his valid roll number and a password. In the login page he must enter this roll and password to go to his dashboard. How can I do this efficiently? I have tried extending AbstractUser but I am unable to make it work. -
How to display relationship with back reference at django template through User?
I have such models class Employee(models.Model): """Employee information.""" user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='employee', unique=True) position = models.CharField("current position in a company", max_length=64, blank=True) birth_date = models.DateField("date of birth", null=True) skills = models.ManyToManyField( Technology, through="Skill", verbose_name="skills", blank=True) class Technology(models.Model): """Technologies.""" name = models.CharField('technology name', max_length=32, unique=True) class Skill(models.Model): """Information about an employee's skills.""" LEVELS = ( ('basic', 'Basic'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'), ('expert', 'Expert'), ) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) start_date = models.DateField( verbose_name='Works with since:') level = models.CharField("level", max_length=64, choices=LEVELS) And I can't understand why my template code doesn't work template.html {{ user.employee.position }} {{ user.employee.birth_date }} {{ user.employee.summary }} {% for i in user.employee.skills.all %} {{ i.technology.name }} {{ i.level }} {% endfor %} I can't see absolutely nothing. All models possible to see at adminpanel. And else then I using TemplateView such as class AccountView(TemplateView): template_name = "profile.html" def get_context_data(self, **kwargs): context = super(AccountView, self).get_context_data(**kwargs) context['skills'] = Skill.objects.filter(employee__user=self.request.user) return context then everything works fine. -
Is there any ways to combine two rows of table into one row using Django ORM?
I have a table which has columns named measured_time, data_type and value. In data_type, there is two types, temperature and humidity. I want to combine two rows of data if they have same measured_time using Django ORM. I am using Maria DB Using Raw SQL, The following Query does what I want to. SELECT T1.measured_time, T1.temperature, T2.humidity FROM ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T1, ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T2 WHERE T1.measured_time = T2.measured_time and T1.temperature IS NOT null and T2.humidity IS NOT null and DATE(T1.measured_time) = '2019-07-01' Original Table | measured_time | data_type | value | |---------------------|-----------|-------| | 2019-07-01-17:27:03 | 1 | 25.24 | | 2019-07-01-17:27:03 | 2 | 33.22 | Expected Result | measured_time | temperaure | humidity | |---------------------|------------|----------| | 2019-07-01-17:27:03 | 25.24 | 33.22 | -
Understanding Django localization in templates
I am trying to use two languages in my website, my native, and an english one. I followed the django documentation, from where I copied the code. I have the locale folders and files set up. When I open the site, it already sets the default language to Slovene, which should be English instead, and I don't know why. The main.html looks like this when I open the site: <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html" xmlns:height="http://www.w3.org/1999/xhtml" lang="sl" > If I understand correctly, the lang="sl" should be lang="en", and I do not know why it defaults to Slovene. Even when I use the form, it shows me both choices (English and Slovene), but when I select English, and click Go, it just refreshes the page, but doesn't change the language. The current language (Slovene) still stays selected, so I'm guessing that somewhere the correct language doesn't get selected. I'm also confused as to why it doesn't default to English when I start the server. Can anyone provide some insight or point me in the right direction? settings.py LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/Ljubljana' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] ugettext = lambda s: s LANGUAGES … -
How do I add points of skill tags for every correct main questions and sub questions?
enter image description here consider a folder which contains main questions and subquestions. Teacher create those questions with skill tags( core skill, knowledge skill, exam skill, foundation skill). Now student is taking his exam, first he will get main question, if he do well we have to add the points to that main question. For suppose he did mistake the main question, we have to give sub questions which relates to main question it also has skill tags. If he do correct here we should add the points of main and subquestions. -
how to test django modal details?
i'd like to test this little part of code : @staff_member_required() def prestation_details_modal(request, uuid): p = get_object_or_404(Prestation, uuid=uuid) return TemplateResponse(request, "includes/modal /prestation_modal.html", {'prestation': p}) i ever tested something like : def test_resp_temp_page(self): url = reverse('index') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplate(response, 'include/modal /mission_modal.html') thx for help ! -
Calling View in API Request Factory when testing in Django Rest Framework
Whenever we test an API in Django Rest Framework using API Request Factory why do we call the view when we are already passing the url . Look at the following code for better understanding . request = self.factory.post("/api/v1/menu/", data) views = MenuResource.as_view({"post": "post"}) response = views(request) response.render() self.assertEqual(201, response.status_code) In the above code we are calling the url as well as calling the view . View is being called for rendering the view on the url but that is not what my use case is . I just want to test the response code . Is there a way of getting the response code without rendering the view as that is an over kill for my use case . I have looked for other methods except for using API Request Factory but i just wanted to know why does API Request Factory need to call the view . Is there any advantage in comparison to other API Testing modules present in Django Rest Framework .enter code here -
How do I create a button for adding a time in the Django Form Template?
How do I create a button for adding a time in the Django Form Template? form is this class TodoForm(forms.ModelForm): dead_line = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime, initial=datetime.datetime.now()) class Meta: model = Todo fields = ['title', 'content','classification','dead_line'] widgets = { 'content': SummernoteWidget(), } form.html is this <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | safe }} <button type="submit" class="btn btn-primary float-right btn-block">Submit</button> </form> result question : What if I want to create an hour button or an extra day button? Do I need to use a widget? Should I create a js button? Thank you very much for giving me specific examples. tanks for reading ~! -
I want to show a fixed value in a field in forms.py
I am making a model form for mock up website, asking for seller information. I want the field country to be fixed to a certain country and the seller cannot change it.Assuming the website do not operate in any other country. How can i show the field as fixed and not changeable showing a fixed country value ? This is my model form: class seller(forms.Form): gst_number = forms.CharField(label='GST-Number',max_length=100, validators=[GST_validator]) add_line_i = forms.CharField(label='Address Line 1',max_length=100) city= forms.CharField(required = True,widget = forms.Select(choices=indiancities)) country = forms.CharField(required = True) I am getting it like this : I want it to be like this and country should not be editable. -
How to keep track of history of transactions and rollback when needed?
Let's say I'm maintaining an Activity log of a user in UserActivity model. class UserActivity(models.Model): description = models.TextField() query = models.TextField() How to implement and what fields are required on this model, so that I would be able to rollback a transaction in history at any time? What are its cons and dependencies? I know transaction.atomic. Think of this as doing a transaction a few days ago and rolling back today. -
Tests fails after import external library
Hey I'm facing kind of weird problem. I have Django project with 3 applications: core mturk_manager cognito_admin The mturk_manager is the new one. When I run tests only for this application using command python manage.py test mturk_manager or even with core application together python manage.py mturk_manager core everythings passes as expected. Problem is with application cognito_admin when I run all tests together some of the tests from my new application mturk_manager fails. I was debugging the problem for such a long time :) and found problem: In cognito_admin I'm importing external package from moto library from moto import cognito_idp even if I have commented out all tests from cognito_admin tests still fails in other application. I really need this package its really usefull. Any ideas how to solve this problem ? -
Delete data form after sending post request
I'm coding user management page. In page, I have form to add new user with post request and delete button with comfirmation form. I add new user successfully, page is reloaded, then I delete any account, but data in form I sent request to create new user is sent again with new user ID. How to fix?