Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating A Profile Model Object in Django
I've searched and searched to try to figure out my issue or what I need to do here. I'm new to Django and havn't quite gotten the hang of allowing a user to change a model Object of a database through a form. What my code is doing is creating a default 'Profile' database whenever the user signs up with the following code: Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) state = models.CharField(max_length= 20, choices=STATE_CHOICES,default='N/A',) city = models.CharField(max_length=30,null=True, blank=True) birth_date = models.DateField(null=True, blank=True) Primary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000') Secondary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() This generates an empty table in my database that I would like the user to then be able to edit through a form. However, I would only like for the user to be able to edit the state and city fields along with some of the user fields, not the username. forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('state','city') views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = SignUpForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, _('Your profile was successfully … -
How to display the data of an Inline in a (ListView) that is in a class based on function? Django
I have an inLine in my create function which works very well, but to which I now want that inLine to pass it to my view based on class ArancelListView (ListView), the inline has code and description, that fields I want to pass to my listView, If someone has an idea of how to follow this, it would be of great help to me. Thank you. def ArancelCreateUpdate(request, pk=None): if pk: arancel = Arancel.objects.get(pk=pk) title_meta = u'Arancel: Actualización' title = u'Arancel' nav = ( ('Panel Mando', '/'), ('Arancel', reverse('arancel_list')), ('Actualización', '') ) else: arancel = Arancel() title_meta = u'Arancel: Registro' title = u'Arancel' nav = ( ('Panel Mando', '/'), ('Arancel', reverse('arancel_list')), ('Registro', '') ) # formset ArancelTipoIMDGFormset = inlineformset_factory(Arancel, ArancelTipoIMDG, extra=0, can_delete=True, fields=('arancel', 'tipo_imdg'), min_num=0, validate_min=True) if request.method == 'POST': next = request.GET.get('next') form = ArancelForm(request.POST, instance=arancel) arancelTipoIMDGFormset = ArancelTipoIMDGFormset(request.POST, instance=arancel) if form.is_valid() and arancelTipoIMDGFormset.is_valid(): resultado = ArancelTipoIMDG.validar_formset(arancelTipoIMDGFormset) if resultado['estado'] == 'OK': arancel = form.save() arancelTipoIMDGFormset.save() if next == 'new': return redirect(reverse('arancel_create')) if next == 'self': return redirect(arancel.get_update_arancel_url()) else: return redirect('arancel_list') else: errores = resultado['msg'] return render('administrador/arancel/arancel_form.html', locals(), context_instance=ctx(request)) else: form = ArancelForm(instance=arancel) arancelTipoIMDGFormset = ArancelTipoIMDGFormset(instance=arancel) return render('administrador/arancel/arancel_form.html', locals(), context_instance=ctx(request)) HTML: <form id="form" action="#" method="post" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} … -
How to Add Attribute to Django QuerySet That Will Get Serialized?
I have two Django 1.8 models that represent lists and items in lists. I also have a view that uses the Django REST framework to act as a REST endpoint and a template containing an jQuery Ajax block that calls this endpoint. This view gets all the lists owned by a particular user and looks to see if a given item is in any of the lists. Whenever it finds such an item, it should add an 'in_list' attribute to the data being passed back to the template. The problem I'm having is that while I can add this extra 'in_list' attribute to the list, it doesn't get picked up by the serializer and added to the serialized data. Here's the code: # views.py def get_viewer_lists_checked(request, *args, **kwargs): user = User.objects.get(id=kwargs['viewer_id']) lists = List.objects.filter(user=user, type=type) item = Item.objects.get(value=kwargs['viewed_id']) if item: for list in lists: if List.contains_item(item, list): list.in_list = True else: list.in_list = False serializer = MemberListsSerializer(lists, many=True) return JSONResponse(serializer.data) # models.py class List(models.Model): user = models.ForeignKey(User) name = models.CharField(_('list'), max_length=128) @classmethod def contains_item(cls, item, list, *args, **kwargs): try: item.lists.get(id=list.id) return True except List.DoesNotExist: return False class Item(models.Model): lists = models.ManyToManyField(List, related_name='items') value = models.IntegerField(_('value')) # serializer.py class MemberListsSerializer(serializers.ModelSerializer): class … -
Getting Max count based on Vehid group by Houseid Django
I am trying to get the Max count of a Vehid together with the housid. So, the problem is something like Houseid Vehid 1 1 1 1 1 2 1 2 1 2 2 1 2 1 2 2 2 3 3 1 3 2 4 1 4 2 4 3 4 3 And the output should be the max occurrence of a vehid used by a houseid. Like in this case. Housed Vehid 1 2 2 1 3 1 3 2 4 3 So, I wrote a Django query ModelClassName.objects.values('houseid','vehid').annotate(Count('vehid')).order_by('houseid') This is giving me the count of each vehid but as I am not sure how to incorporate Max here, I am unable to get the right result. Any help is appreciable. Thanks. -
How to perform SELECT FOR UPDATE with SKIP LOCKED on MySQL with Django
I have a Django project which uses a MySQL v5.5 backend with InnoDB storage. To avoid race condition updates in DB, I'm using select_for_update to lock the rows. Now if this lock stays for a long time, any queries on the locked rows will timeout. I want to avoid this with one of the following options: Skip the rows which are locked, similar to SKIP LOCKED option. Return immediately if some rows you're querying are locked, similar to NOWAIT option. Reduce the lock wait timeout period for specific queries. How do I perform any of these with Django ORM. -
How to compare less than or equals with only date of field having timestamp with timezone field
i am using default auth_user table with field date_joined as type as timestamp with time zone. All i want to check use the lte and gte comparison on only its date not with the time and zone. def get_fm_objects(self, filters): fm = FacilityManager.objects.all().order_by('-id') if filters['from_date']: fm = fm.filter(user__date_joined__gte=filters['from_date']) if filters['to_date']: fm = fm.filter(user__date_joined__lte=filters['to_date']) return fm here FacilityManager is another model and filters['from_date'] and filters['to_date'] are my input dates(it only contains date. eg:2018-1-10). i have a row in auth_user table with date_joined as 2018-01-11 00:56:39.735756+05:30 but when i give From and To date as 2018-01-11 it returns nothing. looking for answers. Thanks in advance. -
JSON API and django database
Hello I'm new with Django I'm traying to create my first application with django using a Json API to get that from the net I wanna to know how to save this data to my database I got the data in a forms.py like that: from django import forms import requests from .models import Series API_KEY = 'af237ff4830b5773f3d23f396e6f8616' class SeriesAPI(forms.Form): serie = forms.CharField(label='Search for Serie', max_length=100) def search(self): result = {} serie = self.cleaned_data['serie'] endpoint = 'https://api.themoviedb.org/3/search/tv?api_key={api_key}&query={serie_name}' url = endpoint.format( api_key = API_KEY, serie_name = serie ) response = requests.get(url) if response.status_code == 200: result = response.json() if result['total_results'] >= 1: id = result['results'][0]['id'] else: return None return id def get_serie(self): result = {} endpoint = 'https://api.themoviedb.org/3/tv/{id}?language=en-US&api_key={api_key}' url = endpoint.format( id = self.search(), api_key = API_KEY ) response = requests.get(url) if response.status_code == 200: result = response.json() return result right now everything's good I got the data and I showed it; I create a new form with only submit input to store the data but I can't do it this is my views.py: def index(request): search_result = {} form = SeriesAPI(request.POST or None) if 'serie' in request.POST: if form.is_valid(): search_result = form.get_serie() else: form = SeriesAPI() return render(request, 'series/serie.html', {'form': … -
Getting first few links from custom google search
i'm very new to web development . I'm using the custom google search engine for my webapp . I don't know if there is a way or api to get , say first 10 links from custom google search . -
Django-rest-auth + Allauth Twitter. Error 89. Invalid or expired token
I'm using Django with Allauth + REST-Auth for SPA social Login and successfully set up Facebook, VK and Google authorization but faced a problem while adding Twitter. It ends up with {"code":89,"message":"Invalid or expired token."} Looks like i'm missing something 'cos standard login with Twitter works as it should Here are my tries: First of all, i've set Twitter login endpoint as described in doc: class TwitterLogin(SocialLoginView): serializer_class = TwitterLoginSerializer adapter_class = CustomTwitterOAuthAdapter It features post method, expecting access_token and token_secret So redirect view was created to receive redirect from twitter, complete login and set token to browser localStorage via template render: class TwitterReceiveView(APIView): def get(self, request, *args, **kwargs): access_token = request.query_params.get('oauth_token') token_secret = request.query_params.get('oauth_verifier') params = {'access_token': access_token, 'token_secret': token_secret} try: s = requests.Session() result = s.post(settings.DOMAIN + reverse('tw_login'), data=params).text result = json.loads(result) except (requests.HTTPError, json.decoder.JSONDecodeError): result = {} access_token = result.get('access_token') context = {'access_token': access_token} return render(request, 'account/local_storage_setter.html', context, content_type='text/html') Have to mention that I tried two methods to start process(get initial token) 1. Used standard allauth url http://0.0.0.0:8080/accounts/twitter/login 2. Created another view (using lib python oauth2) which could be used from SPA: class TwitterGetToken(APIView): def get(self, request, *args, **kwargs): request_token_url = 'https://api.twitter.com/oauth/request_token' authorize_url = 'https://api.twitter.com/oauth/authorize' app = … -
Django: output textfile to be proceeded
i have a small django application that i use to manage my patients data ( i am a doctor with an intermediate level in python/django) I used LaTeX to output my reports via a view function like that def consultation_pdf(request, pk2, pk1): entry = Consultation.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) # context = Context({ 'consultation': entry, 'patient': source }) context = dict({'consultation': entry, 'patient': source}) template = get_template('clinic/consultation.tex') rendered_tpl = template.render(context, request).encode('utf-8') # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r Now i need to switch to ConTeXT since it fills more my needs. The biggest problem so far is that ConTeXT needs both the source file and the pdf to be saved on the disk, and not simply piping stdin and stdout , respectively. How could i manage to complete this task? so far the only workaround i've found is to generate a tex file … -
When to use NullBooleanField in Django
I have a button that, when clicked, should save in the database that the user has drunk water. I just wanted to check whether NullBooleanField would be the correct way to define this. A broader question that if answered would be useful to the community is a list of optimal circumstances under which to use NullBooleanField. But I'm not asking that here. Just in case you wanted a better challenge. Thank you in advance. -
Django add user to 'team'
I want the logged in user to be able to add users to a team they have created. At the moment I have created a form which lets the user select the user and the team they want to add them to, but they can select from every team in the database rather than just those they have created. Any ideas? These are my models, view and the form i have created. Also help with what to put in my HTML file would be appreciated. Models: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) class Team(models.Model): name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) View: def invite(request): if request.method == 'POST': form = InvitePlayerForm(request.POST) if form.is_valid(): userteam = form.save(commit=False) userteam.save() else: form = InvitePlayerForm() query = UserTeams.objects.all() return render(request, 'teammanager/invite.html', { "invite": query, "form": form }) Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = UserTeams fields = ['userID','teamID'] -
Django serialization validation optimization for bulk create
I am trying to write an api to process large number of rows of data using bulk_create on zipped csv records. but when serializer.is_valid() is called to validate the data before calling serializer.save(), it takes a long time to validate due to the foreign key constraint for device_id(sensorReading_device). I've tried prefetch_related() & select_related() and nested serializer and the performance is similar or worse as i suspect the modelserializer is committing the n+1 DB roundtripping problem for validation due to the foreign key. The only method which worked is to remove the foreign key in my model and implement as charfield and it became blazingly fast but it means there will be no more foreign key constraint. Is the removal of foreign key the way forward or am I missing something? heres my code and any advice is greatly appreciated! serializer.py class SensorReadingListSerializer(serializers.ListSerializer): def create(self, validated_data): sensor_readings = [SensorReading(**item) for item in validated_data] return SensorReading.objects.bulk_create(sensor_readings) class SensorReadingSerializer(serializers.ModelSerializer) device_qs = Device.objects.all() sensorReading_device = PrimaryKeyRelatedField(label='SensorReading device', many=True, queryset=device_qs) class Meta: model = ReadingsModel.SensorReading fields = ('id', 'device_timestamp', 'server_timestamp', 'payload', 'sensorReading_device') list_serializer_class = SensorReadingListSerializer model.py class Device(models.Model): device_id = models.CharField(primary_key=True, max_length=120) device_deviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE) device_softwareVersion = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) class SensorReading(models.Model): device_timestamp = models.DateTimeField(default=datetime.today) … -
Upgraded Django(1.11) & Django-cms(3.5.0) - pages no longer appearing
So I've successfully upgraded a django site (django 1.4 - 1.11. Python 2.5 - 3.5. Django-CMS 2.4 - 3.5) I started with a fresh database, made the migrations, migrated and everything went fine. No conflicts, no issues. Yes I'm doing it all locally for now. My internet is horrific so I'd rather do it locally, get it working then deploy it. Now I come to the site, enter the admin, everything is there except one particular plugin (snippets) and there are no pages. At all. Everything else is fine though and when I go to publish an empty page, I get the following error: Exception Type: IntegrityError at /en/cms_wizard/create/ Exception Value: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`eo_web_live`.`cms_page`, CONSTRAINT `site_id_refs_id_5f61f09c` FOREIGN KEY (`site_id`) REFERENCES `django_site` (`id`))') Here is the full traceback with settings: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/en/cms_wizard/create/ Django Version: 1.11.10 Python Version: 3.6.3 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_comments', 'djangocms_admin_style', 'django.contrib.admin', 'djangocms_text_ckeditor', 'cms', 'mptt', 'menus', 'treebeard', 'filer', 'easy_thumbnails', 'sekizai', 'reversion', 'gunicorn', 'compressor', 'form_designer', 'store_locator', 'cms_redirects', 'eo_registration', 'eo_jobs', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_link', 'cmsplugin_filer_image', 'cmsplugin_filer_teaser', 'cmsplugin_filer_video', 'eo_cms', 'eo_cms.plugins.feature_block', 'eo_cms.plugins.teaser_block', 'eo_cms.plugins.profile_block', 'eo_cms.plugins.accordion_block', 'eo_cms.plugins.tabbed_block', … -
Expanding a div when a Django error pops up
So I was currently coding on my password reset form page. I have a div of a specific height. Problem is, that when passwords don't match or they are too short, of course the form will display a message. I chose to show all the errors at the bottom of my form. Problem is, I can't figure to find a way, that when I have an error, the div would expand its height to fit the errors. Any solutions ? //scss #confirm { @include center; @extend #login; width: 30em; height: 70%; #pass-confirm { text-align: center; margin-top: -10%; margin-bottom: 10%; } #std-reg4 { text-decoration: none; color: $color1; margin-left: 43%; margin-top: -8%; font-family: $font2; position: fixed; &:hover { color: $color2; } .fa-times { font-size: 20px !important; } } .password1, .password2 { border-radius: 10px; box-shadow: none; width: 250px; height: 35px; border: 1.5px solid $color1; padding-left: 10px; background-color: white; } .confirm { text-align: center; margin-top: 20%; } .btn-default { @include button; margin-top: 0; } .alert-div { position: absolute; margin-top: 20%; left: 50%; .alert { width: 340px; font-size: 0.8em; background-color: transparent !important; border: none; color: #d01116; transform: translate(-50%, -50%); padding: 0; } } } <div id="confirm"> <form class="confirm" method="post"> {% csrf_token %} <a id="std-reg4" href="{% … -
I have some errors in python of django
OperationalError at /admin/firstapp/aritcle/ no such table: firstapp_aritcle Request Method: GET Request URL: http://127.0.0.1:8000/admin/firstapp/aritcle/ Django Version: 2.0.2 Exception Type: OperationalError Exception Value: no such table: firstapp_aritcle Exception Location: C:\Users\GodLike\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Users\GodLike\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\Users\GodLike\Desktop\project\HelloWorld', 'C:\Users\GodLike\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\GodLike\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\GodLike\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\GodLike\AppData\Local\Programs\Python\Python36', 'C:\Users\GodLike\AppData\Roaming\Python\Python36\site-packages', 'C:\Users\GodLike\AppData\Local\Programs\Python\Python36\lib\site-packages'] Server time: Fri, 9 Mar 2018 15:55:50 +0000 -
Generate a pdf file after success signal recieved from django-paypal
I'm working on a Django(1.10) project in which I have implemented Paypal payment method. I need to send a pdf file to the user when he completes the payment to our PayPal account. I'm receiving the payment completed signals from PayPal but now I don't know how I can send the pdf file to the user in a new tab. Here's what I have tried: **from signals.py: ** def show_me_the_money(sender, **kwargs): ipn_obj = sender custom = ipn_obj.custom # Undertake some action depending upon `ipn_obj`. if ipn_obj.payment_status == ST_PP_COMPLETED: print('Get success signal') user_info = ast.literal_eval(ipn_obj.custom) if int(user_info['taggedArticles']) > 11: # here i need to generate and send a pdf file to the user in a new tab pass else: print('Get fail signal') I have another view and URL to generate a pdf file, but can I send a post request to that URL and open it in a new tab? Help me, please! Thanks in advance! -
Django Bootstrap input-group-addon on Model Form without separating fields
I'm currently rendering my Django form in the following way: <form action="/student/" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Launch" class="btn btn-primary"/> </form> I have multiple fields of different types, with different things applied to each field, such as validators and help-text. I have two fields that I would like to add bootstrap spans to. One money field which I'd like to prepend a pound symbol to, and one percentage field which I'd like to append a percentage symbol to, I know that this is possible to do using bootstrap as follows: This input field. <div class="input-group"> <span class="input-group-addon">$</span> <input type="text" class="form-control" placeholder="Price"/> </div> But to do this in my django template would require me to break up the form into specific fields and create field specific html. Such as the solution to This question proposes. What I'm looking for is a way to specify either in the model, or the modelform, an attribute or class which will only apply to a specific field, but will render it as above without breaking up the form. Thank you. Info: Bootstrap-4 Django-2.0.2 Python-3.6.1 -
Django 2.0.3 upgrade 'WSGIRequest' object has no attribute 'user'
Upgrading from 1.11 The actual error displayed with DEBUG on: AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.3 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: /home/tim/anaconda3/envs/dct/lib/python3.6/site-packages/django/contrib/admin/sites.py in has_permission, line 186 Python Executable: /home/tim/anaconda3/envs/dct/bin/python Python Version: 3.6.4 Python Path: ['/home/tim/DII/datacentrictools/tools/dct', '/home/tim/anaconda3/envs/dct/lib/python36.zip', '/home/tim/anaconda3/envs/dct/lib/python3.6', '/home/tim/anaconda3/envs/dct/lib/python3.6/lib-dynload', '/home/tim/anaconda3/envs/dct/lib/python3.6/site-packages'] Server time: Fri, 9 Mar 2018 15:34:04 +0000 Apps: INSTALLED_APPS = ( 'dal', 'dal_select2', 'dal_queryset_sequence', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django_countries', 'tastypie', 'dmgen', 'translator', ) Middleware: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) All help is appreciated. -
Iterating over both formset and other list at the same time
I am creating a form that is used for gathering movie ratings. All fields in the model are hidden except for the rating variable. The form is in the form of a formset, for creating multiple instances of form. I also want to pass values for the hidden elements in the form, which is in the form of a list of dicts. The form.py: class RecommendationQuestionsForm(ModelForm): userId = forms.IntegerField(min_value = 0) rating = forms.IntegerField(min_value = 0, max_value = 5) class Meta: model = Movies fields = ['userId','movieId','rating'] The model Movies: class Movies(models.Model): movieId = models.IntegerField(primary_key=True) title = models.CharField(max_length=90) genre = models.CharField(max_length=60) The view for the form: @login_required def recommendationquestions(request,user_id,template_name): RecFormSet = formset_factory(RecommendationQuestionsForm,extra = 7) if request.method == 'POST': #some code else: uid = user_id resp_list = MoviesRetrieval.provide_movie_choices(uid) #print(resp_list) form_and_resp = zip(RecFormSet,resp_list) return render(request, 'questions.html', {"form_and_resp":form_and_resp}) Sample of resp_list: [ { "userId": 672, "movieId": 1950, "title": "In the Heat of the Night (1967)" }, { "userId": 672, "movieId": 3741, "title": "Badlands (1973)" }, { "userId": 672, "movieId": 3959, "title": "Time Machine, The (1960)" }, { "userId": 672, "movieId": 4101, "title": "Dogs in Space (1987)" }, { "userId": 672, "movieId": 8572, "title": "Littlest Rebel, The (1935)" }, { "userId": 672, "movieId": 65230, … -
Dynamically combine Q() - OR objects
I am trying to create a dynamic search in this ListView I have. My idea is to specify the fields and the type of search each time I try to inherit this view. My problem is that every time I try to make a search, it works only on the first field of the tuple. In my example: requests__email is the first field, and when I print the object query_q after making a query for 'app', I get the following output: (OR: (AND: ), ('requests__email__icontains', 'app'), (AND: ('requests__email__icontains', 'app'), ('status__icontains', 'app')), (AND: ('requests__email__icontains', 'app'), ('status__icontains', 'app'), ('license_type__name__icontains', 'app'))) I don't understand why, because I am using the operator I thought it would work |= in query_q |= Q(**query_kwargs). If I try to make a search based on the other attributes, status for example, the search doesn't work. views.py class DefaultListView(ListView): searchable_fields = ( ('requests__email', 'icontains'), ('status', 'icontains'), ('license_type__name', 'icontains'), ) def get_queryset(self): form = self.form_class(self.request.GET) if form.is_valid(): if not self.searchable_fields: raise AttributeError('searchable_fields has not been configured.') term = form.cleaned_data['term'] query_kwargs = dict() query_q = Q() # Build a list of Q objects based on the searchable attribute for field, search_type in self.searchable_fields: query_kwargs["{0}__{1}".format(field, search_type)] = term query_q |= Q(**query_kwargs) ordering … -
django Lists are not currently supported in HTML input
Sorry for my english. I want create field, this field must contains list of files. my serializer: class FileSerializer(serializers.Serializer): file = serializers.FileField() class MySerializer(serializers.Serializer): list_files = FileSerializer(many=True, required=False) But in UI i have this text List files Lists are not currently supported in HTML input. How i can fix it? -
Django request object created by current user
I am trying to make a query where the current logged in user can view the Teams they have created. Therefore I am trying to print a list of the UserTeams where the UserID = the current user's ID. I know I need to use the 'owner' field i have created for the Teams, though I don't really know where/ what to do. Here is my view: def teamsview(request): query = UserTeams.objects.filter(userID=request.user) return render(request, 'teammanager/teams.html', { "teams": query}) My Teams and UserTeams models: class Team(models.Model): name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) def __str__(self): return self.name class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) And my HTML: {%for team in userteams%} <h3><a href='/teams/{{userteam.id}}'>{{team.name}}</a></h3> {%endfor%} -
django - prepending a field in the query set that doesn't exist in the model
I have a model that reads from a pre-existing university database. The username is stored as the students id. I'm not able to add a new column to the database in a save or I could use a save function in my model. class Student(models.Model): student_id = models.IntegerField(db_column = 'Student_ID', primary_key = True) statusid = models.IntegerField(db_column = 'StatusID') fname = models.CharField(db_column = 'Student_First_Name', max_length = 35) lname = models.CharField(db_column = 'Student_Last_Name_Formatted' , max_length = 40) class Meta: managed = False db_table = '[Student]' What i'm trying to do is take the username in a query and match it up with another field that is umich.edu/AAA#### as a primary key. I'm defining the request in one function as: def user_list(request): student = Student.objects.all() passing in the argument for students to my template with a POST to the form. In my next view that gets posted def criteria(request): user = request.POST.get('student_id') print(user) student = CourseCriteria.objects.get(universitystudentid = request.POST.get('student_id')) My print/post of user is coming through correctly as the student id, but I need to prepend umich.edu/ to the student_id in the queryset. How can I accomplish this without being able to add that field to my model? -
Iterate over a mock-patched list does not work
I'm trying to mock a Django property named next_automatic_service_days that returns a list of Date objects. Here is how I do: @freeze_time("2029-01-01") def test_create_next_services_on_monday(self): today = date.today() with patch('restaurants.models.RestaurantParameters._next_automatic_service_days', return_value=[today + td(days=i) for i in range(4)]): # Call create_next_services method here On another file: def create_next_services(self): for day in self._next_automatic_service_days: # We should enter this loop 4 times! The problem is, we never enter the loop. When I use ipdb in create_next_services, I can see _next_automatic_service_days is a magic mock, and the return value is a list of 4 items. What is wrong with my code? Thanks.