Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error while installing psycopg2 in vscode on windows
I am trying the following command in vscode cmd on windows 8.1 pip install psycopg2 error I am getting after using the above command: ERROR: Command errored out with exit status 1: command: 'c:\users\rock\envs\demo\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\rock\\AppData\\Local\\Temp\\pip-install-fczxt3cu\\psycopg2\\setup.py'"'"'; __file__='"'"'C:\\Users\\rock\\AppData\\Local\\Temp\\pip-install-fczxt3cu\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\rock\AppData\Local\Temp\pip-wheel-i_fkxw14' --python-tag cp38 cwd: C:\Users\rock\AppData\Local\Temp\pip-install-fczxt3cu\psycopg2\ Complete output (22 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\psycopg2 copying lib\compat.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\errors.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\extras.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\pool.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\sql.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\tz.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_json.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_lru_cache.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_range.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-3.8\psycopg2 running build_ext building 'psycopg2._psycopg' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ -
How to properly render a field from a database in a page without refreshing?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page, for example, they enter their # and then after they click/tab onto the next field, it renders the name on top, so the user knows they've entered the correct info. This name is also stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = … -
How to subclass Media to override render_js method?
How to create Media class with custom render in Django 2.X? I want to render widget with custom js module (script type is not text/javascript as in parent Media class) class TypedScriptMedia(forms.widgets.Media): def render_js(self): # This never got called, instead parent method will be called return [format_html( f'<script type="{script_type}" src="{script_path}"></script>', self.absolute_path(script_path) ) for script_type, script_path in self._js] class CustomWidget(forms.Widget): template_name = 'geo/widgets/display_map.html' # media = TypedScriptMedia( # js=( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # ) # class Media(TypedScriptMedia): # extend = False # js = ( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # @property # def media(self): # return TypedScriptMedia(js=( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # ) @property def media(self): # this is called media = super().media media += TypedScriptMedia( js=( ('module', 'module.js'), ( 'text/javascript', 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' 'webcomponents-bundle.js' ) ) ) return media All commented code has no effect I also tried creating custom Media class like: class ModuleScriptMedia(forms.widgets.Media): def __init__(self, *args, modules: Optional[Tuple[str, ...]] = None, **kwargs): super().__init__(*args, **kwargs) if not modules: modules = [] self._modules_lists = [modules] @property def _modules(self): … -
redirect() not passing arguments to view Django
I'm having trouble with redirect() in my Django views. I have two views defined as follows: # view for managing a user's account @login_required @require_http_methods(['GET']) def view_account(request, updated=False): context = { 'user': request.user, 'cart_items': ShoppingCartItem.objects.filter(user_key=request.user), 'updated': updated, } print("DEBUG: view_account: %s" % updated) # debug return render(request, 'registration/view_account.html', context) and # view for updating information about a user's account @login_required @require_http_methods(['GET', 'POST']) def update_account_info(request): if request.method == 'POST': # if this is a POST, user has submitted updated information form = UpdateUserInfoForm(request.POST, instance=request.user) if form.is_valid(): # if valid, redirect to view_account form.save() # return render(request, 'registration/view_account.html', context) return redirect('/view_account', updated=True) My url's for these functions look like so: path('view_account', views.view_account, name='view_account'), path('update_account', views.update_account_info, name='update_account'), In the second function, I'm trying to redirect the user to the view_account() view and pass in the updated=True argument to notify the user on the page that their information has been updated. For some reason when I run this, it does not seem to be changing the default value of updated. As you can see, I've got a debug statement in the view_account() view. Output is as follows: [04/Nov/2019 16:51:33] "POST /update_account HTTP/1.1" 302 0 DEBUG: view_account: False [04/Nov/2019 16:51:33] "GET /view_account HTTP/1.1" 200 1247 … -
Django error (1054, "Unknown column 'models_author.user' in 'field list'")
good In models.py I changed the name of the field "login" to "user" and added others. Even having executed: Python3 manage.py makemigrations models python3 manage.py sqlmigrate models 0001 python3 manage.py migrate I still get an error (1054, "Unknown column 'models_author.user' in 'field list'"). If I change the field back to "login" it works perfectly Versions Python 3.5.2 django.VERSION (2, 2, 6, "final", 0) the database is in MYSQL. Code:Models.py class Autor(models.Model): nombre = models.CharField(max_length=30) apellidos = models.CharField(max_length=50) usuario=models.CharField(max_length=50) class Post(models.Model): author = models.ForeignKey('auth.User', ) titulo = models.CharField(max_length=100) comentario = models.CharField(max_length=1000) Regards -
How to sanity check if public ssh key passed from html form is valid?
Im using django to create website and want sanity check ssh keys. The user enters a public ssh key in a html form to add it to his account for later use. Before saving the key I want to check if the public key is valid, i.e. the string passed has the correct form etc. to be a real ssh key. There are some similar questions I found like this: https://serverfault.com/questions/453296/how-do-i-validate-an-rsa-ssh-public-key-file-id-rsa-pub But they use ssh-keygen, which needs a saved file to read from. What would be a more elegant way to implement this in python? -
How to choose model fields to be displayed in the generic ListView
I would like to create a table using some of the model fields names. As you can see below, model has defined 8 fields but I just want to display on the table 3 of them. After you click on the contractor name in the table you will be forward to the detail view where you will see all the models fields. I don't want to hardcode the table column names. So how can I display only these 3 model fields in the table? views.py class ListView(generic.ListView): model = Contractor template_name = 'contractors/list.html' context_object_name = "all_contractors" fields = ['company_name', 'email', 'website'] models.py class Contractor(models.Model): company_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=50) email = models.EmailField() website = models.URLField() city = models.CharField(max_length=100) street = models.CharField(max_length=100) postal_code = models.CharField(max_length=50) notes = models.TextField() def __str__(self): return self.company_name -
Nginx not service static file in django project
In django project I used Js and Css files and this files not downloading. after installation to server nginx is not service django static files, but it service pictures. Web site is working but style and js files not service, why it happen which component not working? Nginx file: location /static/ { alias /var/www/project.com/project/static/; } location /media/ { alias /var/www/project.com/project/media/; } Setting.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static') ] MEDIA_URL = 'media/' MEDIAFILES_DIR = [os.path.join(BASE_DIR, 'media') ] Index.html file: <script type="text/javascript" src="{% static 'js/functions.js'%}"> </script> When I checked by browser console, it give me like this error: http://someurl/static/js/functions.js net::ERR_ABORTED 403 (Forbidden) -
Django server performance. More CPU on less instance or more instance with less CPU through load balancer?
I am deploying Django application and want to scale up a little bit on AWS. I am wondering given the same amount of CPU(let's say 100), whether two 50 CPU machines perform better than fifty 2 CPU machines? -
Format Django model data before serialization into DataTable
I have a model with two manytomany fields and a few list fields. I want to to serialize the data into JSON to present within a Jquery DataTable. Right now, I'm able to grab the data via an HTTP request- however, when I get the data into the table, it looks like so: Current data output My question is this: How do I either format my models or prepare the data for serialization in a way that will display values as plain strings to the user? I'd like the manytomany fields to display the names of the users, and the list fields to display as comma separated strings. The model being serialized: class Project(models.Model): meetingtypelist = [ ('Introduction', 'Introduction'), ('Follow-Up', 'Follow-Up'), ('Formal Pitch', 'Formal Pitch'), ] pursuitname = models.CharField(max_length=500) datecreated = models.DateTimeField(auto_now=True) bdmember = models.ManyToManyField('team.TeamMember') meetingtype = models.CharField(max_length=200, choices= meetingtypelist) sourcingbroker = models.ManyToManyField('team.Broker') sendsurvey1 = models.BooleanField(default=False) pursuitsize = models.IntegerField(max_length=20000, default=0) servicelines = models.CharField(max_length=200) techused = models.CharField(max_length=200) briefcard = models.BooleanField(default=False) class Meta: ordering = ['datecreated'] def natural_key(self): return self.my_natural_key def __str__(self): return self.pursuitname thank you! -
Django / Mypy: Incompatible type on for models
I'm working on a Django project and I'm using mypy for type checking. To enable type checking for django I'm using the django-stubs package. This works great, but I've now run into a situation where mypy is throwing two errors that I seem unable to solve: Item "None" of "Optional[Season]" has no attribute "league" Incompatible type for "league" of "Match" (got "Union[ForeignKey[Union[League, Combinable], League], Any]", expected "Union[League, Combinable, None]") These errors are raised for the code below. I'm initiating (but not creating / saving to the database) an instance of the Match model. match = Match( home_team=home_team, away_team=away_team, league=home_team.seasons.last().league, season=home_team.seasons.all().last(), ) The models involved are displayed below: class League(models.Model): name = models.CharField(max_length=200) class Season(models.Model): first_year = models.PositiveIntegerField() second_year = models.PositiveIntegerField() league = models.ForeignKey( League, related_name="seasons", on_delete=models.CASCADE ) class Team(models.Model): name = models.CharField(max_length=200) seasons = models.ManyToManyField(Season, related_name="teams") class Match(models.Model): league = models.ForeignKey( League, related_name="matches", on_delete=models.CASCADE ) season = models.ForeignKey( Season, related_name="matches", on_delete=models.CASCADE ) home_team = models.ForeignKey( Team, related_name="home_matches", on_delete=models.CASCADE ) away_team = models.ForeignKey( Team, related_name="away_matches", on_delete=models.CASCADE ) I understand the first error (Item "None" of "Optional[Season]" has no attribute "league") As Seasons refers to a ManyToMany field which can of course be None. I do not see what I'm doing wrong … -
How to let DjangoModelFactory create a model without saving it to the DB?
I'm writing unit tests in a Django project. I've got a factory to create objects using the .create() method. This always creates a record in the DB though. Is there a way that I can instantiate an object without saving it to the DB yet? I looked over the documentation but I can't find it. Am I missing something? -
Django inline-formset ordering issue when editing
I am trying to use the Django inline-formset. Forms should be displayed sorted by their order value which is correctly done when I request the form. But if I change the order values and save, the first view is with the previous order (refresh does the trick) forms: class SlidesForm(forms.ModelForm): order = forms.IntegerField(widget=forms.NumberInput()) background_image = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'}), required=False) text = forms.CharField(max_length=256, widget=forms.Textarea(attrs={'rows': 2, 'class': 'form-control'}), required=False) class Meta: model = SlideCarousel fields = ['order', 'background_image', 'text'] views: def management_form_general(request, city_slug): city = City.objects.get(slug=city_slug) SlideCarouselInlineFormSet = inlineformset_factory(City, SlideCarousel, form=SlidesForm, extra=0) if request.method == 'POST': carousel_formset = SlideCarouselInlineFormSet(request.POST, request.FILES, instance=city, queryset=city.slidecarousel_set.order_by("order")) if carousel_formset.is_valid(): carousel_formset.save() else: carousel_formset = SlideCarouselInlineFormSet(instance=city, queryset=city.slidecarousel_set.order_by("order")) return render(request, 'management/form/city_general.html', {'city': city, 'carousel_formset': carousel_formset}) Any idea what I am doing wrong ? Tried to reinstance the carousel_formset after the save but it seems nasty and it actually didn't work -
I have the below code I’m getting the error RelatedObjectDoesNotExist i
I have the below code I’m getting the error RelatedObjectDoesNotExistn Anyone can help me, please -
Change LDAP password encryption using django-python3-ldap
I am using django-python3-ldap v0.11.2 for LDAP authentication in Django. I successfully managed to connect to my ldap test server which I created with some dummy users. The migration using this command: python manage.py ldap_sync_users works fine and is refreshing my db. However, when I try to connect with one of the user, I am getting this error message: LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - INVALID_CREDENTIALS: Bind failed: Invalid authentication - bindResponse - None. I suspect this is because the stored password is incorrectly encrypted... This is because the following test works fine: Connect with a pre existing admin account Change the password for newly imported user jdoe to abc Log out The connection using user: jdoe and password abc now works perfectly fine! Have anyone faced this issue before ? Or knows how to change the password encryption used by the migrate command ? Or maybe I missed an important LDAP configuration... Python LDAP settings: # LDAP Connection Settings LDAP_AUTH_URL = "ldap://localhost:10389" LDAP_AUTH_USE_TLS = None LDAP_AUTH_SEARCH_BASE = "DC=example,DC=com" LDAP_AUTH_USER_FIELDS = { "username": "uid", "first_name": "givenName", "last_name": "sn", "email": "mail", "password": "userPassword" } LDAP_AUTH_OBJECT_CLASS = "organizationalPerson" LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" … -
How to create multiple reusable Mixins which each contain get_queryset methods?
I am trying to not repeat myself when writing views by separating some of my logic into Mixins which will be reused in different views.py files. The idea seems to be great but my implementation seems to be failing. This first method seems to call both Mixins but does not properly filter using the CasinoMixin. class CasinoMixin: def get_queryset(self): queryset = super(CasinoMixin, self).get_queryset() user_casino = self.request.user.casino user_emp_type = self.request.user.employee_type queryset = queryset.filter( casino=user_casino).filter( receiver=user_emp_type) print('CasinoMixin') return queryset class SearchMixin: def get_queryset(self): queryset = super(SearchMixin, self).get_queryset() query = self.request.GET.get('q') if query: return queryset.filter( Q(title__icontains=query) | Q(content__icontains=query)) print('SearchMixin') return queryset class MemoListView(LoginRequiredMixin, SearchMixin, CasinoMixin, ListView): """ Display a list of memos **Context** ``Memo`` An instance of :model:`memos.Memo` **Template:** :template:`memos/memos.html` """ model = Memo template_name = 'memos/memos.html' context_object_name = 'memos' def get_ordering(self): ordering = self.request.GET.get('ordering', '-date_time') return ordering def get_queryset(self): queryset = super(MemoListView, self).get_queryset() ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset I have also tried what somewhat else suggested which was: class SearchMixin: model = None def get_queryset(self): queryset = self.model.objects.all() query = self.request.GET.get('q') if query: return queryset.filter( Q(title__icontains=query) | Q(content__icontains=query)) return queryset The issue with that was that my code never got past … -
How to retrieve the data entered through a form (NOT through model form based on a model) in django
I'm familiar with creating forms based on Model forms, in that case i can use form.save() to save the data in database. The question is how do i save/retrieve the data of this form that i didn't create through a model form I've tried the following code but I'm not sure how to retrieve and save the data from NameForm. #forms.py file: from django import forms class NameForm(forms.Form): your_name = forms.CharField(label = 'your name', max_length = 100) # views.py file from django.shortcuts import render, redirect from .forms import NameForm def home(request): return render(request, 'meal_plans/home.html') def name(request): if request.method != 'POST': form = NameForm() else: form = NameForm(data=request.POST) if form.is_valid(): your_name = form.cleaned_data['your_name'] return redirect('meal_plans:home') return render(request, 'meal_plans/name.html', {'form': form}) # name.html template <form action="{% url 'meal_plans:home' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form -
How to properly reference a field from an external model in Django?
I'm fairly new to Python/Django. I'm making a form that has a few fields from my models. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp_number, which is just a regular ID#. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their Employee #/adp_number. What I was trying to achieve is that the form doesn't submit if the Employee #/adp_number is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee #/adp_number to the auto-generated ID in the database, not the adp_number in Salesman. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'adp_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('adp_number').remote_field, site), } fields = ('adp_number', … -
Datatables not showing django data on server side processing
{"draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [{"order_id": "56562", "date": "2019-11-03"}, {"order_id": "56614", "date": "2019-11-03"}, {"order_id": "56621", "date": "2019-11-03"}]} <script> // Call the dataTables jQuery plugin $(document).ready(function() { let searchParams = new URLSearchParams(window.location.search); var dict = {}; for (const [key, value] of searchParams) { //console.log(value); //console.log(key); dict[key] = value; console.log(dict); } $('#dataTable').DataTable( { "processing": true, "serverSide": true, "ajax": { "processing": true, "url": "/tasty/", "data":dict, "dataSrc": "" }, "columns": [ { "data": "order_id" }, { "data": "date" }, ], }); console.log(dict); }); </script> Datatables is not loading any JSON data in HTML view. But loading other pagination variables like total records. filtered records etc. So can anyone guide me why data tables are not loading and with even JSON response looks good -
Is there a way to separate django admin (superuser) from normal user?
In my Django Rest Framework api I have no human users which interact with my api, but I would like to use the User authentication on these machine users. However, the AbstractBaseUser still locks me in to much with the required email and username (which do not make sense for my machine users). Also, I would like to have human admins (superusers) but by customizing with AbstractBaseUser the superuser also changes. Can I separate the User for authentication from the superuser I want to use in the admin? I have already tried to use a OneToOne link with user in my machine user model as a profile but this still means I need to conform to django's user. Also, I have tried to use AbstractBaseUser but this creates the problems mentioned above. The model that should be my User model as this creates another resource (receipts) class ReceiptMachine(models.Model): machine_user = models.OneToOneField('ReceiptUser', on_delete=models.CASCADE) machine_id = models.UUIDField(verbose_name='id of receipt machine', default=uuid.uuid4, editable=False, unique=True) store = models.ForeignKey('Store', on_delete=models.CASCADE, to_field='store_id') class ReceiptUser(AbstractBaseUser): ? So I want to use this model as my Authentication via the Django user but I would also like to retain the normal admin superuser. -
Django render() in 2.X
I ran into this problem while trying to capture POST data. In Django 1.X, I structured my views like this: def view_name(request, template_name='template.html'): variable1 = data variable2 = moreData return render_to_response(template_name, locals(), context_instance=RequestContext(request)) Now, I see that render_to_response() has been deprecated, but I'm unsure how to port the code with all of the locals() calls. Do I have to convert all of my views by building a dict with all desired variables? Is there another way to port this to keep the locals() incorporation? Thanks! -
Usage of admin inline Error message no foreign key
Error Messages <class 'app.inlines.ContactInline'>: (admin.E202) 'delegator.Contact' has no ForeignKey to 'delegator.Organisation'. I intend to use the model Contact in Organisation and also in User(Member) and ended up with the error messages above. models.py: class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES) contact_detail = models.OneToOneField(Contact, null=True, on_delete=models.SET_NULL) class Organisation(TenantMixin): key = models.CharField(max_length=24, unique=True) type = models.CharField(max_length=3, choices=TYPE_CHOICES, default='LN') name = models.CharField(max_length=128) contact_detail = models.OneToOneField(Contact, null=True, on_delete=models.SET_NULL) ... admin.py @admin.register(Organisation) class OrganisationAdmin(admin.ModelAdmin): fields = ['key', 'type', 'name', 'domain_url', 'schema_name'] actions = ("export_as_csv",) inlines = [ContactInline] @admin.register(Member) class UserAdmin(admin.ModelAdmin): list_display = ('user', 'group', 'role') inlines = [ContactInline] This is not excactly what I expected. Is there onother possibility to rech this without creating two extra models for organisation contacts and user contacts and linking them with a foreign key relation? -
Django: combine related records
hope someone can help me with my little problem. I have a model which stores selled articles after a purchase confirmation: class Journal(models.Model): journal_id = models.CharField(max_length=256, blank=True, default="N/A") typ = models.CharField(max_length=100, blank=True, default="N/A") lead_id = models.CharField(max_length=256, blank=True, default="N/A") firmenname = models.CharField(max_length=256, blank=True, default="N/A") datum = models.DateField() artikeltyp = models.CharField(max_length=256, blank=True, default="N/A") netto = models.DecimalField(max_digits=19, decimal_places=2) brutto = models.DecimalField(max_digits=19, decimal_places=2) mwst = models.DecimalField(max_digits=19, decimal_places=2) each article is saved separately because i need to create an invoice with all articles of the same journal_id, But for the frontend i need to show all related records as one, combined under the journal_id with summarized net(netto), gross(brutto) and VAT(mwst). I use DataTables for the frontend with server side processing. I need to find a solid and performant way combined with my search query: def get_journal(request): # ? Setting up search values and buildung filter fields_and_expressions = { 'lead_id': '__istartswith', 'typ': '__icontains', 'firmenname': '__icontains', 'journal_id': '__istartswith', 'datum': '__icontains', 'netto': '__istartswith', 'brutto': '__istartswith', 'mwst': '__istartswith' } fields = list(fields_and_expressions.keys()) search_expressions = list(fields_and_expressions.values()) search_values = [] for i in range(len(fields)): value = request.GET.get('columns['+str(i)+'][search][value]') search_values.append(value) expr = (Q(**{fields[i] + search_expressions[i]: value}) for i, value in enumerate(search_values) if value is not '') search_terms = Q() try: search_terms = reduce(AND, … -
Query to get foreign key PK
i am trying to carry out a check on the user once he want to go to the next page. the code will do a check on the User and its related model to see if the user has created the data. if it is created he will be redirected to next page else he will redirected to the create page. the similer query function will then be used to assign the other models foreign keys when form is being processed. class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) @login_required def create_startupform(request) : q = User.objects.filter(Startup.startup_name.primary_key) if q.exists(): return redirect ( 'str_detailedview' ) else: form = startupform ( request.POST or None ) if form.is_valid ( ) : instance = form.save (commit = False) instance.author = request.user instance.save() return redirect ( 'str_detailedview' ) else: form = startupform() return render ( request , 'str_name.html' , { 'form' : form } ) -
Django Form in VueJS component
I'm currently starting a project in which I'm using Django for the backend, graphql (Graphene) for the API, VueJS for the frontend, and Vue Apollo to ease running graphql queries through VueJS. The thing is : I'm already able to do custom forms in Vue components and run the appropriate query to fetch/add/delete data. But I haven't been able to integrate Django Forms into a Vue component so far, I have no idea how to do it. I could be satisfied with custom forms, but I wan't to be able to use Django Forms since all the validation of forms is easy to do with Django. Any help would be appreciated. Thanks in advance, lbris.