Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible in Django admin to make a model out of an intermediate table and create a one to one relationship with another model?
I have 2 tables that have a many to many relationship. I want to know if it is possible for me to make a model out of it and then create a one to one relationship out of it with another model. What I want to do is to have this model from the intermediate table display its fields in a list display together with the fields of the other model where it has a one to one relationship. -
Django-Filter returns return the request object
I was trying to dynamically filter the queryset in Django using Django-filters library in DRF but the filters send the response exactly as the same to request ie if i choose mode = transfer the response is { "data": { "mode": "transfer" } } the filterset_class is defined in the views and queryset is passed on to it along with the request type. views.py from .filters import DataFilter def get(self, request): query_set = ModelName.objects.all() queryset_filter = DataFilter( request.GET, queryset=query_set) return Response({"data": queryset_filter.data}, status=status.HTTP_200_OK) filters.py from django_filters import rest_framework as filters from .models import ModelName from common.models import MODE_CHOICES class DataFilter(filters.FilterSet): currency = filters.ModelMultipleChoiceFilter(lookup_expr='iexact') coin_type = filters.ModelMultipleChoiceFilter(lookup_expr='iexact') mode = filters.ModelChoiceFilter( lookup_expr='iexact', choices=MODE_CHOICES) max_amount = filters.NumberFilter( field_name='price', lookup_expr='gt') min_amount = filters.NumberFilter( field_name='amount', lookup_expr='lt') class Meta: model = ModelName fields = ('currency', 'coin_type', 'mode', 'max_amount', 'min_amount') The django-filters documentation suggests django-filter backend can be used by default by adding it to the DEFAULT_FILTER_BACKENDS. Is there some configuration that i am missing or something -
i am importing news api in my django project i can print it data in my terminal but i can't print in my html template
I am importing news api in my Django project.my can print my data in my terminal but can't print through my news.html i have something problem in importing the data in html.I need some help to get it. from django.shortcuts import render import requests def news(request): url = ('https://newsapi.org/v2/top-headlines?' 'sources=bbc-news&' 'apiKey=647505e4506e425994ac0dc310221d04') response = requests.get(url) print(response.json()) news = response.json() return render(request,'new/new.html',{'news':news}) this base.html <html> <head> <title></title> </head> <body> {% block content %} {% endblock %} </body> </html> news.html {% extends 'base.html' %} {% block content %} <h2>news API</h2> {% if news %} <p><strong>{{ news.title }}</strong><strong>{{ news.name}}</strong> public repositories.</p> {% endif %} {% endblock %} This my terminal output with my API output System check identified no issues (0 silenced). November 28, 2018 - 12:31:07 Django version 2.1.3, using settings 'map.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. {'status': 'ok', 'totalResults': 10, 'articles': [{'source': {'id': 'bbc-news', 'name': 'BBC News'}, 'author': 'BBC News', 'title': 'Sri Lanka defence chief held over murders', 'description': "The country's top officer is in custody, accused of covering up illegal killings in the civil war.", 'url': 'http://www.bbc.co.uk/news/world-asia-46374111', 'urlToImage': 'https://ichef.bbci.co.uk/news/1024/branded_news/1010/production/_104521140_26571c51-e151-41b9-85a3-d6e441f5262b.jpg', 'publishedAt': '2018-11-28T12:12:05Z', 'content': "Image copyright AFP Image caption Adm Wijeguneratne denies the charges Sri Lanka's top military … -
Django 2.1.3 reset password link not displaying
After upgrading to Django 2.1.3, I noticed the "Forgotten your password or username?" link was missing from the admin login page. After some investigating, I found the that the django.contrib.auth.urls.py module used the name password_reset for the reset url, while in the django/contrib/admin/templates/admin/login.html template the url was named admin_password_reset: django.contrib.auth.urls.py (line 16) path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), django/contrib/admin/templates/admin/login.html (starting at line 54) {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} When I changed admin_password_reset to password_reset in Django's login.html, the link showed up on the login page and worked as expected. In my urls.py I have: path('lodging/', include('django.contrib.auth.urls')), My project has no other modifications to the authentication system. Is this a bug or am I missing something? -
"python social auth" adding a backend
I'm trying to add a new social backend based on the python social auth library but when I click my "Login with X" or "Sign up with X" button it always redirects me back to the login page without logging in. The ACCESS_TOKEN_URL is never called. I wrote the following as new social backend: class xOAuth2(BaseOAuth2): name = 'x' API_URL = 'http://localhost:8000/api/' AUTHORIZATION_URL = 'http://localhost:8000/' ACCESS_TOKEN_URL = 'http://localhost:8000/api/login/oauth/access_token' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ',' REDIRECT_STATE = False STATE_PARAMETER = True def get_user_details(self, response): return {'username': response['username'], 'email': response['email'], 'fullname': response['fullname'], 'first_name': response['first_name'], 'last_name': response['last_name']} def user_data(self, access_token, *args, **kwargs): user_info = self.get_json('http://localhost:8000/api/oauth/resources?access_token=' + format(access_token)) return user_info and class xAuthBackend(SocialAuthMixin, xOAuth2): auth_backend_name = "X" def get_verified_emails(self, *args: Any, **kwargs: Any) -> List[str]: access_token = kwargs["response"]["access_token"] try: emails = self._user_data(access_token, '/emails') except (HTTPError, ValueError, TypeError): emails = [] verified_emails = [] for email_obj in emails: if not email_obj.get("verified"): continue if not email_obj.get("primary"): continue verified_emails.append(email_obj["email"]) return verified_emails def user_data(self, access_token: str, *args: Any, **kwargs: Any) -> Dict[str, str]: return super().user_data( access_token, *args, **kwargs ) I'm using a custom written IdP, which has the following code for exchanging a auth token for an access token: public function generate_access_token(Request $request){ $auth_token = $request->get('code'); $x_user = … -
Django: admin.site.site_header set, but not visible for own pages
I set admin.site.site_header = 'Fooo' like explained in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite.site_header This works very nice for all normal admin-pages. I have an additional (custom) page which I want to look like the admin page. I use {% extends 'admin/base_site.html' %} in my template. On this page site_header 'Fooo' is not displayed. The normal/default django string is visible. What am I doing wrong? -
How to get existing values from the database into the django model field for django admin
I need help to get existing questions from the field question_name into the field dependent_question (with dropdown) from the Questions model class. It will help user to select dependent question when they add any new question from django admin panel. # model.py class Questions(models.Model): question_id = models.AutoField(primary_key=True) question_name = models.CharField(max_length=300) dependent_question = models.CharField(max_length=300,blank=True, null=True) -
django SMTPServerDisconnected using gmail account
Can you please me I have tried this code but unfortunately its not working Having Error : SMTPServerDisconnected at / Connection unexpectedly closed: [Errno 104] Connection reset by peer Setting.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'shabbirfast@gmail.com' EMAIL_HOST_PASSWORD = '*****' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Views.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from django.http import HttpResponse def sendemail(request): subject = 'Test Mail' message = 'This is an automatic massage HELLO from django.' email_from = settings.EMAIL_HOST_USER recipient_list = ['shabbir@xcodes.net'] try: send_mail(subject, message, email_from, recipient_list,fail_silently=False) return HttpResponse("SEND Confirm") except Exception as e: raise e -
Django template default filter with nullable boolean values
I need to pass a boolean variable to a template. To convert it to js boolean you usually do: {{ boolval|yesno:'true,false' }} Now my boolvar may not exist. In that case I need it to default to true, so I am trying this: {{ boolval|default_if_none:'true'|yesno:'true,false' }} Unexpectedly, the result of this is false. I am trying to debug what {{ boolval|default_if_none:'true' }} produces but I am getting syntax errors. Not sure what's going on, but it is definitely not producing true. How can I achieve with filters the behavior I'm after? -
Hitting an API from Django admin Panel
In Django admin Panel. I have a model which has fields like userID, name, status. I want to call an API (e.g:- www.xyx.com?user=userID&status='approved') when status="approved" is selected and click on save button. -
Which apache modules are necessary when running Django application via mod_wsgi?
We are running Django application behind Apache using mod_wsgi. We also need to serve HTTPS requests. Are the following modules sufficient ? mod_alias.so mod_authz_host.so mod_deflate.so mod_mime.so mod_negotiation.so mod_rewrite.so mod_wsgi.so -
Which approach is better in Django Jsonfield or ForeignKey?
Such a question, I want to create a price comparison site, there are two ideas how to implement a list of prices from different stores. First via ForeignKey class Price(models.Model): price = models.DecimalField() shop = models.CharField() class Product(models.Model): name = models.CharField(max_length=255) prices = models.ForeignKey() JSONfield second method class Product(models.Model): name = models.CharField(max_length=255) data = JSONField() """ Product.objects.create(name='product', data={'price': 999, 'shop': 'Amazon.com'} def __str__(self): return self.name If anyone has experience, what works faster and more reliable if a large number of goods? Thanks for the early ones. -
Trigger a modal on django form submit
I have a series of Django forms and formsets that are connected together in a series of steps. When the final form step is submitted a celery task is started to create an entity based on all the information provided. The way this is currently working, is that the final form is submitted (and the task starts) and then redirects to a page which lets the user know that the entity is being created and then redirects once this is complete. However, I now want to have this loading page show up as a modal on the previous page, rather than show on an entirely new page. I have previously been doing this almost solely in Django. When I submit the final form the form_valid looks like this (I am using django-extra-views to make formsets so it is slighlty different from normal): def forms_valid(self, form, inlines): self.object = form.save() models.ActivityBaseNext.objects.create( activity_base=self.activity_base, order=self.activity_base.get_next_next_step_order(), activity_configure=self.object, ) for formset in inlines: formset.save() transaction.on_commit( tasks.activity_configure.s( id=self.object.pk, ).delay ) return HttpResponseRedirect(self.object.get_current_next_url()) which causes the redirect to the loading page, which looks like so: class ActivityConfigureStatus(LoginRequiredMixin, DetailView): model = models.Activity template_name = 'alert.html' title = 'Create Activity' display_text = 'Importing activity data' refresh_secs = 1 def … -
django-threadlocals stopped working upgrading from django 1.11 to django 2.1.3
I'm trying to upgrade for a project the django framework from 1.11 to 2.13. The project depends on django-threadlocals. (https://github.com/benrobster/django-threadlocals). After upgrade, request is not set by threadlocals middleware anymore so any call to threadlocals.get_current_user() threadlocals.get_current_request() returns None Did not find any issue on github Have you any hints? I'm running python 3.5.2 -
Django: When I delete item from one of the user's shopping cart, that same item gets deleted from every user's shopping cart
Using python 3.7 When I add item to the cart, the item gets added individually to each user, but I have delete button on the cart details page and the function in views.py looks like this: def delete_cart_item(request, item_id): user_profile = get_object_or_404(User_Profile, user=request.user) shopping_cart = user_profile.shopping_cart_set.first() item = shopping_cart.items.get(pk=item_id) item.delete() return redirect('Sales:cart_details') Those are my models: class User_Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.IntegerField() item_description = models.CharField(max_length=300) item_bought_price = models.IntegerField() stock_level = models.IntegerField() restock_level = models.IntegerField() class Cart_Item(models.Model): item = models.OneToOneField(Item, on_delete=models.SET_NULL, null=True) class Shopping_Cart(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(User_Profile, on_delete=models.SET_NULL, null=True) items = models.ManyToManyField(Cart_Item) What is the issue here? I tried changing on_delete=models.SET_NULL of Cart_Item to on_delete=models.CASCADE but that didn't seem to change anything. There also is a weird issue that when the cart is empty and I add the first item, that item cannot be deleted from the page, I can delete it from shell though. -
Django : Issue with MultiValueDictKeyError with download function
I would like to get your help in order to improve my code and get the possibility to download document thanks to 2 different ways. Explanations: The first method let to check some documents and user has to fill an email field. Once it done, a modal appears with pre-filled fields according to previous email address because a queryset is executed with a filter on email adress This is the main process to download documents. The second method is different. I generate an unique hyperlink with the document id in the url. But through this way, I don't need the email address as previously. My codes: This is my model.py file : class Document(models.Model): code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False) language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False, blank=False) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False, blank=False) title = models.CharField(max_length=512, verbose_name=_('title'), null=False, blank=False) publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents') upload = models.FileField(upload_to='media/files/', validators=[validate_file_extension], verbose_name=_('document file'), null=False, blank=False) class Meta: verbose_name = _('document') verbose_name_plural = _('documents') class Customer(EdqmTable): email = models.EmailField(max_length=150, verbose_name=_('e-mail'), null=False) first_name = models.CharField(max_length=70, verbose_name=_('first name'), null=False) last_name = models.CharField(max_length=70, verbose_name=_('last name'), null=False) country = models.ForeignKey(Country, verbose_name=_('country')) institution = models.CharField(max_length=255, verbose_name=_('institution'), null=True) class Meta: verbose_name = _('customer') verbose_name_plural = _('customers') def … -
Deploying Seprate React Frontend and Django DRF API
I have a react frontend made with create-react-app to deploy a production build of this I just do npm run build. My app uses a Django Rest FrameWork API backend. How can I setup the app for deployment on a single server. Is there a way I can store the React Frontend and route to it in Django and have requests from the Frontend hit a api/ view or endpoint. What are the best strategies for deploying something like this or is it better to host the Frontend and Backend desperately on different servers? -
how to make sure my django app1 url is not accessible by app2
My problem is I have a app called guardian, which has login, register features. Now there is another app called tutor, which also has the same. and when I login to guardian it automatically logs in tutor app also. -
How to change Django content based on different templates
I created a model to handle templates in Django, different templates, now the issue is that how do I serve different content in the html tags using Django context since the p tags and div tags content for each template are different using context processing -
Django rendering multiple images using inlineformset
A django newbie here, I am trying to enable uploading multiple images in one classified post. I am using a generic class-based view, CreateView, but the formset for images are not rendered in my html, only the ClassifiedForm and the submit/publish button. Note this is a duplicate for this question but it was not answered. My files are like this (Just the important parts, I have skipped some code chunks). models.py class Classified(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODE, on_delete=models.SET_NULL) timestamp = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255, null=False) content = models.CharField(max_length=1000) class ClassifiedImages(models.Model): classified = models.ForeignKey(Classified, default=None,\ on_delete=models.CASCADE, related_name='classified_images') images = models.ImageField(upload_to=get_image_filename, verbose_name='Image') forms.py class ClassifiedForm(forms.ModelForm): class Meta: model = Classified fields = ["title", "content"] ImagesFormSet = inlineformset_factory(Classified, ClassifiedImages, fields =["images"], extra=5) I just think this views.py is wrong but it goes like this class CreateClassifiedView(CreateView): model = Classified message = _("Your classified has been created.") form_class = ClassifiedForm template_name = 'classifieds/classified_create.html' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) images_form = ImagesFormSet() return self.render_to_response( self.get_context_data(form=form, images_form=images_form )) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) images_form = ImagesFormSet(self.request.POST) if (form.is_valid() and images_form.is_valid()): return self.form_valid(form, images_form) else: return self.form_invalid(form, images_form) def … -
How to test excel file upload in django
I've written a view which handles the excel file upload, now I'm trying to write unit test for the business logic but I'm stuck on excel file mocking. can someone help me with that? -
Django UNIQUE constraint
Django UNIQUE constraint failed error django.db.utils.IntegrityError: UNIQUE constraint failed while I am using the unique together constraint in the models. How can I use it properly? -
Value not getting saved in django model
I have made two models which are as follows: class itemsSearched(models.Model): searched_items = models.CharField(max_length=120) def __str__(self): return self.searched_items class VisitorInfo(models.Model): user_id = models.CharField(max_length=120) items_searched = models.ManyToManyField(itemsSearched,blank=True) I want to save value tshirt in visitorInfo model. Here is the view for this def get_req(request): event = request.GET['e'] if event == 'pv': x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') check_user(request,ip) elif event == 'pp': visitor = VisitorInfo.objects.get(user_id=request.GET['duid']) visitor.active = True print(visitor.active) visitor.save() elif event == 'ue': u_id = request.GET['duid'] tz = request.GET['tz'] url = request.GET['url'] link = request.GET['ue_pr'] #ue_pr is the property of unstructured event of the type json. o = json.loads(link) print(o) if(o['data']['data']['elementId']=='nf-field-1'): name = o['data']['data']['value'] print("Name: "+ name) visitor= VisitorInfo.objects.get(user_id=u_id) visitor.name = name visitor.save() elif(o['data']['data']['elementId']=='s'): searched_item = int(o['data']['data']['value']) print("Searched: "+ searched_item) #6 print("Type of searched_item " + type(searched_item)) #7 visitor= VisitorInfo.objects.get(user_id=u_id) visitor.items_searched.add(searched_item) visitor.save() For the sake of clarity I printed 'o' which is a python dictionary parsed from json.Here is the what i have got {'schema': 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0', 'data': {'schema': 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0', 'data': {'formId': 'FORM', 'elementId': 's', 'nodeName': 'INPUT', 'type': 'search', 'elementClasses': ['search-field'], 'value': 'tshirt'}}} I want to save the value 'tshirt' in visitor info but i am getting the following error. Traceback (most recent call last): … -
importing csv in djang
i am trying to import csv file into db from manage.py shell but it is giving me error import csv with open(r"C:\Users\yousa\Desktop\xp\exp\Dist_Extended_TissuesWise_ClusteredAnnotated_21nov2018_qaz.csv", 'r') as f: reader = csv.reader(f) lines = list(reader) del lines[0] objects = [] for line in lines: obj =Maize_clustert() obj.chromosome = int(line[0]) obj.cluster_start = int(line[1]) obj.cluster_end = int(line[2]) obj.strand = line[3] obj.pac = int(line[4]) obj.pac_suppoort = int(line[5]) obj.cluster_support = int(line[6]) obj.region = line[7] obj.gene_id = line[8] obj.transcript_id = line[9] obj.distance = line[10] obj.transcript_code = line[11] obj.gene_cord = line[12] obj.utr_length = int(line[13]) obj.gene_biotype = line[14] obj.cluster_size = int(line[15]) obj.number_pas = int(line[16]) obj.zygote = int(line[17]) obj.sperm = int(line[18]) obj.egg = int(line[19]) obj.root = int(line[20]) obj.embryo = int(line[21]) obj.basal = int(line[22]) obj.ear = int(line[23]) obj.apical = int(line[24]) obj.ovule = int(line[24]) objects.append(obj) Maize_clustert.objects.bulk_create(objects) while runnig this code in manage.py shell it give me result Traceback (most recent call last): File "<input>", line 8, in <module> NameError: name 'Maize_clustert' is not defined while in models.py i have created full model of my data is there any alternative way or i am doing it wrong kindly help me in it -
Django filter - Multiple value
so a have little problem: genres = (x, y, z,...) search = Movie.filter(Q(genres=x) | Q(genres=y| ...) I can filter by that in django and have in one variable like this but i dont know how many variables will genres have. So it is possible to that at all?