Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between usage of Django celery and Django cron-jobs?
I am sorry if its basics but I did not find any answers on the Internet comparing these two technologies. How should I decide when to use which as both can be used to schedule and process periodic tasks. This is what an article says: Django-celery : Jobs are essential part of any application that does some processing for you in the background. If your job is real time Django application celery can be used. Django-cronjobs : django-cronjobs can be used to schedule periodic_task which is a valid job. django-cronjobs is a simple Django app that runs registered cron jobs via a management command. can anyone explain me the difference between when should I choose which one and Why? Also I need to know why celery is used when the computing is distributed and why not cron jobs -
Access files in production-mode of django project
For my Django project I have to open an xsl-file that is permanently located on the server to perform some actions on other files that the users can upload. In development mode I just used a relative path in the python script to point to that xsl-file and it worked fine: xslFile = open('./transform.xsl') However, as I am now in the stage of deploying the project to the server, I am having troubles with changing that line of code so that the file can still be found in production mode. I already tried setting an absolute path like xslFile = open('/srv/www/htdocs/djangoProject/mysite/transform.xsl') which threw errors. Furthermore I tried moving the file to the static directory which I state in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and tried then to open the file like this: from django.conf import settings xslFile = open(os.path.join(settings.STATIC_ROOT, 'transform.xsl')) However, both of these tries produce error messages of this kind: FileNotFoundError at /mysite/add/ [Errno 2] No such file or directory: 'transform.xsl' Request Method: POST Request URL: xx.xx.xx.xxx/mysite/add/ Django Version: 2.2.7 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'transform.xsl' Exception Location: /srv/www/htdocs/djangoProject/mysite/createDatabase.py in handleInputFiles, line 84 Python Executable: /usr/bin/python3 Python Version: … -
Can't add comment form in Django web application
I have a trouble adding form-group (I believe it's bootstrap class). The form-group doesn't do anything at all, or maybe it's a problem with form.author and form-body variables!? More simply, I need UI comment section (now only I can add and edit comments from django admin page). Some code: post_details.html <article class="media content-section"> <form action="/post/{{ post.slug }}/" method="post"> {% csrf_token %} <div class="form-group"> {{ form.author }} </div> <div class="form-group"> {{ form.body }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <ul> {% for comment in post.comments.all %} <p> <b>@{{ comment.author }}</b> <small>{{ comment.created_date }} </small> </p> <p> {{ comment.text }}</p> <hr> {% if comment.replies.all %} <ul> {% for reply in comment.replies.all %} <p>{{ reply.text }}</p> <hr> {% endfor %} </ul> {% endif %} {% endfor %} <ul> </article> forms.py from django import forms class CommentForm(forms.Form): author = forms.CharField( max_length=60, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Your Name"} ), ) body = forms.CharField( widget=forms.Textarea( attrs={"class": "form-control", "placeholder": "Leave a comment!"} ) ) views.py def comment(request): form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post, ) comment.save() context = {"post": post, "comments": comments, "form": form} if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( … -
Struggling to pass request.user.id to SQL function in python/django
hoping someone can help as I'm new django (and coding) and I'm stuck with trying to pass the current user's ID number to an SQL function. I've spent days searching for a solution but nothing I've tried has worked. I know the SQL function works as I can pass through a number without any issue, but when trying to use request.user it just comes up blank. views.py: def my_custom_sql(request): current_user = User.objects.get(request.user) with connection.cursor() as cursor: cursor.execute("SELECT first_name FROM customuser WHERE id = %s",[current_user]) row = cursor.fetchone() return row def dashboard(request): return render(request, 'dashboard.html', {'my_custom_sql': my_custom_sql}) models.py: class CustomUser(AbstractUser): pass # add additional fields in here employee_dob = models.DateField(blank=True, null=True) is_executive = models.IntegerField(blank=True, null=True) def __str__(self): return self.username dashboard.html: <a href="{% url 'home' %}">Home</a> <br> {% if user.is_authenticated %} <p>Is this the your first name?: {{my_custom_sql}}</p> {% else %} <p>You are not logged in, please do so.</p> {% endif %} I've read everything I can find around the issue but haven't found anything yet that has helped. I'm not sure if it has something to do with sessions or django hashing the info? But I'm not sure how to get around this safely. Anyone got any idea how to resolve … -
How to plug in a specific validator for all cases of a built-in type?
I recently noticed that some of my entries in a database coming from users contain incorrectly encoded strings, such as ó when ó was clearly meant. It's coming from copy-pasting of other websites that aren't properly encoded, which is beyond my control. I discovered that I can add this validator to catch such cases and raise an exception - here's an example with an attached model: from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError import ftfy def validate_ftfy(value): value_ftfy = ftfy.ftfy(value) if value_ftfy != value: raise ValidationError( _('Potential UTF-8 encoding error: %(value)r' ' decoded to %(value_ftfy)r.'), params={'value': value, 'value_ftfy': value_ftfy} ) class Message(models.Model): content = models.CharField(max_length=1000, validators=[validate_ftfy]) def save(self, *args, **kwargs): self.full_clean() return super(Message, self).save(*args, **kwargs) The problem is that now that I discovered it, I see no point skipping it in any of my instances of CharField, TextField and the like. Is there a way to plug in this validator to all data types, so that if anything non-binary has invalid UTF-8, I can count on it not making it to the database? -
How to transfer data from a callback to another view in Django?
I have a function that makes a request to Erlang. Next, the Erlang sends a response to the url callback. I need this data in the original function to verify the success of the operation. Accordingly, the original function must wait until an answer arrives. How do I transmit this data? def pay(request): try: body = request.body.decode('utf-8') if not body: raise ValidationError('empty query') body = json.loads(body) for field_name in ['phone', 'amount', 'merchant_name', 'payment_type', 'prefix', 'number']: check_field(body, field_name) except ValidationError as error: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': error.message }, }) except JSONDecodeError: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'not Json or incorrect Json' }, }) active_subs = MfsSubscription.objects.filter( phone=body.get('phone'), is_subscribe=True, ) if not active_subs.exists(): response = mfs_create_and_activate(body.get('phone')) logger.info('activate code = {}'.format(response['code'])) if response is None: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 500, 'message': 'Connection timeout', }, }) else: if response['code'] == 201 or response['code'] == 200: 'check data from callback function and next actions' @csrf_exempt def callbackpay(request): try: data = json.loads(request.body.decode("utf-8"))#here is the answer from Erlang logger.info('Callback with post data: {}'.format(data)) phone = data['details']['payment_source']['details']['msisdn'] handler = callback_factory(data['action']) response = JsonResponse({}, status=500) if handler: response = handler(phone, data) return JsonResponse({}, status=response.status_code) except ( KeyError, … -
Django Rest Framework: Set Permissions for function view
The default permissions requires token authentication. I have a function based view that has the api_view decorator. How can I explicitly set its permissions to not require authentication and csrf exempt? @api_view(['GET']) def activate(request, uidb64, token): .... -
Django get() returned more than one objects
I'm trying to add a song to the playlist model that I have but it keeps saying Direct assignment to the forward side of a many-to-many set is prohibited. Use songs.set() instead. My code for Playlist model: class Playlist(models.Model): image = models.ImageField() name = models.CharField(max_length=100) artist = models.ForeignKey(User, on_delete=models.CASCADE) fav = models.BooleanField(default=False) songs = models.ManyToManyField(Music) slug = models.SlugField(editable=False, default=name) def __str__(self): return self.name def get_absolute_url(self): return reverse('playlist-detail', kwargs={'pk': self.pk}) @classmethod def add_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.add(new_song) @classmethod def remove_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.remove(new_song) My code for Song model: class Music(models.Model): image = models.ImageField() name = models.CharField(max_length=100) song = models.FileField(upload_to='musics/', blank=False, null=False) artist = models.ForeignKey(User, on_delete=models.CASCADE) fav = models.BooleanField(default=False) slug = models.SlugField(editable=False, default=name) lyrics = models.TextField(default="Unknown lyrics") genre = models.CharField( max_length=2, choices=GENRE, null=False, blank=False, default="" ) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) my view method that adds the song to the playlist object def add_to_playlist(request, operation, pk): new_song = Music.objects.get(pk=pk) if operation == 'add': Playlist.add_music(new_song) elif operation == 'remove': Playlist.remove_music(new_song) return redirect('/') Html code: {% for i in music %} {% for v in playlist %} <a class="dropdown-item" href="{% url 'add_to_playlist' operation='add' pk=i.pk %}">Add to{{v.name}}</a> {% endfor %} {% endfor %} -
MAYAN-EDMS reviews and capabilities
I am currently working on a project to convert my organization away from manual file systems. We have a fairly narrow set of requirements for a document management system, and it appears that something open source like Mayan may be suitable for our needs. What I've not been able to discern from the documentation / website is whether the software system is capable of dealing with large numbers of documents and clients on a network. Our document count is in the neighborhood of 100 billions documents, and we have a dedicated scanning department (approx 1000 users) and a client-consumer base of about 6000 users. Some initial questions: Whether the Mayan is capable of dealing with large (100 Bn) numbers of documents. Will Mayan work at an enterprise level with the user and document base I've described? Can Mayan use MS SQL, or is it PostegreSQL / MySQL only? What would a file/data migration to Mayan look like? Is there any articles / documents that could help me jump into the code base? I've been doing quite a bit of Python work lately, and would be very interested in seeing how your system works under-the-hood. Please suggest any other open source … -
Error while executing 'pip install virtualenv p1'. It installed virtualenv perfectly but It generated error while collecting p1
When i executed the above said command in command prompt it generate the following error: Requirement already satisfied: virtualenv in c:\users\user\appdata\local\programs\python\python37\lib\site-packages (16.7.8) Collecting p1 Using cached https://files.pythonhosted.org/packages/24/16/a5c2ade5472a8fca3d8ef5cee2214fd49ef827269e85e1c39b7bd6fba56a/p1-1.0.1.tar.gz Collecting rpi.gpio>=0.5.5 Using cached https://files.pythonhosted.org/packages/cb/88/d3817eb11fc77a8d9a63abeab8fe303266b1e3b85e2952238f0da43fed4e/RPi.GPIO-0.7.0.tar.gz Installing collected packages: rpi.gpio, p1 Running setup.py install for rpi.gpio ... error ERROR: Command errored out with exit status 1: command: 'c:\users\user\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-rb458cr0\\rpi.gpio\\setup.py'"'"'; __file__='"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-rb458cr0\\rpi.gpio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\USER\AppData\Local\Temp\pip-record-blgtvdr9\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\USER\AppData\Local\Temp\pip-install-rb458cr0\rpi.gpio\ Complete output (32 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\RPi copying RPi\__init__.py -> build\lib.win-amd64-3.7\RPi creating build\lib.win-amd64-3.7\RPi\GPIO copying RPi\GPIO\__init__.py -> build\lib.win-amd64-3.7\RPi\GPIO running build_ext building 'RPi._GPIO' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\user\appdata\local\programs\python\python37\include -Ic:\users\user\appdata\local\programs\python\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcsource/py_gpio.c /Fobuild\temp.win-amd64-3.7\Release\source/py_gpio.obj py_gpio.c source/py_gpio.c(87): error C2143: syntax error: missing ';' before '{' source/py_gpio.c(115): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data source/py_gpio.c(119): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data source/py_gpio.c(200): error C2143: syntax error: missing … -
How to get all subscription end date, so that I can send email to customer using stripe and python?
I created web hook http://example.com/api/webhook/ NOw I want to trigger this url, to get all the subscribed id, which end date is coming, or expired subscribed id Is there any code or demo to obtain it?? -
How to add minutes to datetime in postgres via django
TL;DR: I want to add minutes to a datetime in postgres and can think of two ways to do it. Consider the following django model: from django.db import models class AppointmentManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( end=models.ExpressionWrapper( models.F('start') + models.F('duration'), output_field=models.DateTimeField(), ) ) class Appointment(models.Model): start = models.DateTimeField() duration = models.DurationField() objects = AppointmentManager() Note that end is computed dynamically in the database by adding start and duration. This does exactly what I want. However, I want the UI for the duration to be a number input that gives the duration in minutes. My current approach is to use the following form field: import datetime from django import forms class MinutesField(forms.DurationField): widget = forms.NumberInput def prepare_value(self, value): if isinstance(value, datetime.timedelta): return int(value.total_seconds() / 60) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value if isinstance(value, str): value = int(value, 10) return datetime.timedelta(seconds=value * 60) This looks a little brittle to me. Is it also possible to store the duration as integer and transform it to a duration dynamically? -
Core compute for solid returned an output multiple times
I am very new to Dagster and I can't find answer to my question in the docs. I have 2 solids: one thats yielding tuples(str, str) that are parsed from XML file, he other one just consumes tuples and stores objects in DB with according fields set. However I am running into an error Core compute for solid returned an output multiple times. I am pretty sure I made fundamental mistake in my design. Could someone explain to me how to design this pipeline in the right way or point me to the chapter in the docs that explains this error? @solid(output_defs=[OutputDefinition(Tuple, 'classification_data')]) def extract_classification_from_file(context, xml_path: String) -> Tuple: context.log.info(f"start") root = ET.parse(xml_path).getroot() for code_node in root.findall('definition-item'): context.log.info(f"{code_node.find('classification-symbol').text} {code_node.find('definition-title').text}") yield Output((code_node.find('classification-symbol').text, code_node.find('definition-title').text), 'classification_data') @solid() def load_classification(context, classification_data): cls = CPCClassification.objects.create(code=classification_data[0], description=classification_data[1]).save() @pipeline def define_classification_pipeline(): load_classification(extract_classification_from_file()) -
Django - Take PK of loged user as default value to another model
I'm new to development and I'm trying to do a django / python project. I have the model "Account" below: email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) data_inscricao = models.DateTimeField(verbose_name='Data de Inscrição', auto_now_add=True) ultimo_login = models.DateTimeField(verbose_name='ùltimo Login', auto_now_add=True) def __str__(self): return self.username and this other "PersonalData"... id_user = models.OneToOneField(Account, on_delete=models.CASCADE) nome_completo = models.CharField(max_length=56, unique=True, null=True) email = models.EmailField(max_length=60, verbose_name="Email", unique=True, null=True) cpf = models.CharField(max_length=14, unique=True, null=True, verbose_name="CPF") rg = models.CharField(max_length=12, unique=True, null=True, verbose_name="RG") idade = models.IntegerField(null=True) data_nascimento = models.DateField(verbose_name="Data de Nascimento", null=True) genero = models.CharField(max_length=8, choices=GENERO, null=True) estado_civil = models.CharField(max_length=13, null=True, choices=ESTADO_CIVIL, verbose_name="Estado Civil") def __str__(self): return self.nome_completo I'ld like PersonalData.id_user use by default the Account.username of the loged user and I don't know how do that. In Django Admin, my PersonalData model allows me to choose the user, but I want it to happen automatically and not manually. enter image description here Can someone help me? -
Deploy Django in subdomains
I want to deploy a django app into an existing webenvironment, with other sites already existing. Therefore i received a domain from the webadmin like this: www.websites.com/theapp Now, in my local development environment the path /theapp does not exist. I tried to add this path to the urls, what really doesn't work. As i am fairly new to Django i would appreciate any assistance on how to handle this leading path, so Django could handle the incoming url correctly. -
Django - Existing DB Views and Foreign Keys
I have a simple view on the DB which select info from other DB's located on the same MSSQL Server to ultimately serve the info as a dropdown to the user. So far I've added the Model with inspectdb: class AutPricePlanView(models.Model): priceplan_name = models.CharField(db_column='PricePlan', max_length=50, blank=True, unique=True) class Meta: managed = False # Created from a view. Don't remove. db_table = 'AUT_PricePlanView' Also I have a second existing (Django Native) Model where I want to use the values from the view for a Dropdown Field (to keep everything in sync): class PricePlanDownload(models.Model): requesting_user = models.CharField(blank=True, default=None, max_length=50, null=True) requested_at = models.DateTimeField(auto_now_add=True) document = models.FileField(upload_to='documents/price_plan_uploads/%Y/%m/%d', blank=True) priceplan = models.ForeignKey(AutPricePlanView, null=True, on_delete=models.DO_NOTHING)``` Makemigrations works fine but when I try to actually migrate I get the following issue: (shortened it a little bit) *django.db.utils.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Foreign key references object 'AUT_PricePlanView' which is not a user table. (1768) (SQLExecDirectW)")* I would be really grateful if someone had an idea or a workaround since I can't figure out what the heck this has to do with a "user" table... -
Django admin widget override for all of abstract model
I have an abstract model that contains a field type that I would like to override the widget for in the admin view. Now you can't register abstract models in the admin view so I have had to override the widget for each of the models that inherit from the abstract model. This feels clunky - is there a neater way to do this? -
Time-Based Indexing in Elasticsearch in python? like daily logs date suffix index
i am developing a 3rd party tool which is fetching report data from apis, i am indexing this in elastic search using django_elasticsearch_dsl But every time i index the fetched data it overrides the previous one. one approach was mentioned in the documentation help i.e We can store index fer day with date as suffix in index name. For example: index_name = report-yyyymmdd-hhmmss How to do this in python using django_elasticsearch_dsl? What is the best practice to do this? Here is my code: class ReportDocument(Document): def prepare_labels(self, instance): if instance.labels == '--': return '' return list(map(str.strip, eval(instance.labels))) class Index: name = "report1" settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Report fields = [ field.name for field in Report._meta.get_fields()] auto_refresh = False -
Can't serialize request.data with another function inside post method.using Post request. DRF
I'm pretty new to Django and DRF. I have a Model with Image and ForeignKey fields. class Image(models.Model): image = models.ImageField(blank=False, null=False) predicted_result = models.ForeignKey(PredictedIllness, on_delete=models.CASCADE) Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields =['image','predicted_result'] And a view: class UploadImage(APIView): def post(self, request, format=None): serializer = ImageSerializer(data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response('Classified', status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def classify_image(self, image_file, image): image = open_image(image) pred_class, pred_idx, outputs = fastAi_learner.predict(image) print(pred_class.data.item()) return pred_class.data.item() So when I'm shooting with the POST request, everything works fine and Response: 'Classified' withStatus 201 is returned. But, what I want to do is to classify image myself, using classify_image function. def post(self, request, format=None): try: im = pilImage.open(request.data['image']) if im.load(): predicted_condition = self.classify_image(image_file=request.data['image'].name, image=request.data['image']) request.data['predicted_result'] = predicted_condition serializer = ImageSerializer(data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(1, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except IOError: return Response('problems with image', status=status.HTTP_400_BAD_REQUEST) For Some reason, When I'm shooting from Postman with exactly the same request I receive the following 400 Response: { "image": [ "Upload a valid image. The file you uploaded was either not an image or a corrupted image." ] } What can cause this error is thrown? Because I send exactly the same image. And how can … -
email field in Django only for corporate emails
Guys Is it possible in sign up form to limit email input only to corporate emails such as @bp.com @kpmg.com etc so to eliminate non-business emails such as gmail.com yahoo.com etc? So that if user insert xxx@gmail.com the form rejects and ask to insert business emails? I saw such option when i applied for master and they required for recomendation to insert business emails. I hope you got what i mean. What source you would advise to look for or what example of code you can share? If you can sharwe any would be great to have some idea. My forms.py is from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' Any help would be appreciated. -
why the time in Django rest framework is not correct
why when I updated an entry in the database the updated time field in the model updated = models.DateTimeField(auto_now=True) is updated correctly according to timezone in my settings file but when it appeared in the Django rest Framework terminal it is shifting back 3 hours the following code is for DRF: last_update = serializers.SerializerMethodField() class Meta: model = hashtag fields = [ 'id', 'tag', 'date_display', 'last_update', 'timestamp', 'updated' ] def get_last_update(self,obj): return obj.updated.strftime('%b %d %I:%M %p') -
Return a queryset of all jobs that a logged in user applied for
I am building a job portal where users can apply for any job listed on the system. Assuming a user is logged in, and has applied for different job positions, I want to be able to return all the jobs he has applied for and pass it to my template. I have two models: Job and Applicants Models.py class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) location = models.CharField(choices=country_state, max_length=20) description = RichTextUploadingField() requirement = RichTextUploadingField() years_of_experience = models.IntegerField(blank=True, null=True) type = models.CharField(choices=JOB_TYPE, max_length=10) last_date = models.DateTimeField() created_at = models.DateTimeField(default=timezone.now) date = models.DateTimeField(default=timezone.now) filled = models.BooleanField(default=False) def __str__(self): return self.title class Applicants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) cv = models.FileField(upload_to=user_directory_path) degree = models.CharField(choices=DEGREE_TYPE, blank=True, max_length=10) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.get_full_name()} Applied' In my views.py I tried getting the logged in user with request.user and filter the Applicants model with the request.user. Then I filtered jobs in the applicant job list. Views.py class AppliedJobs(ListView): model = Applicants template_name = 'my_job_list.html' context_object_name = 'jobs' ordering = ['-date'] @method_decorator(login_required(login_url=reverse_lazy('login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def get_queryset(self): user = self.request.user my_job_list = Applicants.objects.filter(user=user).values_list('job', flat=True) return Applicants.objects.filter(job__in=my_job_list) I don't know … -
MAYAN-EDMS REST API: Documents are not getting checked in
Overview I'm try to maintain document versioning in MAYAN EDMS using REST API. If one user open and updating document then document will be checked out and on completion of changes user will check in document with new version which will be available for other users. Problem Documents are not getting checked in using REST API. It responds with status code 500 Error: Internal Server Error, without any exception etc. Swagger API Call Error Message -
Use seperate url for separate apps django
How can i use different domains for different apps. If user enters foo.com then it should open landing page of foo app and if he enters bar.com then it should open landing page of bar app. Please share the example -
how to group all records with multiple matching fields
this is my model and i'm using postgresql: class TripRequest(models.Model): ... passenger = models.ForeignKey('user.Passenger', on_delete=models.DO_NOTHING) beginning_point = models.PointField() beginning_locality = models.CharField(max_length=50, null=True) destination_point = models.PointField() destination_locality = models.CharField(max_length=50, null=True) ... how can i group all records that have matching beginning_locality and matching destination_locality?