Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return XML and JSON and PDF from Django Rest Framework
having a request like this { "report": "score", "name": "CHRIS WAKE", "format": "xml" } I want to to return an XML format of the response based on the "format": "xml" parameter which can also be json or pdf. What i have now returns the XML as a string which does not show the XML tags in the preview tab of postman. This also does not work in the browse-able API version. Many thanks in advance for any assistance. -
django-s3direct file upload issue
Let me explain you the situation in brief: I am working on a django project in which I am trying to add a functionality wherein, I can upload a file directly to S3 from django-admin. For this purpose, I am using django-s3direct package. I have done all the setup as stated in the documentation. The problem I am facing is, whenever I select a file to upload, the progress-bar in the admin shows no progress and the following is the output on commandline: POST /s3direct/get_aws_v4_signature/ HTTP/1.1" 200 64 Requesting your help at the earliest. -
Django: Ajax POST to database together with Django Forms
I have a models.py and views.py file below which works together with Django Form. I would like to populate the latitude and longitude fields in models.py by posting it from Javascript/Ajax. The problem is I am not sure how to do this in the views.py(Main) file below. Could any kind soul help me with this? Thank you. models.py class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True, blank=True) description = models.TextField(blank=True) service = models.ForeignKey(Service, on_delete=models.CASCADE, blank=True, null=True) image = models.ImageField(upload_to='product', blank=True) latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) user = models.ForeignKey(User, on_delete=models.CASCADE) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def get_url(self): return reverse('shop:ProductDetail', args=[self.slug]) def __str__(self): return '{}'.format(self.name) def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Product.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) views.py (Main Version) def CreateProduct(request): error = '' if request.method == 'POST': product_form = ProductForm(request.POST, request.FILES) if product_form.is_valid(): product = product_form.save(commit=False) product.user = request.user # product.latitude = request.POST['latitude'] # product.longitude = request.POST['longitude'] product.save() products = Product.objects.filter(user=request.user) return render(request, 'shop/allproducts.html', {'products':products}) else: error = … -
Order queryset by date in descending order, but for elements which dates are less that now() order in ascending?
I have a queryset that i want to kind of split in two parts. Part one would contain objects with future dates and part two - past dates. The thing is: i need to sort two part with different order. One - descending, two - ascending. I need the output to be Queryset, not list, since I want to use filters and pagination on them. Is it possible? -
Adding permission in django not working
I have problem with my permission class - i don't know why adding permission to user don't working as i wish to. How do i like it to work -> After clicking button in site with user list he get permission to see download specific file. Class that gives permission(in views.py): class GiveBetaPermission(LoginRequiredMixin, AccountTypeRequiredMixin, RedirectView): model = BetaSoftware account_type_required = ['admin', ] url = reverse_lazy('accounts:client-list') success_message = _("Permission granted.") def get(self, request, *args, **kwargs): user = get_object_or_404(User, pk=kwargs.get('pk')) perm_name = 'softwares.view_beta' perm = Permission.objects.get( content_type=ContentType.objects.get_for_model(BetaSoftware), codename='view_beta') assert perm_name == '{}.{}'.format(perm.content_type.app_label, perm.codename) print('check before add:', user.has_perm(perm)) user.user_permissions.add(perm) user.save() user = get_object_or_404(User, pk=kwargs.get('pk')) print('check after add:', user.has_perm(perm)) return super(GiveBetaPermission, self).get(request, *args, **kwargs) Model: class BetaSoftware(models.Model): (some working download code) class Meta: permissions = ( ("view_beta","view_beta"), ) Table action code (button that gives access) {% if user.account_type == 'admin' %} {% if not softwares.view_beta %} <a href="{% url 'softwares:beta-permission' pk=record.pk %}" data-toggle="tooltip" data-placement="bottom" title="{% trans "Beta test access" %}"><i class="fa fa-fw fa-bold"></i></a> {% endif %} {% endif %} Html code which should be avaible with permission: {% if softwares.view_beta %} <div class="card mb-3"> <div class="card-header"> <i class="fa fa-table"></i> {% trans "Beta Software" %} </div> <div class="card-body"> {% if user_has_licences %} <div class="form-group row … -
Getting a key error trying to use YamJam to store my secret variables in a Django project
I am doing this on a local machine. I have yamjam installed, and my config.yaml file is located in the same folder as settings.py. Anyway, this is my code: config.yaml myproject: SECRET_KEY: 8fe_cx)(i4(oxx+k@w=_&owiy$vcmh37&2dk#)-zye--ei*9s= settings.py import os from YamJam import yamjam SECRET = yamjam()['myproject']['SECRET_KEY'] When I try to run my project, I get an error saying KeyError: 'myproject', and it references the line SECRET = yamjam()['myproject']['SECRET_KEY']. Any help? -
django add master field value to datetime field
MYSQL I have: today = django.util.timezone.now() Model Parent: X = IntegerField() Model Child: id = ForeignKey(Parent) created_date = DateTime(auto_add_now=True) Now I want to filter records with created_date__lte= created_date + id__x + today What I am doing is: child.objects.filter(created_date__lte=today+created_date+ timedelta(days=1)*F('id__x')) As suggested by: Lutz Prechelt This gives error in MYSQL as can't multiply with INTERAL as: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; .... syntax to use near '* `masters_product`.`expire_in_days`))))' at line 1") I have also tried using ExpressiongWrapper, none worked. Actual Data: (might help) Query: days = expired_in + receive_delay time = timezone.now() - timedelta(days=days) store_products = StoreProductMapping.objects\ .filter(store_id=store_id, is_published=1, is_deleted=0, created_date__lte=time + (timedelta(days=1)*F('master_product__expire_in_days'))) print(store_products.query) SQL Output: (replaced field names with * for readability) SELECT * FROM `store_storeproductmapping` INNER JOIN `masters_product` ON (`store_storeproductmapping`.`master_product_id` = `masters_product`.`master_product_id`) WHERE (`store_storeproductmapping`.`store_id` = 13 AND `store_storeproductmapping`.`is_published` = True AND `store_storeproductmapping`.`is_deleted` = False AND `store_storeproductmapping`.`created_date` <= ((2018-07-30 05:11:35.728078+00:00 + (INTERVAL '86400.000000' SECOND_MICROSECOND * `masters_product`.`expire_in_days`)))) Models: StoreProductMapping: class StoreProductMapping(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, db_index=True) master_product = models.ForeignKey(Product, on_delete=models.CASCADE, ) display_product_name = models.CharField(max_length=500) display_size = models.CharField(max_length=100) display_description = models.TextField(blank=True, null=True) last_updated_date = models.DateField(auto_now=True) last_updated = models.DateTimeField(auto_now=True) created_date = models.DateTimeField(auto_now_add=True) Product class Product(models.Model): master_product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=1000, db_index=True) size = models.CharField(max_length=100) cost_price = models.FloatField(default=1.0) … -
How to start an existing Django project?
I am a new to Django and have 0 experience with this framework. I cloned a project from git it came with requirements.txt file, but I am not sure how to run it. Do I need to create virtual environment first and clone the project into the directory of the virtual environment, and then install the requirements? Do I need to clone the project first into some folder and then create the virtual environment inside this folder and then install the requirements? Do I need to use any special IDE to run the project? I tried opening the project in PyCharm, without creating a virtual environment first, and it asked me if I want to install the requirements. I would be glad if someone could explain what is the correct way to run an already existing project. -
Django AttributeError 'datetime.date' object has no attribute 'utcoffset'
I'm a newbie in Django, so sorry if explanation of problem looks weird. I created a blog app within a Django project. models.py: from django.db import models class Blog(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() # issue appears because of this statement body = models.TextField() image = models.ImageField(upload_to='images/') When I create a new blog object in admin page of site, everything's fine and object gets created and stored to the database. But when I want to edit this blog object (clicking on it in the list of blogs), I get this error: AttributeError at /admin/blog/blog/2/change/ 'datetime.date' object has no attribute 'utcoffset' Full traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/blog/blog/2/change/ Django Version: 2.0.2 Python Version: 3.6.4 Installed Applications: ['jobs.apps.JobsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\LENOVO\Anaconda3\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 'datetime.date' object has no attribute 'utcoffset' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not … -
What is diffrence bwtween JSONResponse and JSONRenderer in Django
All I know is that JSONResponse is HttpResponse with content_type="application/JSON" And JSONRenderer will convert the python dictionary data to JSON format Do they do the same work? Or is there any difference between them -
I want to enable multi-level user authorisation in Django /admin panel
I am working on a project where a particular application(form with text data) when submitted by the user should reach the admin with/through intermediate authorizers. If a user submits a form, the middle user should accept it so that the admin can view that particular data(form). I have tried giving staff status to the middle user but it's not working the way I wanted. I have the complete project ready with models, views and forms script. I wonder if I need to write an admin model so that it works or can I help myself with the user and groups permissions in the Django admin panel. -
Django rest framework user serializer
I want to be able to get some user information through django rest framework. I'm using the default django user model, so I tried making a simple serializer and viewset, but I'm getting an error. Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. My code (currently just in my global views.py file. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @action(methods=['get'], detail=False) def username(self, request): queryset = User.objects.get(request.user.id) serializer = self.get_serializer(queryset, many=False) return Response(serializer.data) router.register(r'^api/user', UserViewSet, 'user') -
Django: form.html action can't find the desired page
I have a Django project with a folder polls. Under polls, there are views.py and urls.py. They look like: polls/views.py: def index(request): return render(request, 'form.html') def search(request): return HttpResponse("You're at the polls search.") and polls/urls.py: from django.urls import path from . import views from django.conf.urls import include, url urlpatterns = [ path('', views.index, name='index'), path('search', views.search, name='search'), ] and templates/form.html looks like: <form method="POST" action="/search"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Upload text</button> </form> I started from http://127.0.0.1:8000/polls which began at the index function, correctly went to the form.html. However, in the form.html, it can't get back to the search function defined in the polls/view.py. The error is like: I then changed the form.html to: <form method="POST" action="polls/search"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Upload text</button> </form> Then I got the following error: What did I do wrong here and how can I get to the search function under polls/views.py ? Thanks! -
Django, viewing uploaded files and videos.
I would like to be able to view my uploaded files. I really have poor grasp of what I am doing. views.py def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) else: form = DocumentForm() return render(request, 'learning_logs/model_form_upload.html', {'form':form}) def file_preview(request): videos = Document.objects.all() context = {'videos':videos} return render(request, 'learning_logs/video.html', context) models.py class Document(models.Model): docfile = models.FileField(upload_to = 'documents/') upload_at = models.DateTimeField(auto_now_add = True) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['docfile'] I have uploaded videos and pictures. As the files are passed onto the HTML, I can only see the names of the files I uploaded. I can't click on the links and view the files. I would like to have an actual video player to play the videos, or view the pictures. -
NOT NULL constraint failed: history.user_id
I am new to Django and I am trying to learn by practicing with some project but I am stuck with this problem, I want to return the information of the History model to the authenticated user according to its id_user. The problem appears when the user gives the submit of the form. The message that he gives me is this: NOT NULL constraint failed: history.user_id models.py from django.db import models from django.contrib.auth.models import User class History(models.Model): DAY35 = '35 days' DAY45 = '45 days' HISTORY_DAYS = ( (DAY35, '35 days'), (DAY45, '45 days'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.FloatField(default=10) days = models.CharField( max_length=7, choices=HISTORY_DAYS, default=DAY35, ) def is_upperclass(self): return self.days in (self.DAY35, self.DAY45) views.py from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView from .forms import HistoryForm from .models import History @method_decorator(login_required, name='dispatch') class HistoryCreate(CreateView): model = History fields = ['amount', 'days'] success_url = reverse_lazy('history') form_class = HistoryForm forms.py from django import forms from .models import MiningHistory class HistoryForm(forms.ModelForm): class Meta: model = History fields = ['amount', 'days'] widgets = { 'amount': forms.NumberInput(attrs={'class':'x', 'placeholder':'0.00'}), 'days': forms.Select(attrs={'class':'x'}), } -
i have deployed Django project in Heroku.where users can upload images shows up for some hours after some hours images gets dont showup in screen
i have deployed my project in Heroku.what happens is i have form where users can upload files(images) which is reflected back to pages after being uploaded problem is those uploaded images shows on page for some hours and then images gets dont showup in screen after some hours. but again wen some users fill up the form a upload the images ,it shows up in the screen but rest of the previously uploaded images dont show up .in this newly uploaded image also disappears after some hour . also every time i do git push heruko masters those images disappears. you can visit the site(http://productpanditapp.herokuapp.com/) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATICFILES_DIRS = [ os.path.join(BASE_DIR,'producthunt/static/') ] STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') url = models.TextField() votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def short_pub_date(self): return self.pub_date.strftime('%b %e %Y') views.py def home(request): products = Product.objects.all().order_by("-pub_date") query = request.GET.get("q") if query: products= products.filter(Q(title__icontains=query)| Q(body__icontains=query)| Q(hunter__username__icontains=query)).distinct() paginator = Paginator(products, 5) # … -
Django url page not found
So I have been trying to access a project post that I have created for my website, but every time I click on it the url can't be found. I am not sure why. My code is below: mywebsite/urls.py from django.contrib import admin from django.urls import re_path, include from django.conf import settings from django.conf.urls.static import static #re_path(r'^admin/', admin.site.urls), urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^', include('home.urls')), re_path(r'^projects/', include('projects.urls', namespace="create_post")), re_path(r'^contact/', include('contact.urls')), ] projects/urls.py from django.urls import re_path, include from . import views # urls for projects page app_name = 'create_post' urlpatterns = [ re_path(r'^$', views.retrieve_projects, name="retrieve_projects"), #re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"), re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"), re_path(r'^(?P<slug>[\w-]+)/$', views.details_of_project, name="details_of_project"), re_path(r'^(?P<slug>[\w-]+)/update/$', views.update_projects, name="update_projects"), re_path(r'^(?P<slug>[\w-]+)/delete/$', views.delete_projects, name="delete_projects"), ] # To make images work if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) projects/views.py # Function to retrieve all different projects def retrieve_projects(request): # Retrieves objects based on latest publish date projects_list = Projects.objects.all().order_by("-publish_date") context = { 'projects_list': projects_list, } return render(request, 'projects/projects.html', context) projects/projects.html <h1>asdasdasdasdasdasdas</h1> {% if projects_list %} <ul> {% for project in projects_list %} <h2><a href="/{{project.slug}}/">{{project.title}}</a></h2> <h2>{{project.description}}</h2> <h2>{{ project.publish_date }}</h2> {% endfor %} </ul> {% endif %} The error returns page not found -
How to make a function auto run in django.
i want to set up a function auto run every day in django . it was be send a request to api/day. please help me! thankyou so much! def get_data(){ } this is function i want it run only one per day. -
Django Form is not saving to my db?
I am newbie and after reading documentation of django . i made forms but my form is not saving to my db and not showing in my db . please help me i tried so many ways but still its not saving . i have drivers for this purpose i want to register them .. Views.py def driver_form(request): args = {} template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")#sir this ? return render(request, template_page, args) def driver_save(request): args = {} if request.POST: driver_firstname = request.POST.get('driver_firstname') driver_lastname = request.POST.get('driver_lastname') driver_save_form = DriverForm(request.POST) if driver_save_form.is_valid(): new_driver = driver_save_form.save(commit=False) new_driver.driver_firstname = driver_firstname new_driver.driver_lastname = driver_lastname new_driver.save() template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html") return render(request, template_page, args) else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') rentacar_driver_form <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div class="container"> <form method="POST" action="/rentacar/driver-save/"> {% csrf_token %} <label> First Name<br> <input type="text" name="driver_firstname" required> </label> <br> <label> Last Name<br> <input type="text" name="driver_lastname" required> </label> <br> <input type="submit" class='btn btn-primary' value="Submit"> </form> </div> </body> </html> -
Django-paypal never calls valid_ipn_received
I am trying to integrate django-paypal to my website and I can't seem to make the valid_ipn_received to work. mainApp/urls.py urlpatterns = [ path('paypal/', include('paypal.standard.ipn.urls')), ] mainApp/settings.py INSTALLED_APPS = [ ... 'paypal.standard.ipn', 'payment.apps.PaymentConfig' ... ] PAYPAL_RECEIVER_EMAIL = "---" PAYPAL_TEST = True payment/apps.py from django.apps import AppConfig from paypal.standard.ipn.signals import valid_ipn_received class PaymentConfig(AppConfig): name = 'payment' def ready(self): from .hooks import payment_received valid_ipn_received.connect(payment_received) payment/hooks.py @csrf_exempt def payment_received(sender, **kwargs): ipn_obj = sender try: invoice = models.Invoice.objects.get(pk=ipn_obj.invoice) except: return if ipn_obj.payment_status == ST_PP_COMPLETED: # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != utils.get_paypal_buisness_email(): invoice.status = models.Invoice.CANCELED invoice.save() return price = invoice.amount if ipn_obj.mc_gross == price and ipn_obj.mc_currency == 'CAD': invoice.status = models.Invoice.DONE else: invoice.status = models.Invoice.CANCELED invoice.save() else: invoice.status = models.Invoice.CANCELED invoice.save() Code when creating the paypal form paypal_dict = { "business": utils.get_paypal_buisness_email(), "amount": invoice.amount, "item_name": "Registration Fees", "invoice": str(invoice.pk), "currency_code": "CAD", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('payment:done')), "cancel_return": request.build_absolute_uri(reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) utils.get_paypal_buisness_email() returns the buisness email as a string. When I see that the sever receives a POST from Paypal but nothing happens after … -
Django 2.1 model managers missing in action
I have defined a recursive model and a custom manager or two to contain some of the interesting tree exploring methods. I've recently updated to Django 2.1, Python 3.6. # models.py class ParentManager(models.Manager): def get_queryset(self, pk=None): qs = super().get_queryset() def parent(parent_list): """ given a brainstorm object that responds to something (mainly if user clicks a header) it returns the upstream brainstorm object it responds to """ if parent_list[0].responds_to: parent_list.insert(0, qs.get(pk=parent_list[0].responds_to.pk)) parent(parent_list) return parent_list if pk: parent_list = [qs.get(pk=pk), ] parent(parent_list) pk_list = [item.pk for item in parent_list] return qs.filter(pk__in=pk_list) else: return qs class Demand(models.Model): name = models.CharField(max_length=150) reference = models.CharField(max_length=150) parent = models.ForeignKey('self', related_name='child', null=True, blank=True, on_delete=models.DO_NOTHING) counterpart = models.ForeignKey('Supply', null=True, blank=True, on_delete=models.DO_NOTHING) demands = models.Manager() parents = ParentManager() children = ChildManager() def get_absolute_url(self): _qs, pk_list = Demand.parents.get_queryset(pk=self.pk) return 'demand/' + "-".join(pk_list) def __str__(self): return self.name Trying to get a simple ListView of the two test 'Demands' I've created in the admin, I am getting the error 'Demand has no attribute 'demands.' It was the same with 'objects' and I get the same error with my custom objects. # views.py class DemandList(ListView): """Django generic listview of available Demands within a project""" template_name = 'forcedesign/ListView.html' model = Demand context_object_name = 'demand_list' … -
Bokeh plot update in notebook but not in static HTML
This is the first time to ask a question here . I'm totally new to HTML , CSS , JavaScipt , Django , Python and Bokeh . I'm poor in English . And I'll appreciate for your help . I meeting a problem when I want to realize a simple function . There is 2 plots here . When I click the circle of the first plot , the circles not associated with will be hidden . It's work in notebook . But when I add it into an HTML page . The second plot won't Change . I use Django+python to realize this function . And I use HTML component tag to add plots into an web page. I'm sorry that I'm not allow to put a picture here, but there are links. Here is the gif when it works in notebook . workrightinnotebook And this is the gif when it's not work in static HTML . notwork Here is the HTML code . <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <link href="https://cdn.pydata.org/bokeh/release/bokeh-0.13.0.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.13.0.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.pydata.org/bokeh/release/bokeh-tables-0.13.0.min.css" rel="stylesheet" type="text/css"> <script src="https://cdn.pydata.org/bokeh/release/bokeh-0.13.0.min.js"></script> <script src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.13.0.min.js"></script> <script src="https://cdn.pydata.org/bokeh/release/bokeh-tables-0.13.0.min.js"></script> </head> <body> {{ script2 |safe }} {{ div2 |safe … -
How to redirect http url to https for django application served by Apache
What I want to achieve is when I browse for http://example.com:8080 it gets redirected to https://example.com:8080. My web application is written in Django, and I have the following line in my settings: SECURE_SSL_REDIRECT = True The httpd configuration for example.com looks like this: LISTEN 8080 <VirtualHost *:8080> ServerName example.com SSLEngine on SSLCertificateFile /path_to_cer SSLCertificateKeyFile /path_to_key SSLCertificateChainFile /path_to_iterm.cer RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} Alias /static /path_to_mysite/static <Directory /path_to_mysite/static> Require all granted </Directory> <Directory /path_to_mysite_wsgi_dir> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/path_to_mysite:/path_to_mysite_python_packages display-name=%{GROUP} WSGIProcessGroup mysite WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /path_to_mysite_wsgi.py </VirtualHost> with these configurations when I browse http://example.com, I will get the following error: Bad Request Your browser sent a request that this server could not understand. Reason: You're speaking plain HTTP to an SSL-enabled server port. Instead use the HTTPS scheme to access this URL, please. any thoughts? -
How to create a user in django without using django's signup form?
I have a signup page which is built out of HTML, CSS and Bootstrap.It also handles basic checks like password match and email validation.It contains the fields username, password, conf_password, first_name and last_name (Everything that django's User model provides by default). I need to create a user which uses django's User model by using the fields provided by the signup page.Here is what I do from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.contrib.auth import login, logout, authenticate @csrf_exempt def signup_users(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') check_username = User.objects.filter(username=username) if check_username: return "Failure" User.objects.create_user(username=username, password=password, first_name=first_name, last_name=last_name) user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('/') else: return render(request, 'signup.html') Ideally this should work since I am not providing any extra field that django that django's default User model doesn't have.This stackoverflow question confirms the same Django error: create_user() takes at least 2 arguments (3 given) But I get the below error ERROR 2018-08-16 01:17:51,877 django.request Internal Server Error: /signup Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", … -
Error when trying to generate a URL with slugs/string variables that are in different urlpatterns lists
When I load the page that uses the context from GroupDetailView and the template from group_detail.html (the code is below), I get this error: NoReverseMatch at /group/professional/ Reverse for 'create_profile' with keyword arguments '{'slug': 'professional', 'noun': 'profile'}' not found. 1 pattern(s) tried: ['group\/(?P<slug>[-\w]+)/$create_(?P<noun>[-\w]+)/$'] Notice that the keyword arguments have values and both keys are in the pattern that Django tried. urls.py from . import views from profile import views as profile_views app_name = 'group' group_patterns = ([ path('', views.GroupDetailView.as_view(), name='group_detail'), re_path(r'^create_(?P<noun>[-\w]+)/$', profile_views.profile_create_view, name='create_profile'), ]) urlpatterns = [ re_path(r'^(?P<slug>[-\w]+)/$', include(group_patterns)), ] Notice that slug and noun are in two different lists. I tried to put slug and noun into the same re_path function and it works fine but I can't do that because I need them to stay separated. views.py class GroupDetailView(DetailView): model = Group template_name = group_detail.html def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) group_slug = self.kwargs['slug'] context['group'] = group_slug return context group_detail.html template <a role="button" href="{% url 'group:create_profile' slug=group noun='profile' %}">Create New Profile</a> Is there a way Django can realize that the keyword arguments, in fact, do match the pattern it tries when the slugs/strings are in two different url lists? Or, is there any extra code I can use …